diff --git a/.gitignore b/.gitignore index 2272888..64b2364 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ build/bin/ /Desktop-App/bin/ /Desktop-App/frontend/dist/* !/Desktop-App/frontend/dist/.gitkeep +/Web-Clipper/dist/ # PocketBase local data pb_data/ diff --git a/Database/pb_migrations/1764300000_calendars.js b/Database/pb_migrations/1764300000_calendars.js new file mode 100644 index 0000000..a09a978 --- /dev/null +++ b/Database/pb_migrations/1764300000_calendars.js @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Calendars (Phase F, ADR-16): a person's read-only calendar subscriptions, +// an iCalendar feed (ICS, webcal, Google's secret address) or a CalDAV +// account. Their events show on that person's journal pages. The password is +// sealed with the server secret. Events are not stored: the server reads +// them from the source and keeps them in memory for a while. + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + app.save( + new Collection({ + type: "base", + name: "calendar_accounts", + fields: [ + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "name", type: "text", required: true, max: 80 }, + { name: "kind", type: "select", required: true, maxSelect: 1, values: ["ics", "caldav"] }, + { name: "url", type: "text", required: true, max: 2000 }, + { name: "username", type: "text", max: 200 }, + { name: "secret", type: "text", max: 2000 }, + { name: "color", type: "text", max: 20 }, + { name: "enabled", type: "bool" }, + { name: "last_sync", type: "date" }, + { name: "last_error", type: "text", max: 500 }, + { name: "events", type: "number" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE INDEX idx_calendar_accounts_user ON calendar_accounts (user)"], + }), + ); + }, + (app) => { + app.delete(app.findCollectionByNameOrId("calendar_accounts")); + }, +); diff --git a/Docs-Site/guide/configuration.md b/Docs-Site/guide/configuration.md index 43a0db1..076310a 100644 --- a/Docs-Site/guide/configuration.md +++ b/Docs-Site/guide/configuration.md @@ -31,12 +31,12 @@ Docwell's collections in it when it starts. Change the image with `DB_IMAGE`. | `DOCWELL_ADMIN_NAME` | `Admin` | The display name of that account. | | `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. | | `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index and the AI vectors (`ai.db`). Both are rebuilt from the database when missing, so a volume is optional but makes restarts faster (and saves embedding every page again). | -| `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers. Without it, a key derived from `DOCWELL_PB_PASSWORD` is used; changing whichever is in use means entering the provider keys again. | +| `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers and the passwords of people's calendars. Without it, a key derived from `DOCWELL_PB_PASSWORD` is used; changing whichever is in use means entering the keys and passwords again. | | `DOCWELL_MEDIA_URL` | — (`http://media:8090` in the compose stacks) | docwell-media, which cuts recordings over 25 MB into pieces for transcription with ffmpeg. Blank: the server uses its own ffmpeg if it has one (the all-in-one image does), and otherwise cuts only MP3 and WAV. If docwell-media cannot be reached, the server falls back the same way. | | `DOCWELL_MEDIA_TOKEN` | — | Shared secret between docwell-server and docwell-media; set the same value on both, or leave both blank. | | `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. | | `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. | -| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, and the AI providers of workspaces, call loopback and link-local addresses. For development only (AI providers set up in the admin panel may always use local addresses). | +| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, people's calendars, and the AI providers of workspaces, call loopback and link-local addresses (private networks are always allowed, so a CalDAV server on your LAN works). For development only (AI providers set up in the admin panel may always use local addresses). | ### PocketBase settings diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index 8b1b849..8604612 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -172,6 +172,20 @@ space that only you see, workspace admins included. The week strip above a journ marks days that already have a page. In read mode, clicking a date in any page opens that day's journal. Pick the page new journal pages start from in the Info panel, under **Journal**; any page marked as a template can be used. +### Calendars on journal pages + +In **Account settings → Calendars**, subscribe to your calendars; their events for the day are listed at the top of +each journal page, in your time zone. Only you see them, and Docwell only reads them. + +- **iCal feed:** any `.ics` or `webcal://` address. For Google Calendar, use the calendar's **Secret address in iCal + format** (Settings → the calendar → Integrate calendar); for Outlook, publish the calendar and use its ICS link. +- **CalDAV account:** your server's address (for Nextcloud `https://cloud.example.com/remote.php/dav`, for iCloud + `https://caldav.icloud.com` with an app-specific password) with your user name and password; Docwell reads every + event calendar of the account, or only the one whose address you enter. + +Repeating events, moved and cancelled occurrences and time zones are taken into account. Events are read again every +15 minutes, or at once with **Refresh**; the list says when a calendar was last read, or why it could not be. + ## Sharing **Share** in the page header shows who can open the page through its space and copies the page's link. Editors can @@ -184,7 +198,8 @@ page too. Turning it off makes the link stop working at once. Pages in the trash - **Export:** the **⋯** menu in the page header saves the page as Markdown, HTML, PDF or Word. PDFs are A4, with a bookmark per heading and the page's images. Word files keep headings, lists, to-dos, callouts, tables, colours and the page's images, and import back into Docwell as they were. Draw.io and Excalidraw diagrams become a link to their - file, and Mermaid charts show their source. + file, and Mermaid charts show their source. **Export as PNG** saves the page as one picture, the way it looks on + screen, and **Print** prints only the page, in the light theme, without the app around it. - **Import:** **Import** on a space's page list creates a page per Markdown (`.md`, `.txt`), HTML or Word (`.docx`) file. A leading `# Heading`, or the Word document's title, becomes the page title. Word headings, lists, quotes, tables, alignment, colours, links and images are kept. Up to 20 files at once. @@ -193,8 +208,39 @@ page too. Turning it off makes the link stop working at once. Pages in the trash between the pages, and stores images and files as attachments. Each database becomes a page with a database block of its rows, with guessed property types, and the row pages under it. Tables in pages come in as tables; callouts and to-do lists are kept. +- **From Obsidian, or any folder of Markdown:** zip the vault folder and import the `.zip`. Folders become pages with + their notes inside (a note named like its folder, such as `Projects/Projects.md`, is that folder's page), + `[[wikilinks]]` and `![[embeds]]` are found by name anywhere in the vault, images and files become attachments, and + callouts come through. YAML front matter becomes properties (created when the workspace has none of that name; lists + become multi-selects, dates dates) and its `tags`, with the `#tags` in the text, become the page's tags. A Docwell + space export imports back the same way. +- **From Bear:** import a Bear backup (`.bear2bk`), or a `.zip` of notes exported as TextBundle. `#tags` and + `#multi word tags#` become tags. +- **From OneNote:** in OneNote for Windows, choose **File → Export**, pick a page or section and **Single File Web + Page (\*.mht)**, and import the `.mht`. Each page becomes a page, with its pictures. +- **From Readwise:** in Readwise, choose **Export → Export to CSV** and import the `.csv`. A **Readwise** page holds a + page per book or article, with its highlights as quotes, your notes and locations, its author as a property and its + document tags as tags. Readwise's Markdown export imports like any folder of Markdown. +- **CSV:** any other `.csv` becomes a page with a database of its rows. - **To Notion:** export the page as Word or Markdown, then import that file with **Import** in Notion's sidebar. +### Web clipper + +The Docwell Web Clipper (in `Web-Clipper/` of the source; Chrome, Edge and Firefox) saves the page you are reading as +a new page: the article on it, or only what you selected, with its links and pictures, under a note saying where it +came from. In its options, enter the address you open Docwell at and an API token with *Read and write* access +(Account settings → API tokens), then pick the space new clips go to. + +### Workspace snapshots + +**Workspace settings → Snapshot → Download snapshot** (workspace admins) saves the whole workspace as one zip: spaces, +pages with their full documents, tags, properties, shared collections, comments and files. **New workspace → Restore +from a snapshot** (organization admins) makes a new workspace from it, on this server or another one, with every link, +mention, embedded page and relation pointing at the restored pages and comments still anchored to their text. A +snapshot holds what you can open: other people's journals and pages hidden from you are left out. Members, sharing, +public links, webhooks, AI settings and page history are not part of it. For a backup of the whole server, see +[Backups](./backups-upgrades). + ## Trash **Move to trash** hides a page and everything inside it. Restore it from the space's **Trash**. Space admins can diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index b041102..ea9605e 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -87,6 +87,9 @@ export type PropertyVisibility = Schemas["PropertyVisibility"]; export type Property = Schemas["Property"]; export type PropertyInput = Schemas["PropertyInput"]; export type Tag = Schemas["Tag"]; +export type CalendarAccount = Schemas["CalendarAccount"]; +export type CalendarAccountInput = Schemas["CalendarAccountInput"]; +export type CalendarEvent = Schemas["CalendarEvent"]; export type TagInput = Schemas["TagInput"]; export type DocRule = Schemas["DocRule"]; export type DocFilter = Schemas["DocFilter"]; @@ -494,6 +497,16 @@ export function createClient(opts: ClientOptions) { setDefaultPageMode: (id: string, defaultPageMode: PageMode) => request("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { defaultPageMode }), remove: (id: string) => request("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}`), + /** A zip that restores the workspace 1:1 (workspace admin). */ + snapshot: (id: string) => download(`/api/v1/workspaces/${encodeURIComponent(id)}/snapshot`), + /** Makes a new workspace from a snapshot (organization admin). */ + restore: (file: File, opts: { name?: string; organization?: string } = {}) => { + const form = new FormData(); + form.append("file", file, file.name); + if (opts.name) form.append("name", opts.name); + if (opts.organization) form.append("organization", opts.organization); + return upload("/api/v1/workspaces/restore", form); + }, members: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/members`), setMember: (id: string, email: string, role: WorkspaceRole) => @@ -557,6 +570,19 @@ export function createClient(opts: ClientOptions) { remove: (id: string) => request("DELETE", `/api/v1/properties/${encodeURIComponent(id)}`), }, + calendars: { + list: () => request("GET", "/api/v1/calendars"), + /** Subscribes to a feed or CalDAV account; the server reads it once to check it. */ + create: (input: CalendarAccountInput) => post("/api/v1/calendars", input), + update: (id: string, patch: CalendarAccountInput) => + request("PATCH", `/api/v1/calendars/${encodeURIComponent(id)}`, patch), + remove: (id: string) => request("DELETE", `/api/v1/calendars/${encodeURIComponent(id)}`), + refresh: (id: string) => post(`/api/v1/calendars/${encodeURIComponent(id)}/refresh`), + /** The caller's events from day from to day to (inclusive), in zone tz. */ + events: (from: string, to: string, tz?: string) => + request("GET", `/api/v1/calendar/events${query({ from, to, tz })}`), + }, + tags: { update: (id: string, patch: TagInput) => request("PATCH", `/api/v1/tags/${encodeURIComponent(id)}`, patch), remove: (id: string) => request("DELETE", `/api/v1/tags/${encodeURIComponent(id)}`), diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index e7a87de..c3301b1 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -550,6 +550,48 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/snapshot": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** + * Download a snapshot of the workspace that restores 1:1 (workspace admin or above) + * @description One zip: snapshot.json (the workspace's settings, spaces, pages and their place in the tree, tags, properties, shared collections, comments and the attachments' details), pages/.ydoc (each page's Yjs state), pages/.json (the same document as JSON) and files/ (each attachment). It holds what the caller can open: other people's journals and pages hidden from the caller are left out, as are trashed pages. Members, page sharing, share links, webhooks, AI settings and page history are not included. + */ + get: operations["exportWorkspaceSnapshot"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/restore": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Make a new workspace from a snapshot (organization admin or superadmin) + * @description Every record gets a new id and old ids are replaced wherever they appear (links, mentions, embedded pages, database relations, property values, collection rules), so a snapshot can be restored next to its original. Pages come back from their Yjs state, so comments stay anchored to their text. People named in the snapshot keep their comments and collections when they exist on this server; everything else is the caller's. On any error nothing is left behind. Up to 4 GB. + */ + post: operations["restoreWorkspaceSnapshot"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/workspaces/{id}": { parameters: { query?: never; @@ -1532,8 +1574,8 @@ export interface paths { get?: never; put?: never; /** - * Create pages from Markdown, HTML, Word files or a Notion export (editor) - * @description One page per Markdown, HTML or Word file (.md, .markdown, .txt, .html, .htm up to 5 MB; .docx up to 25 MB). A leading level-1 heading (a Word title) becomes the title, otherwise the file name. A .zip (up to 100 MB) is read as a Notion export, Markdown & CSV or HTML: its page tree, links between its pages, images and files are kept, and each database becomes a page listing its rows with the row pages under it. At most 20 files and 2000 pages at once. Content is reduced to what the editor supports; scripts and styles are dropped. The response lists the pages created at the parent's level. + * Create pages from Markdown, HTML, Word, CSV, OneNote, Notion, Obsidian or Bear files (editor) + * @description One page per Markdown, HTML or Word file (.md, .markdown, .txt, .html, .htm up to 5 MB; .docx up to 25 MB). A leading level-1 heading (a Word title) becomes the title, otherwise the file name. A .csv (up to 5 MB) becomes a page with a database, or, when it is a Readwise export, a "Readwise" page with a page of highlights per book. A .mht or .mhtml web archive (up to 100 MB; OneNote's "Single File Web Page" export) becomes a page per page it holds, with its images. A .zip (up to 100 MB) is read as a Notion export (Markdown & CSV or HTML; each database becomes a page listing its rows with the row pages under it) or as a folder of Markdown notes: an Obsidian vault, Bear TextBundles, or any Markdown with its images, Docwell's own space export included. Folders become pages (a note named like its folder is that page), [[wikilinks]] and ![[embeds]] are found by name, YAML front matter becomes properties (made when missing) and tags, and #tags are added to the page's tags. A Bear backup (.bear2bk) is read the same way. Page trees, links between pages, images and files are kept. At most 20 files and 2000 pages at once. Content is reduced to what the editor supports; scripts and styles are dropped. The response lists the pages created at the parent's level. */ post: operations["importPages"]; delete?: never; @@ -2037,6 +2079,86 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/calendars": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The caller's calendar subscriptions (passwords are never returned) */ + get: operations["listCalendars"]; + put?: never; + /** + * Subscribe to an iCalendar feed or a CalDAV account (read once first, to check it) + * @description kind "ics" reads an .ics or webcal:// address (Google Calendar's secret address in iCal format, Outlook's published calendar, any feed), with an optional user name and password. kind "caldav" reads a CalDAV calendar, or every event calendar of the account when the address is the server or the account's home (Nextcloud, iCloud with an app password, Fastmail…). Addresses follow the webhook rules: loopback and link-local addresses are refused unless DOCWELL_WEBHOOKS_ALLOW_LOCAL is on. At most 20 calendars per person. + */ + post: operations["createCalendar"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/calendars/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Remove a calendar subscription */ + delete: operations["deleteCalendar"]; + options?: never; + head?: never; + /** Rename, recolour, turn off or change the address or sign-in of a calendar */ + patch: operations["updateCalendar"]; + trace?: never; + }; + "/api/v1/calendars/{id}/refresh": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Read a calendar from its source now (events are otherwise kept for 15 minutes) */ + post: operations["refreshCalendar"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/calendar/events": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The caller's events between two days, from their enabled calendars + * @description Repeating events are expanded, changed and cancelled occurrences applied. All-day events come first. A calendar that cannot be read is left out (its lastError says why). + */ + get: operations["listCalendarEvents"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/workspaces/{id}/journals": { parameters: { query?: never; @@ -3660,6 +3782,52 @@ export interface components { * @enum {string} */ PropertyType: "text" | "number" | "checkbox" | "date" | "select" | "multi_select" | "member" | "link"; + CalendarAccount: { + id: string; + name: string; + /** @enum {string} */ + kind: "ics" | "caldav"; + url: string; + username: string; + hasPassword: boolean; + color: components["schemas"]["LabelColor"]; + /** @description Whether its events show on journal pages */ + enabled: boolean; + /** @description When the source was last read */ + lastSync: string; + /** @description Why the last read failed; empty when it worked */ + lastError: string; + /** @description Events the source held then (repeating ones once) */ + events: number; + created: string; + }; + CalendarAccountInput: { + name?: string; + /** @enum {string} */ + kind?: "ics" | "caldav"; + /** @description http, https or webcal address */ + url?: string; + username?: string; + /** @description Empty keeps the stored one */ + password?: string; + clearPassword?: boolean; + color?: components["schemas"]["LabelColor"]; + enabled?: boolean; + }; + CalendarEvent: { + id: string; + /** @description The calendar account's id */ + calendar: string; + title: string; + location: string; + url: string; + /** @description RFC 3339 time, or a date (YYYY-MM-DD) for all-day events */ + start: string; + /** @description Exclusive; a date for all-day events */ + end: string; + allDay: boolean; + color: components["schemas"]["LabelColor"]; + }; /** * @description A colour of the editor palette, drawn from the theme; empty for none * @enum {string} @@ -4889,6 +5057,63 @@ export interface operations { 403: components["responses"]["Error"]; }; }; + exportWorkspaceSnapshot: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The zip, streamed as it is built */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/zip": string; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + restoreWorkspaceSnapshot: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "multipart/form-data": { + /** Format: binary */ + file: string; + /** @description The new workspace's name; empty keeps the snapshot's */ + name?: string; + /** @description Organization id (required for superadmins) */ + organization?: string; + }; + }; + }; + responses: { + /** @description The new workspace */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Workspace"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + }; + }; deleteWorkspace: { parameters: { query?: never; @@ -7669,6 +7894,151 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + listCalendars: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarAccount"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + createCalendar: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CalendarAccountInput"]; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarAccount"]; + }; + }; + 400: components["responses"]["Error"]; + }; + }; + deleteCalendar: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 404: components["responses"]["Error"]; + }; + }; + updateCalendar: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CalendarAccountInput"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarAccount"]; + }; + }; + 400: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + refreshCalendar: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The calendar with its new sync time or error */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarAccount"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + listCalendarEvents: { + parameters: { + query: { + from: string; + /** @description Inclusive; at most 92 days after from */ + to: string; + /** @description IANA time zone the days are in (default UTC) */ + tz?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarEvent"][]; + }; + }; + 400: components["responses"]["Error"]; + }; + }; getJournal: { parameters: { query: { diff --git a/Packages/ui/src/theme.ts b/Packages/ui/src/theme.ts index 477d6de..714e048 100644 --- a/Packages/ui/src/theme.ts +++ b/Packages/ui/src/theme.ts @@ -29,6 +29,9 @@ export function useTheme() { document.documentElement.classList.toggle("dark", dark); }; media.addEventListener("change", apply); + // Paper is light: print in the light theme, then put the chosen one back. + window.addEventListener("beforeprint", () => document.documentElement.classList.remove("dark")); + window.addEventListener("afterprint", apply); watchEffect(() => { apply(); try { diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 6437ec5..0fc49b1 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -3564,6 +3564,232 @@ enum PropertyType { String toJson() => value; } +enum CalendarAccountKind { + ics('ics'), + caldav('caldav'); + + const CalendarAccountKind(this.value); + final String value; + + static CalendarAccountKind fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown CalendarAccountKind', value), + ); + + String toJson() => value; +} + +class CalendarAccount { + const CalendarAccount({ + required this.id, + required this.name, + required this.kind, + required this.url, + required this.username, + required this.hasPassword, + required this.color, + required this.enabled, + required this.lastSync, + required this.lastError, + required this.events, + required this.created, + }); + + factory CalendarAccount.fromJson(Map json) => + CalendarAccount( + id: json['id'] as String, + name: json['name'] as String, + kind: CalendarAccountKind.fromJson(json['kind'] as String), + url: json['url'] as String, + username: json['username'] as String, + hasPassword: json['hasPassword'] as bool, + color: LabelColor.fromJson(json['color'] as String), + enabled: json['enabled'] as bool, + lastSync: json['lastSync'] as String, + lastError: json['lastError'] as String, + events: (json['events'] as num).toInt(), + created: json['created'] as String, + ); + + final String id; + + final String name; + + final CalendarAccountKind kind; + + final String url; + + final String username; + + final bool hasPassword; + + final LabelColor color; + + /// Whether its events show on journal pages + final bool enabled; + + /// When the source was last read + final String lastSync; + + /// Why the last read failed; empty when it worked + final String lastError; + + /// Events the source held then (repeating ones once) + final int events; + + final String created; + + Map toJson() => { + 'id': id, + 'name': name, + 'kind': kind.toJson(), + 'url': url, + 'username': username, + 'hasPassword': hasPassword, + 'color': color.toJson(), + 'enabled': enabled, + 'lastSync': lastSync, + 'lastError': lastError, + 'events': events, + 'created': created, + }; +} + +enum CalendarAccountInputKind { + ics('ics'), + caldav('caldav'); + + const CalendarAccountInputKind(this.value); + final String value; + + static CalendarAccountInputKind fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => + throw FormatException('unknown CalendarAccountInputKind', value), + ); + + String toJson() => value; +} + +class CalendarAccountInput { + const CalendarAccountInput({ + this.name, + this.kind, + this.url, + this.username, + this.password, + this.clearPassword, + this.color, + this.enabled, + }); + + factory CalendarAccountInput.fromJson(Map json) => + CalendarAccountInput( + name: json['name'] == null ? null : json['name'] as String, + kind: json['kind'] == null + ? null + : CalendarAccountInputKind.fromJson(json['kind'] as String), + url: json['url'] == null ? null : json['url'] as String, + username: json['username'] == null ? null : json['username'] as String, + password: json['password'] == null ? null : json['password'] as String, + clearPassword: json['clearPassword'] == null + ? null + : json['clearPassword'] as bool, + color: json['color'] == null + ? null + : LabelColor.fromJson(json['color'] as String), + enabled: json['enabled'] == null ? null : json['enabled'] as bool, + ); + + final String? name; + + final CalendarAccountInputKind? kind; + + /// http, https or webcal address + final String? url; + + final String? username; + + /// Empty keeps the stored one + final String? password; + + final bool? clearPassword; + + final LabelColor? color; + + final bool? enabled; + + Map toJson() => { + 'name': ?name, + 'kind': ?kind?.toJson(), + 'url': ?url, + 'username': ?username, + 'password': ?password, + 'clearPassword': ?clearPassword, + 'color': ?color?.toJson(), + 'enabled': ?enabled, + }; +} + +class CalendarEvent { + const CalendarEvent({ + required this.id, + required this.calendar, + required this.title, + required this.location, + required this.url, + required this.start, + required this.end, + required this.allDay, + required this.color, + }); + + factory CalendarEvent.fromJson(Map json) => CalendarEvent( + id: json['id'] as String, + calendar: json['calendar'] as String, + title: json['title'] as String, + location: json['location'] as String, + url: json['url'] as String, + start: json['start'] as String, + end: json['end'] as String, + allDay: json['allDay'] as bool, + color: LabelColor.fromJson(json['color'] as String), + ); + + final String id; + + /// The calendar account's id + final String calendar; + + final String title; + + final String location; + + final String url; + + /// RFC 3339 time, or a date (YYYY-MM-DD) for all-day events + final String start; + + /// Exclusive; a date for all-day events + final String end; + + final bool allDay; + + final LabelColor color; + + Map toJson() => { + 'id': id, + 'calendar': calendar, + 'title': title, + 'location': location, + 'url': url, + 'start': start, + 'end': end, + 'allDay': allDay, + 'color': color.toJson(), + }; +} + /// A colour of the editor palette, drawn from the theme; empty for none enum LabelColor { none(''), diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go index 743e9c1..1b0abfb 100644 --- a/Server/cmd/docwell-server/main.go +++ b/Server/cmd/docwell-server/main.go @@ -20,6 +20,7 @@ import ( "docwell/server/internal/ai" "docwell/server/internal/audit" "docwell/server/internal/auth" + "docwell/server/internal/calendar" "docwell/server/internal/collab" "docwell/server/internal/config" "docwell/server/internal/directory" @@ -174,6 +175,9 @@ func run(log *slog.Logger) error { reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second, func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) }) go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute) + // Calendars (ADR-16): passwords are sealed with the same secret as AI keys; + // sources follow the webhook address rules. + calSvc := calendar.New(db, calendar.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal}) dirSvc.SetPublicURL(cfg.PublicURL) dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20) dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string { @@ -198,6 +202,7 @@ func run(log *slog.Logger) error { Collab: hub, Audit: auditLog, Previews: unfurl.New(), + Calendars: calSvc, Push: pushSvc, AI: aiSvc, Admin: admin.Handler("/admin"), diff --git a/Server/go.mod b/Server/go.mod index 85b4c6e..f3d474f 100644 --- a/Server/go.mod +++ b/Server/go.mod @@ -43,6 +43,8 @@ require ( github.com/boombuler/barcode v1.0.1 // indirect github.com/buger/jsonparser v1.1.2 // indirect github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect + github.com/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6 // indirect + github.com/emersion/go-webdav v0.7.0 // indirect github.com/getkin/kin-openapi v0.142.0 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -63,6 +65,7 @@ require ( github.com/speakeasy-api/jsonpath v0.6.3 // indirect github.com/speakeasy-api/openapi v1.24.0 // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect + github.com/teambition/rrule-go v1.8.2 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect diff --git a/Server/go.sum b/Server/go.sum index 88a339d..f9677b9 100644 --- a/Server/go.sum +++ b/Server/go.sum @@ -99,6 +99,13 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w= github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q= +github.com/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6 h1:kHoSgklT8weIDl6R6xFpBJ5IioRdBU1v2X2aCZRVCcM= +github.com/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw= +github.com/emersion/go-ical v0.0.0-20261112170022-46c5b53a1723 h1:p8cDduDfznI5LDWxHDRD2B7b6y2TlFRVV4i5xzKq4xk= +github.com/emersion/go-ical v0.0.0-20261112170022-46c5b53a1723/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw= +github.com/emersion/go-vcard v0.0.0-20230815062825-8fda7d206ec9/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM= +github.com/emersion/go-webdav v0.7.0 h1:cp6aBWXBf8Sjzguka9VJarr4XTkGc2IHxXI1Gq3TKpA= +github.com/emersion/go-webdav v0.7.0/go.mod h1:mI8iBx3RAODwX7PJJ7qzsKAKs/vY429YfS2/9wKnDbQ= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -227,6 +234,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8= +github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index 534a457..c568d49 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -171,6 +171,42 @@ func (e ApiTokenScope) Valid() bool { } } +// Defines values for CalendarAccountKind. +const ( + CalendarAccountKindCaldav CalendarAccountKind = "caldav" + CalendarAccountKindIcs CalendarAccountKind = "ics" +) + +// Valid indicates whether the value is a known member of the CalendarAccountKind enum. +func (e CalendarAccountKind) Valid() bool { + switch e { + case CalendarAccountKindCaldav: + return true + case CalendarAccountKindIcs: + return true + default: + return false + } +} + +// Defines values for CalendarAccountInputKind. +const ( + CalendarAccountInputKindCaldav CalendarAccountInputKind = "caldav" + CalendarAccountInputKindIcs CalendarAccountInputKind = "ics" +) + +// Valid indicates whether the value is a known member of the CalendarAccountInputKind enum. +func (e CalendarAccountInputKind) Valid() bool { + switch e { + case CalendarAccountInputKindCaldav: + return true + case CalendarAccountInputKindIcs: + return true + default: + return false + } +} + // Defines values for DocFilterMatch. const ( All DocFilterMatch = "all" @@ -1269,6 +1305,76 @@ type BrandingSettings struct { Logo string `json:"logo"` } +// CalendarAccount defines model for CalendarAccount. +type CalendarAccount struct { + // Color A colour of the editor palette, drawn from the theme; empty for none + Color LabelColor `json:"color"` + Created string `json:"created"` + + // Enabled Whether its events show on journal pages + Enabled bool `json:"enabled"` + + // Events Events the source held then (repeating ones once) + Events int `json:"events"` + HasPassword bool `json:"hasPassword"` + Id string `json:"id"` + Kind CalendarAccountKind `json:"kind"` + + // LastError Why the last read failed; empty when it worked + LastError string `json:"lastError"` + + // LastSync When the source was last read + LastSync string `json:"lastSync"` + Name string `json:"name"` + Url string `json:"url"` + Username string `json:"username"` +} + +// CalendarAccountKind defines model for CalendarAccount.Kind. +type CalendarAccountKind string + +// CalendarAccountInput defines model for CalendarAccountInput. +type CalendarAccountInput struct { + ClearPassword *bool `json:"clearPassword,omitempty"` + + // Color A colour of the editor palette, drawn from the theme; empty for none + Color *LabelColor `json:"color,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Kind *CalendarAccountInputKind `json:"kind,omitempty"` + Name *string `json:"name,omitempty"` + + // Password Empty keeps the stored one + Password *string `json:"password,omitempty"` + + // Url http, https or webcal address + Url *string `json:"url,omitempty"` + Username *string `json:"username,omitempty"` +} + +// CalendarAccountInputKind defines model for CalendarAccountInput.Kind. +type CalendarAccountInputKind string + +// CalendarEvent defines model for CalendarEvent. +type CalendarEvent struct { + AllDay bool `json:"allDay"` + + // Calendar The calendar account's id + Calendar string `json:"calendar"` + + // Color A colour of the editor palette, drawn from the theme; empty for none + Color LabelColor `json:"color"` + + // End Exclusive; a date for all-day events + End string `json:"end"` + Id string `json:"id"` + Location string `json:"location"` + + // Start RFC 3339 time, or a date (YYYY-MM-DD) for all-day events + Start string `json:"start"` + Title string `json:"title"` + Url string `json:"url"` +} + // Collection defines model for Collection. type Collection struct { CanEdit bool `json:"canEdit"` @@ -2405,6 +2511,17 @@ type ConfirmVerificationJSONBody struct { Token string `json:"token"` } +// ListCalendarEventsParams defines parameters for ListCalendarEvents. +type ListCalendarEventsParams struct { + From openapi_types.Date `form:"from" json:"from"` + + // To Inclusive; at most 92 days after from + To openapi_types.Date `form:"to" json:"to"` + + // Tz IANA time zone the days are in (default UTC) + Tz *string `form:"tz,omitempty" json:"tz,omitempty"` +} + // UpdateCommentJSONBody defines parameters for UpdateComment. type UpdateCommentJSONBody struct { Body string `json:"body"` @@ -2664,6 +2781,17 @@ type CreateWorkspaceJSONBody struct { Organization *string `json:"organization,omitempty"` } +// RestoreWorkspaceSnapshotMultipartBody defines parameters for RestoreWorkspaceSnapshot. +type RestoreWorkspaceSnapshotMultipartBody struct { + File openapi_types.File `json:"file"` + + // Name The new workspace's name; empty keeps the snapshot's + Name *string `json:"name,omitempty"` + + // Organization Organization id (required for superadmins) + Organization *string `json:"organization,omitempty"` +} + // UpdateWorkspaceJSONBody defines parameters for UpdateWorkspace. type UpdateWorkspaceJSONBody struct { // DefaultPageMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it @@ -2822,6 +2950,12 @@ type ConfirmVerificationJSONRequestBody ConfirmVerificationJSONBody // RequestVerificationJSONRequestBody defines body for RequestVerification for application/json ContentType. type RequestVerificationJSONRequestBody = EmailRequest +// CreateCalendarJSONRequestBody defines body for CreateCalendar for application/json ContentType. +type CreateCalendarJSONRequestBody = CalendarAccountInput + +// UpdateCalendarJSONRequestBody defines body for UpdateCalendar for application/json ContentType. +type UpdateCalendarJSONRequestBody = CalendarAccountInput + // UpdateCollectionJSONRequestBody defines body for UpdateCollection for application/json ContentType. type UpdateCollectionJSONRequestBody = CollectionInput @@ -2939,6 +3073,9 @@ type UpdateWebhookJSONRequestBody = WebhookInput // CreateWorkspaceJSONRequestBody defines body for CreateWorkspace for application/json ContentType. type CreateWorkspaceJSONRequestBody CreateWorkspaceJSONBody +// RestoreWorkspaceSnapshotMultipartRequestBody defines body for RestoreWorkspaceSnapshot for multipart/form-data ContentType. +type RestoreWorkspaceSnapshotMultipartRequestBody RestoreWorkspaceSnapshotMultipartBody + // UpdateWorkspaceJSONRequestBody defines body for UpdateWorkspace for application/json ContentType. type UpdateWorkspaceJSONRequestBody UpdateWorkspaceJSONBody diff --git a/Server/internal/calendar/calendar.go b/Server/internal/calendar/calendar.go new file mode 100644 index 0000000..f3f0e83 --- /dev/null +++ b/Server/internal/calendar/calendar.go @@ -0,0 +1,595 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package calendar reads people's calendars for their journals (Phase F, +// ADR-16): read-only subscriptions to an iCalendar feed (an .ics or webcal +// address, Google Calendar's secret address, Outlook's published calendar) +// or a CalDAV account (Nextcloud, iCloud, Fastmail…). Each person sees only +// their own. Events are not stored: they are read from the source when +// asked for and kept in memory for a while, so a journal opens fast and the +// source is not asked on every page view. +package calendar + +import ( + "bytes" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "slices" + "strings" + "sync" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" + "docwell/server/internal/webhooks" +) + +// Kinds of calendar accounts. +const ( + KindICS = "ics" + KindCalDAV = "caldav" +) + +const ( + maxAccounts = 20 + // maxRange caps the days one events request covers. + maxRange = 92 + // fetchTimeout caps one source fetch. + fetchTimeout = 30 * time.Second +) + +// Colours an account can have; the apps draw them from the theme. +var colors = []string{"gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"} + +// Options configure the service. +type Options struct { + // Secret seals the accounts' passwords (DOCWELL_SECRET_KEY). + Secret string + // AllowLocal lets sources on loopback addresses through (development). + AllowLocal bool + // TTL is how long events stay in memory before the source is asked again (15 min). + TTL time.Duration + // Client replaces the HTTP client (tests). + Client *http.Client +} + +type Service struct { + pb *pocketbase.Client + aead cipher.AEAD + client *http.Client + ttl time.Duration + mu sync.Mutex + cache map[string]*entry +} + +// entry is an account's last read: the iCalendar data and its parses by zone. +type entry struct { + mu sync.Mutex + key string // what the data was read with; a change reads again + at time.Time + data []byte + err error + feeds map[string]*feed +} + +func New(pb *pocketbase.Client, o Options) *Service { + key := sha256.Sum256([]byte("docwell-calendar:" + o.Secret)) + block, _ := aes.NewCipher(key[:]) + aead, _ := cipher.NewGCM(block) + client := o.Client + if client == nil { + dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)} + client = &http.Client{ + Timeout: fetchTimeout, + Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment, MaxResponseHeaderBytes: 64 << 10}, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 5 { + return errors.New("too many redirects") + } + return nil + }, + } + } + ttl := o.TTL + if ttl <= 0 { + ttl = 15 * time.Minute + } + return &Service{pb: pb, aead: aead, client: client, ttl: ttl, cache: map[string]*entry{}} +} + +func (s *Service) seal(plain string) string { + if plain == "" { + return "" + } + nonce := make([]byte, s.aead.NonceSize()) + _, _ = rand.Read(nonce) + return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil)) +} + +var errUnreadable = errors.New("the stored password cannot be decrypted (the server secret changed); enter it again") + +func (s *Service) open(sealed string) (string, error) { + if sealed == "" { + return "", nil + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:")) + n := s.aead.NonceSize() + if err != nil || len(raw) < n { + return "", errUnreadable + } + plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil) + if err != nil { + return "", errUnreadable + } + return string(plain), nil +} + +// ---- Accounts ------------------------------------------------------------------ + +type record struct { + ID string `json:"id"` + User string `json:"user"` + Name string `json:"name"` + Kind string `json:"kind"` + URL string `json:"url"` + Username string `json:"username"` + Secret string `json:"secret"` + Color string `json:"color"` + Enabled bool `json:"enabled"` + LastSync string `json:"last_sync"` + LastError string `json:"last_error"` + Events float64 `json:"events"` + Created string `json:"created"` +} + +// Account is a calendar subscription as its owner sees it, without the password. +type Account struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + URL string `json:"url"` + Username string `json:"username"` + HasPassword bool `json:"hasPassword"` + Color string `json:"color"` + Enabled bool `json:"enabled"` + // LastSync is when the source was last read; LastError why that failed ("" when it worked). + LastSync string `json:"lastSync"` + LastError string `json:"lastError"` + // Events counts the events (repeating ones once) the source held then. + Events int `json:"events"` + Created string `json:"created"` +} + +func (r record) view() Account { + return Account{ + ID: r.ID, Name: r.Name, Kind: r.Kind, URL: r.URL, Username: r.Username, HasPassword: r.Secret != "", + Color: r.Color, Enabled: r.Enabled, LastSync: r.LastSync, LastError: r.LastError, Events: int(r.Events), + Created: r.Created, + } +} + +// AccountInput creates an account, or changes the fields that are set. An +// empty Password keeps the stored one when changing; Password "" with +// ClearPassword removes it. +type AccountInput struct { + Name *string `json:"name"` + Kind *string `json:"kind"` + URL *string `json:"url"` + Username *string `json:"username"` + Password *string `json:"password"` + ClearPassword bool `json:"clearPassword"` + Color *string `json:"color"` + Enabled *bool `json:"enabled"` +} + +func signedIn(c access.Caller) error { + if c.ID == "" { + return apperr.NotFound("calendar not found") + } + return nil +} + +func (s *Service) records(ctx context.Context, user string) ([]record, error) { + res, err := pocketbase.List[record](ctx, s.pb, "calendar_accounts", pocketbase.ListOptions{ + PerPage: maxAccounts * 2, Filter: fmt.Sprintf("user = '%s'", user), Sort: "created", + }) + return res.Items, err +} + +func (s *Service) get(ctx context.Context, c access.Caller, id string) (record, error) { + if err := signedIn(c); err != nil { + return record{}, err + } + if len(id) == 0 || len(id) > 64 || strings.ContainsAny(id, `'"\`) { + return record{}, apperr.NotFound("calendar not found") + } + r, err := pocketbase.Get[record](ctx, s.pb, "calendar_accounts", id) + if err != nil || r.User != c.ID { + return record{}, apperr.NotFound("calendar not found") + } + return r, nil +} + +// List lists the caller's calendars. +func (s *Service) List(ctx context.Context, c access.Caller) ([]Account, error) { + if err := signedIn(c); err != nil { + return nil, err + } + rows, err := s.records(ctx, c.ID) + if err != nil { + return nil, err + } + out := make([]Account, len(rows)) + for i, r := range rows { + out[i] = r.view() + } + return out, nil +} + +// patch checks the input against what is stored (zero for a new account). +func (s *Service) patch(in AccountInput, old record) (map[string]any, record, error) { + p := map[string]any{} + next := old + bad := func(field, msg string) (map[string]any, record, error) { + return nil, record{}, apperr.InvalidFields(map[string]string{field: msg}) + } + if in.Name != nil { + name := strings.TrimSpace(*in.Name) + if name == "" || len([]rune(name)) > 80 { + return bad("name", "Give the calendar a name of at most 80 characters.") + } + p["name"], next.Name = name, name + } + if in.Kind != nil { + if *in.Kind != KindICS && *in.Kind != KindCalDAV { + return bad("kind", "Kind must be ics or caldav.") + } + p["kind"], next.Kind = *in.Kind, *in.Kind + } + if in.URL != nil { + u, err := feedURL(*in.URL) + if err != nil || len(*in.URL) > 2000 { + return bad("url", "Enter an http, https or webcal address.") + } + _ = u + v := strings.TrimSpace(*in.URL) + p["url"], next.URL = v, v + } + if in.Username != nil { + v := strings.TrimSpace(*in.Username) + if len(v) > 200 { + return bad("username", "The user name is too long.") + } + p["username"], next.Username = v, v + } + switch { + case in.Password != nil && *in.Password != "": + if len(*in.Password) > 1000 { + return bad("password", "The password is too long.") + } + sealed := s.seal(*in.Password) + p["secret"], next.Secret = sealed, sealed + case in.ClearPassword: + p["secret"], next.Secret = "", "" + } + if in.Color != nil { + if !slices.Contains(colors, *in.Color) { + return bad("color", "Unknown colour.") + } + p["color"], next.Color = *in.Color, *in.Color + } + if in.Enabled != nil { + p["enabled"], next.Enabled = *in.Enabled, *in.Enabled + } + return p, next, nil +} + +// Create adds a calendar after reading it once, so a wrong address or +// password is reported now rather than as an empty journal. +func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput) (Account, error) { + if err := signedIn(c); err != nil { + return Account{}, err + } + if in.Name == nil || in.Kind == nil || in.URL == nil { + return Account{}, apperr.InvalidFields(map[string]string{"url": "Name, kind and address are required."}) + } + rows, err := s.records(ctx, c.ID) + if err != nil { + return Account{}, err + } + if len(rows) >= maxAccounts { + return Account{}, apperr.Invalid(fmt.Sprintf("you can add at most %d calendars", maxAccounts)) + } + if in.Color == nil { + color := colors[(len(rows)+6)%len(colors)] + in.Color = &color + } + on := true + if in.Enabled == nil { + in.Enabled = &on + } + body, next, err := s.patch(in, record{}) + if err != nil { + return Account{}, err + } + f, data, err := s.read(ctx, next) + if err != nil { + return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()}) + } + body["user"] = c.ID + body["last_sync"] = pbTime(time.Now()) + body["last_error"] = "" + body["events"] = f.count() + rec, err := pocketbase.Create[record](ctx, s.pb, "calendar_accounts", body) + if err != nil { + return Account{}, err + } + s.store(rec, data) + return rec.view(), nil +} + +// Update changes a calendar; a new address, kind or sign-in is read first. +func (s *Service) Update(ctx context.Context, c access.Caller, id string, in AccountInput) (Account, error) { + old, err := s.get(ctx, c, id) + if err != nil { + return Account{}, err + } + body, next, err := s.patch(in, old) + if err != nil { + return Account{}, err + } + if len(body) == 0 { + return old.view(), nil + } + if sourceKey(next) != sourceKey(old) { + f, data, err := s.read(ctx, next) + if err != nil { + return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()}) + } + body["last_sync"], body["last_error"], body["events"] = pbTime(time.Now()), "", f.count() + s.store(next, data) + } + rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", old.ID, body) + if err != nil { + return Account{}, err + } + return rec.view(), nil +} + +// Delete removes a calendar. +func (s *Service) Delete(ctx context.Context, c access.Caller, id string) error { + r, err := s.get(ctx, c, id) + if err != nil { + return err + } + s.mu.Lock() + delete(s.cache, r.ID) + s.mu.Unlock() + return s.pb.Delete(ctx, "calendar_accounts", r.ID) +} + +// Refresh reads a calendar from its source now. +func (s *Service) Refresh(ctx context.Context, c access.Caller, id string) (Account, error) { + r, err := s.get(ctx, c, id) + if err != nil { + return Account{}, err + } + s.mu.Lock() + delete(s.cache, r.ID) + s.mu.Unlock() + if _, err := s.feed(ctx, r, time.UTC); err != nil { + slog.Debug("calendar refresh failed", "calendar", r.ID, "err", err) + } + r, err = s.get(ctx, c, id) + return r.view(), err +} + +func pbTime(t time.Time) string { return t.UTC().Format("2006-01-02 15:04:05.000Z") } + +func sourceKey(r record) string { + return r.Kind + "\x00" + r.URL + "\x00" + r.Username + "\x00" + r.Secret +} + +// read fetches and parses a source (to check it). +func (s *Service) read(ctx context.Context, r record) (*feed, []byte, error) { + password, err := s.open(r.Secret) + if err != nil { + return nil, nil, err + } + ctx, cancel := context.WithTimeout(ctx, fetchTimeout) + defer cancel() + data, err := fetch(ctx, s.client, source{kind: r.Kind, url: r.URL, username: r.Username, password: password}) + if err != nil { + return nil, nil, err + } + f, err := parseFeed(bytes.NewReader(data), time.UTC) + if err != nil { + return nil, nil, err + } + return f, data, nil +} + +func (f *feed) count() int { + n := len(f.events) + for _, o := range f.overrides { + n += len(o) + } + return n +} + +func (s *Service) store(r record, data []byte) { + s.mu.Lock() + defer s.mu.Unlock() + if r.ID == "" { + return + } + s.cache[r.ID] = &entry{key: sourceKey(r), at: time.Now(), data: data, feeds: map[string]*feed{}} +} + +// feed returns the account's events parsed in loc: from memory while fresh, +// otherwise read again. A failed read keeps serving the last good data. +func (s *Service) feed(ctx context.Context, r record, loc *time.Location) (*feed, error) { + s.mu.Lock() + e := s.cache[r.ID] + if e == nil { + e = &entry{feeds: map[string]*feed{}} + s.cache[r.ID] = e + } + s.mu.Unlock() + + e.mu.Lock() + defer e.mu.Unlock() + key := sourceKey(r) + if e.key != key || time.Since(e.at) > s.ttl { + _, data, err := s.read(ctx, r) + e.at, e.err = time.Now(), err + patch := map[string]any{"last_sync": pbTime(e.at), "last_error": ""} + if err != nil { + msg := err.Error() + if len(msg) > 500 { + msg = msg[:500] + } + patch["last_error"] = msg + } + if err == nil || e.key != key { + e.data, e.key, e.feeds = data, key, map[string]*feed{} + } + if f, perr := parseFeed(bytes.NewReader(e.data), time.UTC); err == nil && perr == nil { + patch["events"] = f.count() + } + if _, uerr := pocketbase.Update[record](context.WithoutCancel(ctx), s.pb, "calendar_accounts", r.ID, patch); uerr != nil { + slog.Debug("calendar status not saved", "calendar", r.ID, "err", uerr) + } + } + if e.data == nil { + return nil, e.err + } + if f := e.feeds[loc.String()]; f != nil { + return f, nil + } + f, err := parseFeed(bytes.NewReader(e.data), loc) + if err != nil { + return nil, err + } + e.feeds[loc.String()] = f + return f, nil +} + +// ---- Events -------------------------------------------------------------------- + +// Event is one occurrence of an event in one of the caller's calendars. +type Event struct { + ID string `json:"id"` + Calendar string `json:"calendar"` + Title string `json:"title"` + Location string `json:"location"` + URL string `json:"url"` + // Start and End are RFC 3339 times, or for all-day events dates + // (YYYY-MM-DD, End exclusive) in the asked zone. + Start string `json:"start"` + End string `json:"end"` + AllDay bool `json:"allDay"` + Color string `json:"color"` +} + +// Events lists the caller's events from day from to day to (both +// YYYY-MM-DD, inclusive) in zone tz (an IANA name; "" is UTC), from their +// enabled calendars. A calendar that cannot be read is left out. +func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz string) ([]Event, error) { + if err := signedIn(c); err != nil { + return nil, err + } + loc := time.UTC + if tz != "" { + l, err := time.LoadLocation(tz) + if err != nil { + return nil, apperr.InvalidFields(map[string]string{"tz": "Unknown time zone."}) + } + loc = l + } + start, err1 := time.ParseInLocation(time.DateOnly, from, loc) + end, err2 := time.ParseInLocation(time.DateOnly, to, loc) + if err1 != nil || err2 != nil { + return nil, apperr.InvalidFields(map[string]string{"from": "Dates look like 2026-11-16."}) + } + end = end.AddDate(0, 0, 1) + if !end.After(start) || end.Sub(start) > maxRange*24*time.Hour { + return nil, apperr.InvalidFields(map[string]string{"to": fmt.Sprintf("Ask for at most %d days, ending after they start.", maxRange)}) + } + rows, err := s.records(ctx, c.ID) + if err != nil { + return nil, err + } + var ( + wg sync.WaitGroup + mu sync.Mutex + out = []Event{} + ) + for _, r := range rows { + if !r.Enabled { + continue + } + wg.Add(1) + go func(r record) { + defer wg.Done() + f, err := s.feed(ctx, r, loc) + if err != nil { + return + } + occ := f.between(start, end) + list := make([]Event, 0, len(occ)) + for _, o := range occ { + ev := Event{ + ID: eventID(r.ID, o), Calendar: r.ID, Title: o.def.title, Location: o.def.location, + URL: safeLink(o.def.link), AllDay: o.def.allDay, Color: r.Color, + } + if ev.Title == "" { + ev.Title = "(no title)" + } + if o.def.allDay { + ev.Start, ev.End = o.start.In(loc).Format(time.DateOnly), o.end.In(loc).Format(time.DateOnly) + } else { + ev.Start, ev.End = o.start.UTC().Format(time.RFC3339), o.end.UTC().Format(time.RFC3339) + } + list = append(list, ev) + } + mu.Lock() + out = append(out, list...) + mu.Unlock() + }(r) + } + wg.Wait() + slices.SortStableFunc(out, func(a, b Event) int { + if a.AllDay != b.AllDay { + if a.AllDay { + return -1 + } + return 1 + } + return strings.Compare(a.Start, b.Start) + }) + return out, nil +} + +func eventID(calendar string, o occurrence) string { + h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d", calendar, o.def.uid, o.start.Unix()))) + return hex.EncodeToString(h[:8]) +} + +// safeLink keeps only web links from a calendar. +func safeLink(v string) string { + if strings.HasPrefix(v, "https://") || strings.HasPrefix(v, "http://") { + return v + } + return "" +} diff --git a/Server/internal/calendar/fetch.go b/Server/internal/calendar/fetch.go new file mode 100644 index 0000000..3942459 --- /dev/null +++ b/Server/internal/calendar/fetch.go @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/emersion/go-ical" + "github.com/emersion/go-webdav" + "github.com/emersion/go-webdav/caldav" +) + +// maxFeed caps what one account's source may send. +const maxFeed = 20 << 20 + +// source is where an account's events come from. +type source struct { + kind, url, username, password string +} + +// feedURL turns webcal:// (how calendar apps share feeds) into https://. +func feedURL(raw string) (*url.URL, error) { + raw = strings.TrimSpace(raw) + if rest, ok := strings.CutPrefix(raw, "webcal://"); ok { + raw = "https://" + rest + } else if rest, ok := strings.CutPrefix(raw, "webcals://"); ok { + raw = "https://" + rest + } + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return nil, errors.New("enter an http, https or webcal address") + } + return u, nil +} + +// fetch reads the source as iCalendar data (CalDAV objects are joined into +// one stream of VCALENDARs). +func fetch(ctx context.Context, client *http.Client, src source) ([]byte, error) { + u, err := feedURL(src.url) + if err != nil { + return nil, err + } + if src.kind == KindCalDAV { + return fetchCalDAV(ctx, client, u, src) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "text/calendar, */*;q=0.5") + req.Header.Set("User-Agent", "Docwell calendar") + if src.username != "" || src.password != "" { + req.SetBasicAuth(src.username, src.password) + } + res, err := client.Do(req) + if err != nil { + return nil, friendly(err) + } + defer func() { _ = res.Body.Close() }() + switch { + case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden: + return nil, errors.New("the calendar refused the user name or password") + case res.StatusCode == http.StatusNotFound: + return nil, errors.New("no calendar at this address (404)") + case res.StatusCode >= 300: + return nil, fmt.Errorf("the calendar answered %s", res.Status) + } + data, err := io.ReadAll(io.LimitReader(res.Body, maxFeed+1)) + if err != nil { + return nil, friendly(err) + } + if len(data) > maxFeed { + return nil, errors.New("the calendar is larger than 20 MB") + } + if !bytes.Contains(data[:min(len(data), 4096)], []byte("BEGIN:VCALENDAR")) { + return nil, errors.New("the address does not serve an iCalendar (.ics) file") + } + return data, nil +} + +// fetchCalDAV reads the events of the calendar at u, or of every calendar of +// the account when u is the server or the account's home: a year back and +// two years ahead. +func fetchCalDAV(ctx context.Context, client *http.Client, u *url.URL, src source) ([]byte, error) { + var hc webdav.HTTPClient = &limitedClient{c: client} + if src.username != "" || src.password != "" { + hc = webdav.HTTPClientWithBasicAuth(hc, src.username, src.password) + } + c, err := caldav.NewClient(hc, u.String()) + if err != nil { + return nil, err + } + now := time.Now() + query := &caldav.CalendarQuery{ + CompRequest: caldav.CalendarCompRequest{Name: "VCALENDAR", AllProps: true, AllComps: true}, + CompFilter: caldav.CompFilter{Name: "VCALENDAR", Comps: []caldav.CompFilter{ + {Name: "VEVENT", Start: now.AddDate(-1, 0, 0), End: now.AddDate(2, 0, 0)}, + }}, + } + objects, err := c.QueryCalendar(ctx, u.Path, query) + if err != nil { + // Not a calendar itself: find the account's calendars. + paths, err := discover(ctx, c, u) + if err != nil { + return nil, err + } + objects = nil + for _, p := range paths { + got, err := c.QueryCalendar(ctx, p, query) + if err != nil { + return nil, friendly(err) + } + objects = append(objects, got...) + } + } + var buf bytes.Buffer + enc := ical.NewEncoder(&buf) + for _, o := range objects { + if o.Data == nil { + continue + } + if err := enc.Encode(o.Data); err != nil { + continue + } + if buf.Len() > maxFeed { + return nil, errors.New("the calendars hold more than 20 MB of events") + } + } + return buf.Bytes(), nil +} + +func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]string, error) { + principal, err := c.FindCurrentUserPrincipal(ctx) + if err != nil { + return nil, friendly(fmt.Errorf("no CalDAV account at this address: %w", err)) + } + home, err := c.FindCalendarHomeSet(ctx, principal) + if err != nil { + return nil, friendly(fmt.Errorf("the CalDAV account lists no calendars: %w", err)) + } + cals, err := c.FindCalendars(ctx, home) + if err != nil { + return nil, friendly(err) + } + var paths []string + for _, cal := range cals { + events := len(cal.SupportedComponentSet) == 0 + for _, comp := range cal.SupportedComponentSet { + events = events || comp == "VEVENT" + } + if events { + paths = append(paths, cal.Path) + } + } + if len(paths) == 0 { + return nil, errors.New("the CalDAV account has no event calendars") + } + return paths, nil +} + +// limitedClient caps every CalDAV answer. +type limitedClient struct{ c *http.Client } + +func (l *limitedClient) Do(req *http.Request) (*http.Response, error) { + req.Header.Set("User-Agent", "Docwell calendar") + // The address is the person's own calendar; the dialer refuses loopback and + // link-local addresses (webhooks.Guard). + res, err := l.c.Do(req) //nolint:gosec // see above + if err != nil { + return nil, err + } + res.Body = struct { + io.Reader + io.Closer + }{io.LimitReader(res.Body, maxFeed+1), res.Body} + return res, nil +} + +// friendly shortens network errors for people. +func friendly(err error) error { + msg := err.Error() + switch { + case strings.Contains(msg, "address not allowed"): + return errors.New("this server may not reach that address") + case strings.Contains(msg, "no such host"): + return errors.New("the calendar's server name is unknown") + case strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "Timeout"): + return errors.New("the calendar did not answer in time") + case strings.Contains(msg, "401"): + return errors.New("the calendar refused the user name or password") + } + if len(msg) > 300 { + msg = msg[:300] + } + return errors.New(msg) +} diff --git a/Server/internal/calendar/fetch_test.go b/Server/internal/calendar/fetch_test.go new file mode 100644 index 0000000..184d448 --- /dev/null +++ b/Server/internal/calendar/fetch_test.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestFetchICS(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/public.ics": + w.Header().Set("Content-Type", "text/calendar") + _, _ = w.Write([]byte(sampleICS)) + case "/private.ics": + if u, p, ok := r.BasicAuth(); !ok || u != "ann" || p != "secret" { + w.WriteHeader(http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(sampleICS)) + case "/page": + _, _ = w.Write([]byte("hello")) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + ctx := context.Background() + c := srv.Client() + + data, err := fetch(ctx, c, source{kind: KindICS, url: srv.URL + "/public.ics"}) + if err != nil || !strings.Contains(string(data), "Planning") { + t.Fatalf("public feed: %v", err) + } + if _, err := fetch(ctx, c, source{kind: KindICS, url: srv.URL + "/private.ics", username: "ann", password: "secret"}); err != nil { + t.Fatalf("private feed: %v", err) + } + for name, src := range map[string]source{ + "wrong password": {kind: KindICS, url: srv.URL + "/private.ics", username: "ann", password: "nope"}, + "missing": {kind: KindICS, url: srv.URL + "/gone.ics"}, + "not a calendar": {kind: KindICS, url: srv.URL + "/page"}, + "bad scheme": {kind: KindICS, url: "ftp://example.com/cal.ics"}, + } { + if _, err := fetch(ctx, c, src); err == nil { + t.Errorf("%s: no error", name) + } + } +} + +func TestFeedURL(t *testing.T) { + u, err := feedURL("webcal://calendar.example.com/a.ics") + if err != nil || u.String() != "https://calendar.example.com/a.ics" { + t.Fatalf("webcal = %v, %v", u, err) + } + if _, err := feedURL("javascript:alert(1)"); err == nil { + t.Fatal("javascript: accepted") + } +} + +func TestSealRoundTrip(t *testing.T) { + s := New(nil, Options{Secret: "x"}) + sealed := s.seal("hunter2") + if sealed == "hunter2" || !strings.HasPrefix(sealed, "v1:") { + t.Fatalf("sealed = %q", sealed) + } + if got, err := s.open(sealed); err != nil || got != "hunter2" { + t.Fatalf("open = %q, %v", got, err) + } + if _, err := New(nil, Options{Secret: "y"}).open(sealed); err == nil { + t.Fatal("another secret opened the password") + } +} diff --git a/Server/internal/calendar/ics.go b/Server/internal/calendar/ics.go new file mode 100644 index 0000000..d408a4c --- /dev/null +++ b/Server/internal/calendar/ics.go @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "errors" + "fmt" + "io" + "sort" + "strings" + "time" + _ "time/tzdata" // Calendars name IANA zones; Windows hosts have no zone files. + + "github.com/emersion/go-ical" + "github.com/teambition/rrule-go" +) + +// ---- iCalendar: events and their repeats ------------------------------------ + +// maxPerEvent caps the occurrences one repeating event adds to one query. +const maxPerEvent = 500 + +// eventDef is one VEVENT: a single event, a repeating one, or a changed +// occurrence of a repeating one (recurrenceID set). +type eventDef struct { + uid, title, location, link string + start time.Time + dur time.Duration + allDay bool + cancelled bool + set *rrule.Set // nil for an event that does not repeat + recurrenceID time.Time +} + +// feed is a parsed calendar: its events by UID, with each repeating event's +// changed occurrences. +type feed struct { + events []*eventDef + overrides map[string]map[int64]*eventDef // uid -> original start (unix) -> changed occurrence +} + +// zones resolves TZIDs: IANA names, Windows names (Outlook), or a calendar's +// own VTIMEZONE as a fixed offset when nothing else is known. +type zones struct { + defs map[string]*ical.Component + seen map[string]*time.Location +} + +func (z *zones) location(tzid string, fallback *time.Location) *time.Location { + if tzid == "" { + return fallback + } + if loc, ok := z.seen[tzid]; ok { + return loc + } + name := strings.Trim(tzid, `"`) + if alias, ok := windowsZones[name]; ok { + name = alias + } + loc, err := time.LoadLocation(name) + if err != nil { + loc = z.fixed(tzid, fallback) + } + z.seen[tzid] = loc + return loc +} + +// fixed reads a VTIMEZONE's standard offset ("+0100"). +func (z *zones) fixed(tzid string, fallback *time.Location) *time.Location { + tz := z.defs[tzid] + if tz == nil { + return fallback + } + for _, child := range tz.Children { + if child.Name != "STANDARD" && len(tz.Children) > 1 { + continue + } + if p := child.Props.Get("TZOFFSETTO"); p != nil { + if off, ok := parseOffset(p.Value); ok { + return time.FixedZone(tzid, off) + } + } + } + return fallback +} + +func parseOffset(v string) (int, bool) { + v = strings.TrimSpace(v) + if len(v) != 5 && len(v) != 7 { + return 0, false + } + sign := 1 + switch v[0] { + case '-': + sign = -1 + case '+': + default: + return 0, false + } + n := 0 + for _, r := range v[1:] { + if r < '0' || r > '9' { + return 0, false + } + n = n*10 + int(r-'0') + } + h, m, s := n/100, n%100, 0 + if len(v) == 7 { + h, m, s = n/10000, n/100%100, n%100 + } + return sign * (h*3600 + m*60 + s), true +} + +// parseFeed reads every VCALENDAR in r. Times without a zone ("floating") +// and all-day dates are read in loc. +func parseFeed(r io.Reader, loc *time.Location) (*feed, error) { + var cals []*ical.Calendar + dec := ical.NewDecoder(r) + for { + cal, err := dec.Decode() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + if len(cals) > 0 { + break // Keep what was read before a broken tail. + } + return nil, fmt.Errorf("not an iCalendar file: %w", err) + } + cals = append(cals, cal) + } + f := &feed{overrides: map[string]map[int64]*eventDef{}} + for _, cal := range cals { + if err := f.add(cal, loc); err != nil { + return nil, err + } + } + return f, nil +} + +func (f *feed) add(cal *ical.Calendar, loc *time.Location) error { + z := &zones{defs: map[string]*ical.Component{}, seen: map[string]*time.Location{}} + for _, c := range cal.Children { + if c.Name == ical.CompTimezone { + if id := c.Props.Get(ical.PropTimezoneID); id != nil { + z.defs[id.Value] = c + } + } + } + for _, c := range cal.Children { + if c.Name != ical.CompEvent { + continue + } + e, err := readEvent(c, z, loc) + if err != nil { + continue // One broken event does not hide the rest. + } + if !e.recurrenceID.IsZero() { + if f.overrides[e.uid] == nil { + f.overrides[e.uid] = map[int64]*eventDef{} + } + f.overrides[e.uid][e.recurrenceID.Unix()] = e + continue + } + f.events = append(f.events, e) + } + return nil +} + +func propText(c *ical.Component, name string) string { + p := c.Props.Get(name) + if p == nil { + return "" + } + return strings.TrimSpace(p.Value) +} + +// dateTime reads a DTSTART-like property: its time, and whether it is a date. +func dateTime(p *ical.Prop, z *zones, loc *time.Location) (time.Time, bool, error) { + value := strings.TrimSpace(p.Value) + isDate := p.ValueType() == ical.ValueDate || (p.ValueType() == ical.ValueDefault && len(value) == 8) + if isDate { + t, err := time.ParseInLocation("20060102", value, loc) + return t, true, err + } + if strings.HasSuffix(value, "Z") { + t, err := time.Parse("20060102T150405Z", value) + return t, false, err + } + t, err := time.ParseInLocation("20060102T150405", value, z.location(p.Params.Get(ical.PropTimezoneID), loc)) + return t, false, err +} + +func readEvent(c *ical.Component, z *zones, loc *time.Location) (*eventDef, error) { + sp := c.Props.Get(ical.PropDateTimeStart) + if sp == nil { + return nil, fmt.Errorf("event without a start") + } + start, allDay, err := dateTime(sp, z, loc) + if err != nil { + return nil, err + } + e := &eventDef{ + uid: propText(c, ical.PropUID), title: unescape(propText(c, ical.PropSummary)), + location: unescape(propText(c, ical.PropLocation)), link: propText(c, ical.PropURL), + start: start, allDay: allDay, cancelled: strings.EqualFold(propText(c, ical.PropStatus), "CANCELLED"), + } + if e.uid == "" { + e.uid = fmt.Sprintf("%s@%d", e.title, start.Unix()) + } + switch { + case c.Props.Get(ical.PropDateTimeEnd) != nil: + end, _, err := dateTime(c.Props.Get(ical.PropDateTimeEnd), z, loc) + if err == nil && end.After(start) { + e.dur = end.Sub(start) + } + case c.Props.Get(ical.PropDuration) != nil: + if d, err := c.Props.Get(ical.PropDuration).Duration(); err == nil && d > 0 { + e.dur = d + } + } + if e.dur == 0 && allDay { + e.dur = 24 * time.Hour + } + if rp := c.Props.Get(ical.PropRecurrenceID); rp != nil { + if e.recurrenceID, _, err = dateTime(rp, z, loc); err != nil { + return nil, err + } + } + rules := c.Props.Values(ical.PropRecurrenceRule) + rdates := c.Props.Values(ical.PropRecurrenceDates) + if len(rules) == 0 && len(rdates) == 0 { + return e, nil + } + set := &rrule.Set{} + set.DTStart(start) + for _, rp := range rules { + opt, err := rrule.StrToROptionInLocation(rp.Value, start.Location()) + if err != nil { + return nil, err + } + opt.Dtstart = start + r, err := rrule.NewRRule(*opt) + if err != nil { + return nil, err + } + set.RRule(r) + } + each := func(props []ical.Prop, fn func(time.Time)) { + for _, p := range props { + for _, v := range strings.Split(p.Value, ",") { + one := p + one.Value = v + if t, _, err := dateTime(&one, z, start.Location()); err == nil { + fn(t) + } + } + } + } + each(rdates, set.RDate) + each(c.Props.Values(ical.PropExceptionDates), set.ExDate) + e.set = set + return e, nil +} + +// unescape undoes the escapes of iCalendar TEXT values. +func unescape(s string) string { + return strings.NewReplacer(`\n`, "\n", `\N`, "\n", `\,`, ",", `\;`, ";", `\\`, `\`).Replace(s) +} + +// occurrence is one time an event happens. +type occurrence struct { + def *eventDef + start, end time.Time +} + +// between lists the occurrences that overlap [from, to), in time order. +func (f *feed) between(from, to time.Time) []occurrence { + var out []occurrence + overlaps := func(start, end time.Time) bool { + if !end.After(start) { + end = start.Add(time.Second) // A moment, like a reminder. + } + return start.Before(to) && end.After(from) + } + for _, e := range f.events { + changed := f.overrides[e.uid] + if e.set == nil { + if !e.cancelled && overlaps(e.start, e.start.Add(e.dur)) { + out = append(out, occurrence{e, e.start, e.start.Add(e.dur)}) + } + continue + } + times := e.set.Between(from.Add(-e.dur), to, true) + if len(times) > maxPerEvent { + times = times[:maxPerEvent] + } + for _, t := range times { + if _, moved := changed[t.Unix()]; moved || e.cancelled { + continue + } + if overlaps(t, t.Add(e.dur)) { + out = append(out, occurrence{e, t, t.Add(e.dur)}) + } + } + } + // Changed occurrences stand on their own: they may have moved into or out + // of the range, or been cancelled. + for _, byTime := range f.overrides { + for _, o := range byTime { + if !o.cancelled && overlaps(o.start, o.start.Add(o.dur)) { + out = append(out, occurrence{o, o.start, o.start.Add(o.dur)}) + } + } + } + sort.SliceStable(out, func(i, j int) bool { + if !out[i].start.Equal(out[j].start) { + return out[i].start.Before(out[j].start) + } + return out[i].def.title < out[j].def.title + }) + return out +} + +// windowsZones maps the Windows zone names Outlook and Exchange write to IANA. +var windowsZones = map[string]string{ + "UTC": "UTC", "GMT Standard Time": "Europe/London", "Greenwich Standard Time": "Atlantic/Reykjavik", + "W. Europe Standard Time": "Europe/Berlin", "Central Europe Standard Time": "Europe/Budapest", + "Central European Standard Time": "Europe/Warsaw", "Romance Standard Time": "Europe/Paris", + "E. Europe Standard Time": "Europe/Chisinau", "FLE Standard Time": "Europe/Kiev", "GTB Standard Time": "Europe/Bucharest", + "Russian Standard Time": "Europe/Moscow", "Turkey Standard Time": "Europe/Istanbul", "Israel Standard Time": "Asia/Jerusalem", + "South Africa Standard Time": "Africa/Johannesburg", "Arabian Standard Time": "Asia/Dubai", "India Standard Time": "Asia/Kolkata", + "China Standard Time": "Asia/Shanghai", "Tokyo Standard Time": "Asia/Tokyo", "Korea Standard Time": "Asia/Seoul", + "Singapore Standard Time": "Asia/Singapore", "AUS Eastern Standard Time": "Australia/Sydney", + "New Zealand Standard Time": "Pacific/Auckland", "Eastern Standard Time": "America/New_York", + "Central Standard Time": "America/Chicago", "Mountain Standard Time": "America/Denver", "US Mountain Standard Time": "America/Phoenix", + "Pacific Standard Time": "America/Los_Angeles", "Alaskan Standard Time": "America/Anchorage", "Hawaiian Standard Time": "Pacific/Honolulu", + "Atlantic Standard Time": "America/Halifax", "E. South America Standard Time": "America/Sao_Paulo", + "Argentina Standard Time": "America/Buenos_Aires", "Mexico Standard Time": "America/Mexico_City", + "Central America Standard Time": "America/Guatemala", "SA Pacific Standard Time": "America/Bogota", +} diff --git a/Server/internal/calendar/ics_test.go b/Server/internal/calendar/ics_test.go new file mode 100644 index 0000000..4fb6374 --- /dev/null +++ b/Server/internal/calendar/ics_test.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "strings" + "testing" + "time" +) + +const sampleICS = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//test//EN\r\n" + + "BEGIN:VTIMEZONE\r\nTZID:Custom Zone\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0300\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n" + + // A one-off meeting in Warsaw time. + "BEGIN:VEVENT\r\nUID:one@test\r\nDTSTART;TZID=Europe/Warsaw:20261116T090000\r\nDTEND;TZID=Europe/Warsaw:20261116T100000\r\n" + + "SUMMARY:Planning\\, Q1\r\nLOCATION:Room 2\r\nEND:VEVENT\r\n" + + // An all-day event. + "BEGIN:VEVENT\r\nUID:allday@test\r\nDTSTART;VALUE=DATE:20261116\r\nDTEND;VALUE=DATE:20261117\r\nSUMMARY:Holiday\r\nEND:VEVENT\r\n" + + // Every weekday at 08:30 UTC, the 18th skipped, the 19th moved to 12:00. + "BEGIN:VEVENT\r\nUID:standup@test\r\nDTSTART:20261109T083000Z\r\nDURATION:PT15M\r\n" + + "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR\r\nEXDATE:20261118T083000Z\r\nSUMMARY:Standup\r\nEND:VEVENT\r\n" + + "BEGIN:VEVENT\r\nUID:standup@test\r\nRECURRENCE-ID:20261119T083000Z\r\nDTSTART:20261119T120000Z\r\nDTEND:20261119T121500Z\r\nSUMMARY:Standup (moved)\r\nEND:VEVENT\r\n" + + // A cancelled event, an Outlook zone name and a calendar's own zone. + "BEGIN:VEVENT\r\nUID:gone@test\r\nDTSTART:20261116T150000Z\r\nSTATUS:CANCELLED\r\nSUMMARY:Gone\r\nEND:VEVENT\r\n" + + "BEGIN:VEVENT\r\nUID:win@test\r\nDTSTART;TZID=W. Europe Standard Time:20261117T140000\r\nDTEND;TZID=W. Europe Standard Time:20261117T143000\r\nSUMMARY:Outlook\r\nEND:VEVENT\r\n" + + "BEGIN:VEVENT\r\nUID:custom@test\r\nDTSTART;TZID=Custom Zone:20261117T180000\r\nSUMMARY:Custom\r\nEND:VEVENT\r\n" + + "END:VCALENDAR\r\n" + +func TestFeedBetween(t *testing.T) { + warsaw, _ := time.LoadLocation("Europe/Warsaw") + f, err := parseFeed(strings.NewReader(sampleICS), warsaw) + if err != nil { + t.Fatal(err) + } + day := func(d string) (time.Time, time.Time) { + from, _ := time.ParseInLocation(time.DateOnly, d, warsaw) + return from, from.AddDate(0, 0, 1) + } + titles := func(occ []occurrence) []string { + var out []string + for _, o := range occ { + out = append(out, o.def.title+"@"+o.start.In(warsaw).Format("15:04")) + } + return out + } + cases := map[string]string{ + "2026-11-16": "Holiday@00:00|Standup@09:30|Planning, Q1@09:00", + "2026-11-17": "Standup@09:30|Outlook@14:00|Custom@16:00", + "2026-11-18": "", + "2026-11-19": "Standup (moved)@13:00", + "2026-11-21": "", // Saturday + } + for d, want := range cases { + got := titles(f.between(day(d))) + // Order is by start time; compare as sets of entries. + var wantList []string + if want != "" { + wantList = strings.Split(want, "|") + } + if len(got) != len(wantList) { + t.Errorf("%s: got %v, want %v", d, got, wantList) + continue + } + for _, w := range wantList { + found := false + for _, g := range got { + found = found || g == w + } + if !found { + t.Errorf("%s: %q missing from %v", d, w, got) + } + } + } + occ := f.between(day("2026-11-16")) + if occ[0].def.title != "Holiday" || !occ[0].def.allDay { + t.Errorf("all-day event should come first: %+v", occ[0].def) + } + for _, o := range occ { + if o.def.title == "Planning, Q1" && (o.def.location != "Room 2" || o.end.Sub(o.start) != time.Hour) { + t.Errorf("planning = %+v", o) + } + } +} + +func TestParseFeedRejectsJunk(t *testing.T) { + if _, err := parseFeed(strings.NewReader("not a calendar"), time.UTC); err == nil { + t.Fatal("HTML read as a calendar") + } +} + +func TestParseOffset(t *testing.T) { + for in, want := range map[string]int{"+0100": 3600, "-0530": -19800, "+013015": 5415} { + if got, ok := parseOffset(in); !ok || got != want { + t.Errorf("%s = %d, %v", in, got, ok) + } + } + if _, ok := parseOffset("0100"); ok { + t.Error("offset without a sign accepted") + } +} diff --git a/Server/internal/collab/hub.go b/Server/internal/collab/hub.go index 6f6cc69..00cf0cd 100644 --- a/Server/internal/collab/hub.go +++ b/Server/internal/collab/hub.go @@ -14,6 +14,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "log/slog" "sync" "time" @@ -643,6 +644,31 @@ func (h *Hub) Content(ctx context.Context, page string) (json.RawMessage, error) return h.o.Store.Content(ctx, page) } +// State returns the page's whole document as one Yjs update (the encoding +// Y.encodeStateAsUpdate writes): live from an open room, otherwise loaded. +func (h *Hub) State(ctx context.Context, page string) ([]byte, error) { + var state []byte + err := h.withRoom(ctx, page, func(r *room) error { + snap, err := r.compactLocked(ctx) + state = append([]byte(nil), snap...) + return err + }) + return state, err +} + +// Apply merges a Yjs update into the page as an edit by user (a restored +// snapshot's state). An update the document engine cannot read is refused +// before it reaches the room. +func (h *Hub) Apply(ctx context.Context, page, user string, update []byte) error { + return h.withRoom(ctx, page, func(r *room) error { + if _, err := h.o.Docs.Compact(ctx, append(append([][]byte{r.snapshot}, r.pending...), update)); err != nil { + return fmt.Errorf("collab: unreadable update: %w", err) + } + r.applyLocked(nil, update, user) + return nil + }) +} + func (h *Hub) Versions(ctx context.Context, page string) ([]Version, error) { return h.o.Store.Versions(ctx, page) } diff --git a/Server/internal/collab/hub_test.go b/Server/internal/collab/hub_test.go index 2f01ff5..747cba5 100644 --- a/Server/internal/collab/hub_test.go +++ b/Server/internal/collab/hub_test.go @@ -362,3 +362,34 @@ func TestDeletedPageClosesRoom(t *testing.T) { return h.rooms["p4"] == nil && peer.closeCode() == CloseGone }) } + +func TestStateAndApply(t *testing.T) { + ctx := context.Background() + store := newMemStore() + h, pool := newHub(t, store) + if err := h.Replace(ctx, "src", "alice", docJSON("copied over"), "import"); err != nil { + t.Fatal(err) + } + state, err := h.State(ctx, "src") + if err != nil || len(state) == 0 { + t.Fatalf("state = %d bytes, %v", len(state), err) + } + if textOf(t, pool, state) != "copied over" { + t.Fatal("state does not hold the document") + } + if err := h.Apply(ctx, "dst", "bob", state); err != nil { + t.Fatal(err) + } + if c, _ := h.Content(ctx, "dst"); !strings.Contains(string(c), "copied over") { + t.Fatalf("applied content = %s", c) + } + if err := h.Apply(ctx, "dst", "bob", []byte{1, 2, 3, 4, 5}); err == nil { + t.Fatal("an unreadable update was applied") + } + if c, _ := h.Content(ctx, "dst"); !strings.Contains(string(c), "copied over") { + t.Fatalf("content after a refused update = %s", c) + } + if err := h.Close(ctx); err != nil { + t.Fatal(err) + } +} diff --git a/Server/internal/convert/mht.go b/Server/internal/convert/mht.go new file mode 100644 index 0000000..8bf864c --- /dev/null +++ b/Server/internal/convert/mht.go @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package convert + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "io" + "mime" + "mime/multipart" + "mime/quotedprintable" + "net/mail" + "net/textproto" + "net/url" + "path" + "strings" + + "golang.org/x/net/html" + "golang.org/x/net/html/atom" + "golang.org/x/net/html/charset" +) + +// ---- MHTML: OneNote pages and sections, saved web pages -------------------- +// +// OneNote exports a page or a section as a "Single File Web Page" (.mht): a +// MIME message whose parts are the page's HTML and its images. A section +// holds one HTML part per page next to a frameset that shows them; each +// becomes a page. Browsers save pages as .mhtml the same way. + +// ErrNotMHT is returned for a file that is not an MHTML archive. +var ErrNotMHT = errors.New("not an MHTML (.mht) file") + +const ( + maxMHTParts = 5000 + maxMHTPart = 50 << 20 +) + +type mhtPart struct { + mime string + location string // Content-Location, as written + id string // Content-ID without the angle brackets + data []byte + page int // index of the page an HTML part became, or -1 +} + +// ReadMHT reads an MHTML archive into pages (one per HTML part, frames +// left out) and the files they use. name is the file's name, used as the +// title of a page without one. +func ReadMHT(data []byte, name string) ([]NotionPage, []Asset, error) { + msg, err := mail.ReadMessage(bytes.NewReader(bytes.TrimLeft(data, "\r\n\t "))) + if err != nil { + return nil, nil, ErrNotMHT + } + parts, err := mhtParts(textproto.MIMEHeader(msg.Header), msg.Body) + if err != nil { + return nil, nil, err + } + var pages []NotionPage + var assets []Asset + assetOf := map[int]string{} + for i := range parts { + parts[i].page = -1 + if parts[i].mime != "text/html" || isFrameset(parts[i].data) { + continue + } + parts[i].page = len(pages) + pages = append(pages, NotionPage{Parent: -1}) + } + if len(pages) == 0 { + return nil, nil, ErrNotMHT + } + if len(pages) > maxNotionPages { + return nil, nil, fmt.Errorf("the file has more than %d pages", maxNotionPages) + } + find := func(base *url.URL, raw string) int { + raw = strings.TrimSpace(raw) + if id, ok := strings.CutPrefix(raw, "cid:"); ok { + for i, p := range parts { + if p.id != "" && p.id == id { + return i + } + } + return -1 + } + u, err := url.Parse(raw) + if err != nil { + return -1 + } + if base != nil { + u = base.ResolveReference(u) + } + for i, p := range parts { + if p.location != "" && (p.location == raw || p.location == u.String()) { + return i + } + } + // Last, by file name: exporters write the same file in several ways. + want := strings.ToLower(path.Base(u.Path)) + for i, p := range parts { + if p.location == "" || want == "" || want == "/" { + continue + } + if l, err := url.Parse(p.location); err == nil && strings.ToLower(path.Base(l.Path)) == want { + return i + } + } + return -1 + } + for _, p := range parts { + if p.page < 0 { + continue + } + base, _ := url.Parse(p.location) + if p.location == "" { + base = nil + } + opts := ImportOptions{Resolve: func(raw string) (string, bool) { + i := find(base, raw) + switch { + case i < 0: + if strings.HasPrefix(strings.ToLower(raw), "http") || strings.HasPrefix(raw, "mailto:") { + return "", false + } + return "", true // A file the archive does not hold (file:///C:/…). + case parts[i].page >= 0: + return PageRef(parts[i].page), true + } + if ref, ok := assetOf[i]; ok { + return ref, true + } + ref := AssetRef(len(assets)) + assets = append(assets, Asset{Ref: ref, Name: partName(parts[i], len(assets)), Data: parts[i].data}) + assetOf[i] = ref + return ref, true + }} + doc, err := FromHTMLWith(string(p.data), opts) + if err != nil { + return nil, nil, err + } + title := htmlTitle(p.data) + if h1, rest := Title(doc); h1 != "" && (title == "" || strings.EqualFold(strings.TrimSpace(h1), title)) { + title, doc = h1, rest + } + if strings.TrimSpace(title) == "" { + title = strings.TrimSuffix(path.Base(name), path.Ext(name)) + } + if len(doc.Content) == 0 { + doc.Content = []Node{{Type: "paragraph"}} + } + pages[p.page] = NotionPage{Title: strings.TrimSpace(title), Parent: -1, Doc: doc} + } + return pages, assets, nil +} + +// mhtParts reads every leaf part of the message (nested multiparts too). +func mhtParts(h textproto.MIMEHeader, body io.Reader) ([]mhtPart, error) { + var out []mhtPart + var walk func(h textproto.MIMEHeader, body io.Reader, depth int) error + walk = func(h textproto.MIMEHeader, body io.Reader, depth int) error { + mt, params, err := mime.ParseMediaType(h.Get("Content-Type")) + if err != nil { + mt = "text/html" + } + if strings.HasPrefix(mt, "multipart/") { + if depth > 3 || params["boundary"] == "" { + return ErrNotMHT + } + mr := multipart.NewReader(body, params["boundary"]) + for { + p, err := mr.NextRawPart() + if err == io.EOF { + return nil + } + if err != nil { + return fmt.Errorf("the file is damaged: %w", err) + } + if err := walk(p.Header, p, depth+1); err != nil { + return err + } + } + } + if len(out) >= maxMHTParts { + return ErrTooLarge + } + data, err := decodePart(h, body) + if err != nil { + return err + } + if mt == "text/html" { + if cs := params["charset"]; cs != "" && !strings.EqualFold(cs, "utf-8") { + if r, err := charset.NewReaderLabel(cs, bytes.NewReader(data)); err == nil { + if conv, err := io.ReadAll(io.LimitReader(r, maxMHTPart)); err == nil { + data = conv + } + } + } + } + out = append(out, mhtPart{ + mime: mt, location: strings.TrimSpace(h.Get("Content-Location")), + id: strings.Trim(strings.TrimSpace(h.Get("Content-ID")), "<>"), data: data, + }) + return nil + } + if err := walk(h, body, 0); err != nil { + return nil, err + } + return out, nil +} + +func decodePart(h textproto.MIMEHeader, body io.Reader) ([]byte, error) { + r := body + switch strings.ToLower(strings.TrimSpace(h.Get("Content-Transfer-Encoding"))) { + case "base64": + r = base64.NewDecoder(base64.StdEncoding, &skipSpace{r: body}) + case "quoted-printable": + r = quotedprintable.NewReader(body) + } + data, err := io.ReadAll(io.LimitReader(r, maxMHTPart+1)) + if err != nil { + return nil, fmt.Errorf("the file is damaged: %w", err) + } + if len(data) > maxMHTPart { + return nil, ErrTooLarge + } + return data, nil +} + +// skipSpace drops the line breaks base64 bodies are wrapped with. +type skipSpace struct{ r io.Reader } + +func (s *skipSpace) Read(p []byte) (int, error) { + for { + n, err := s.r.Read(p) + j := 0 + for _, b := range p[:n] { + if b != '\r' && b != '\n' && b != ' ' && b != '\t' { + p[j] = b + j++ + } + } + if j > 0 || err != nil { + return j, err + } + } +} + +func isFrameset(data []byte) bool { + return bytes.Contains(bytes.ToLower(data[:min(len(data), 4096)]), []byte(" 0 { + ext = exts[0] + } + return fmt.Sprintf("file-%d%s", n+1, ext) +} diff --git a/Server/internal/convert/mht_test.go b/Server/internal/convert/mht_test.go new file mode 100644 index 0000000..a07de8d --- /dev/null +++ b/Server/internal/convert/mht_test.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package convert + +import ( + "encoding/base64" + "strings" + "testing" +) + +func TestReadMHTOneNoteSection(t *testing.T) { + img := base64.StdEncoding.EncodeToString(pngOf(t, 3, 3)) + var wrapped strings.Builder + for i := 0; i < len(img); i += 60 { + wrapped.WriteString(img[i:min(i+60, len(img))] + "\r\n") + } + mht := "MIME-Version: 1.0\r\n" + + "Content-Type: multipart/related; boundary=\"----=_NextPart_01\"\r\n\r\n" + + "------=_NextPart_01\r\nContent-Location: file:///C:/Export/Section.htm\r\nContent-Type: text/html; charset=\"utf-8\"\r\n\r\n" + + "\r\n" + + "------=_NextPart_01\r\nContent-Location: file:///C:/Export/Section_files/page1.htm\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\nContent-Type: text/html; charset=\"windows-1252\"\r\n\r\n" + + "Caf=E9 notes
" + + "

First line

next " + + "web

\r\n" + + "------=_NextPart_01\r\nContent-Location: file:///C:/Export/Section_files/page2.htm\r\nContent-Type: text/html\r\n\r\n" + + "

Second

Two

\r\n" + + "------=_NextPart_01\r\nContent-Location: file:///C:/Export/Section_files/image001.png\r\n" + + "Content-Transfer-Encoding: base64\r\nContent-Type: image/png\r\n\r\n" + wrapped.String() + + "------=_NextPart_01--\r\n" + pages, assets, err := ReadMHT([]byte(mht), "Section.mht") + if err != nil { + t.Fatal(err) + } + if len(pages) != 2 || pages[0].Title != "Café notes" || pages[1].Title != "Second" { + t.Fatalf("pages = %+v", pages) + } + if len(assets) != 1 || assets[0].Name != "image001.png" || string(assets[0].Data[1:4]) != "PNG" { + t.Fatalf("assets = %v", assets) + } + j := asJSON(t, pages[0].Doc) + for _, want := range []string{`"src":"asset:0"`, `"href":"page:1"`, `"href":"https://example.com/"`, "First line"} { + if !strings.Contains(j, want) { + t.Errorf("page lacks %s: %s", want, j) + } + } +} + +func TestReadMHTRejectsOtherFiles(t *testing.T) { + if _, _, err := ReadMHT([]byte("just text"), "x.mht"); err == nil { + t.Fatal("plain text read as MHTML") + } +} + +func TestReadReadwise(t *testing.T) { + csv := "Highlight,Book Title,Book Author,Amazon Book ID,Note,Color,Tags,Location Type,Location,Highlighted at,Document tags\n" + + "\"First idea,\nover two lines\",Deep Work,Cal Newport,B00X,My note,yellow,focus,location,120,2024-03-01 10:00:00+00:00,\"productivity, books\"\n" + + "Second idea,Deep Work,Cal Newport,B00X,,yellow,,location,130,,\n" + + "Web quote,An Article,,,,,,,,2024-04-02 08:00:00+00:00,\n" + if !IsReadwiseCSV([]byte(csv)) || IsReadwiseCSV([]byte("Name,Value\na,1\n")) { + t.Fatal("IsReadwiseCSV") + } + pages, err := ReadReadwise([]byte(csv)) + if err != nil { + t.Fatal(err) + } + if len(pages) != 3 || pages[0].Title != "Readwise" || pages[1].Title != "Deep Work" || pages[2].Parent != 0 { + t.Fatalf("pages = %+v", pages) + } + dw := pages[1] + if dw.Props["Author"] != "Cal Newport" || len(dw.Tags) != 2 || dw.Tags[1] != "books" { + t.Errorf("Deep Work props %v tags %v", dw.Props, dw.Tags) + } + j := asJSON(t, dw.Doc) + for _, want := range []string{`"type":"blockquote"`, `"First idea,"},{"type":"hardBreak"}`, "My note", "location 120 · 2024-03-01 · #focus", "Second idea"} { + if !strings.Contains(j, want) { + t.Errorf("Deep Work lacks %s: %s", want, j) + } + } +} + +func TestFromCSV(t *testing.T) { + doc, err := FromCSV([]byte("Name,Count\nApples,3\nPears,4\n")) + if err != nil || len(doc.Content) != 1 || doc.Content[0].Type != "database" { + t.Fatalf("doc = %+v, %v", doc, err) + } +} diff --git a/Server/internal/convert/notion.go b/Server/internal/convert/notion.go index edd8f5e..4ec5cfb 100644 --- a/Server/internal/convert/notion.go +++ b/Server/internal/convert/notion.go @@ -26,6 +26,9 @@ type NotionPage struct { Title string Parent int Doc Node + // Tags and Props come from a note's front matter and #tags (ReadVault). + Tags []string + Props map[string]any } // PageRef is the placeholder URL of the n-th page of an import. diff --git a/Server/internal/convert/readwise.go b/Server/internal/convert/readwise.go new file mode 100644 index 0000000..fe3552e --- /dev/null +++ b/Server/internal/convert/readwise.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package convert + +import ( + "bytes" + "encoding/csv" + "strings" +) + +// ---- CSV: Readwise highlights, or a table ---------------------------------- + +// FromCSV reads a CSV file as a page holding one database (ADR-13): the +// header names the columns, the first column is the title. +func FromCSV(data []byte) (Node, error) { return notionTable(data) } + +// IsReadwiseCSV tells Readwise's "Export to CSV" from any other CSV. +func IsReadwiseCSV(data []byte) bool { + r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM)))) + r.LazyQuotes = true + head, err := r.Read() + if err != nil { + return false + } + has := map[string]bool{} + for _, h := range head { + has[strings.ToLower(strings.TrimSpace(h))] = true + } + return has["highlight"] && has["book title"] +} + +// ReadReadwise turns a Readwise CSV export into a "Readwise" page with one +// page per book or article under it: its highlights as quotes, each with its +// note, location and tags. The book's document tags become the page's tags +// and its author the "Author" property. +func ReadReadwise(data []byte) ([]NotionPage, error) { + r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM)))) + r.FieldsPerRecord = -1 + r.LazyQuotes = true + rows, err := r.ReadAll() + if err != nil { + return nil, err + } + if len(rows) == 0 { + return nil, ErrNotNotion + } + col := map[string]int{} + for i, h := range rows[0] { + col[strings.ToLower(strings.TrimSpace(h))] = i + } + get := func(row []string, name string) string { + if i, ok := col[name]; ok && i < len(row) { + return strings.TrimSpace(row[i]) + } + return "" + } + pages := []NotionPage{{Title: "Readwise", Parent: -1}} + byBook := map[string]int{} + for _, row := range rows[1:] { + text := get(row, "highlight") + if text == "" { + continue + } + book := get(row, "book title") + if book == "" { + book = "Untitled" + } + i, ok := byBook[book] + if !ok { + if len(pages) > maxNotionPages { + break + } + i = len(pages) + byBook[book] = i + p := NotionPage{Title: book, Parent: 0, Doc: Node{Type: "doc"}} + if a := get(row, "book author"); a != "" { + p.Props = map[string]any{"Author": a} + p.Doc.Content = append(p.Doc.Content, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: a, Marks: []Mark{{Type: "italic"}}}}}) + } + for _, t := range strings.Split(get(row, "document tags"), ",") { + if t = strings.TrimSpace(t); t != "" { + p.Tags = append(p.Tags, t) + } + } + pages = append(pages, p) + } + p := &pages[i] + p.Doc.Content = append(p.Doc.Content, Node{Type: "blockquote", Content: []Node{textParagraph(text, nil)}}) + if note := get(row, "note"); note != "" { + p.Doc.Content = append(p.Doc.Content, textParagraph(note, nil)) + } + var meta []string + if loc := get(row, "location"); loc != "" { + kind := get(row, "location type") + if kind == "" || strings.EqualFold(kind, "order") { + kind = "location" + } + meta = append(meta, kind+" "+loc) + } + if at := get(row, "highlighted at"); len(at) >= 10 { + meta = append(meta, at[:10]) + } + for _, t := range strings.Split(get(row, "tags"), ",") { + if t = strings.TrimSpace(t); t != "" { + meta = append(meta, "#"+t) + } + } + if len(meta) > 0 { + p.Doc.Content = append(p.Doc.Content, textParagraph(strings.Join(meta, " · "), []Mark{{Type: "textColor", Attrs: map[string]any{"color": "gray"}}})) + } + } + if len(pages) == 1 { + return nil, ErrNotNotion + } + pages[0].Doc = Node{Type: "doc", Content: []Node{textParagraph("Highlights imported from Readwise.", nil)}} + return pages, nil +} + +// textParagraph is a paragraph of plain text; line breaks stay. +func textParagraph(s string, marks []Mark) Node { + p := Node{Type: "paragraph"} + for i, line := range strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n") { + if i > 0 { + p.Content = append(p.Content, Node{Type: "hardBreak"}) + } + if line != "" { + p.Content = append(p.Content, Node{Type: "text", Text: line, Marks: marks}) + } + } + return p +} diff --git a/Server/internal/convert/vault.go b/Server/internal/convert/vault.go new file mode 100644 index 0000000..1199e48 --- /dev/null +++ b/Server/internal/convert/vault.go @@ -0,0 +1,735 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package convert + +import ( + "archive/zip" + "bytes" + "errors" + "fmt" + "net/url" + "path" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" + + "gopkg.in/yaml.v3" +) + +// ---- Markdown folders: plain zips, Obsidian vaults, Bear exports ----------- +// +// A zip of Markdown files keeps its folders as pages: a folder becomes a page +// with its notes under it, or the note named like the folder ("Guides.md" +// next to "Guides/", or "Guides/Guides.md") is that page. Links between the +// files and to images and other files in the zip are kept, as relative +// Markdown links or as Obsidian [[wikilinks]] and ![[embeds]], which are +// found by file name anywhere in the archive like Obsidian does. YAML front +// matter becomes the page's properties and tags, and #tags in the text are +// added to its tags. Bear's TextBundles (a .bear2bk backup, or exported +// .textbundle folders) are a note each with their own assets. + +// ErrNoNotes is returned for an archive without Markdown notes in it. +var ErrNoNotes = errors.New("the archive holds no Markdown notes") + +// VaultKind is what an archive of Markdown looks like it came from. +type VaultKind string + +const ( + VaultMarkdown VaultKind = "markdown" + VaultObsidian VaultKind = "obsidian" + VaultBear VaultKind = "bear" + VaultNotion VaultKind = "notion" +) + +// DetectArchive tells a Notion export from a folder of Markdown files. It +// only looks at the names in the zip. +func DetectArchive(data []byte) (VaultKind, error) { + zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return "", fmt.Errorf("not a zip file: %w", err) + } + notion, markdown := 0, 0 + kind := VaultMarkdown + for _, f := range zr.File { + name := strings.ReplaceAll(f.Name, "\\", "/") + for _, part := range strings.Split(name, "/") { + switch { + case part == ".obsidian": + kind = VaultObsidian + case strings.HasSuffix(strings.ToLower(part), ".textbundle"): + if kind != VaultObsidian { + kind = VaultBear + } + } + } + base := path.Base(name) + ext := strings.ToLower(path.Ext(base)) + if notionID.MatchString(strings.TrimSuffix(base, path.Ext(base))) { + notion++ + } + switch ext { + case ".md", ".markdown": + markdown++ + case ".zip": + // Large Notion exports come as zips inside a zip. + if strings.HasPrefix(strings.ToLower(base), "export-") { + notion++ + } + } + } + if notion > 0 && kind == VaultMarkdown && notion*2 >= markdown { + return VaultNotion, nil + } + if markdown == 0 && kind != VaultBear { + // HTML pages only: Notion's HTML export is read the same way. + return VaultNotion, nil + } + return kind, nil +} + +// ImportedPage is one page of a multi-page import. Parent is the index of +// its parent page in the list, or -1 at the top. Links to other pages of the +// import use PageRef as their URL, files AssetRef. Tags are tag names, Props +// the front matter values by name (strings, numbers, booleans, dates as +// "YYYY-MM-DD", and lists of strings). +type ImportedPage = NotionPage + +type vaultNote struct { + file string // the Markdown file in the zip + key string // path without extension; for a TextBundle, the bundle without ".textbundle" + dir string // where its relative links start + title string + isDir bool // a folder without a note of its own +} + +type vaultReader struct { + *notionReader + kind VaultKind + root string // a single folder that holds everything, stripped from names + byKey map[string]int + byName map[string][]int // lower-case file name without extension -> pages + fileFor map[string][]string + refs []string // targets of the wikilinks of the note being read +} + +// ReadVault reads a zip of Markdown notes (kind from DetectArchive). Pages +// come parents first. +func ReadVault(data []byte, kind VaultKind) ([]NotionPage, []Asset, error) { + v := &vaultReader{ + notionReader: ¬ionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}, pageAt: map[string]int{}}, + kind: kind, byKey: map[string]int{}, byName: map[string][]int{}, fileFor: map[string][]string{}, + } + if err := v.open(data, false); err != nil { + return nil, nil, err + } + // Hidden folders (.obsidian, .trash, .git) are not part of the notes. + for name := range v.files { + for _, part := range strings.Split(name, "/") { + if strings.HasPrefix(part, ".") || part == "__MACOSX" { + delete(v.files, name) + break + } + } + } + v.root = commonRoot(v.files) + + notes := v.findNotes() + if len(notes) == 0 { + return nil, nil, ErrNoNotes + } + if len(notes) > maxNotionPages { + return nil, nil, fmt.Errorf("the archive has more than %d pages", maxNotionPages) + } + for i, n := range notes { + v.byKey[strings.ToLower(n.key)] = i + if n.file != "" { + v.pageAt[n.file] = i + } + if !n.isDir { + name := strings.ToLower(path.Base(n.key)) + v.byName[name] = append(v.byName[name], i) + } + } + for name := range v.files { + base := strings.ToLower(path.Base(name)) + v.fileFor[base] = append(v.fileFor[base], name) + } + for _, list := range v.fileFor { + // The shortest path wins, like Obsidian's "shortest path" links. + sort.Slice(list, func(i, j int) bool { + return len(list[i]) < len(list[j]) || len(list[i]) == len(list[j]) && list[i] < list[j] + }) + } + + pages := make([]NotionPage, len(notes)) + for i, n := range notes { + parent := -1 + for dir := path.Dir(n.key); dir != "." && dir != "/" && dir != ""; dir = path.Dir(dir) { + if p, ok := v.byKey[strings.ToLower(dir)]; ok && p != i { + parent = p + break + } + } + page := NotionPage{Title: n.title, Parent: parent, Doc: Node{Type: "doc", Content: []Node{{Type: "paragraph"}}}} + if n.file != "" { + var err error + if page, err = v.readNote(n, parent); err != nil { + return nil, nil, fmt.Errorf("%s: %w", v.shown(n.file), err) + } + } + if v.err != nil { + return nil, nil, v.err + } + pages[i] = page + } + return pages, v.assets, nil +} + +// shown is a file's name as the user knows it (with the archive's root folder). +func (v *vaultReader) shown(name string) string { return path.Join(v.root, name) } + +// commonRoot is the one folder every file is in ("" when there is none), and +// takes it off the names: zipping a vault folder puts it around everything. +func commonRoot(files map[string]*zip.File) string { + root := "" + for name := range files { + first, _, ok := strings.Cut(name, "/") + if !ok || (root != "" && first != root) || strings.HasSuffix(strings.ToLower(first), ".textbundle") { + return "" + } + root = first + } + if root == "" { + return "" + } + moved := make(map[string]*zip.File, len(files)) + for name, f := range files { + moved[strings.TrimPrefix(name, root+"/")] = f + } + for name := range files { + delete(files, name) + } + for name, f := range moved { + files[name] = f + } + return root +} + +// findNotes lists the pages: notes, TextBundles, and folders, sorted so that +// parents come first. +func (v *vaultReader) findNotes() []vaultNote { + var notes []vaultNote + seen := map[string]bool{} + bundles := map[string]bool{} + for name := range v.files { + // A TextBundle is a folder "Name.textbundle" with text.md (or + // .markdown, .txt) and an assets folder. + dir, base := path.Split(name) + dir = strings.TrimSuffix(dir, "/") + if strings.HasSuffix(strings.ToLower(dir), ".textbundle") && strings.HasPrefix(strings.ToLower(base), "text.") { + if bundles[dir] { + continue + } + bundles[dir] = true + key := dir[:len(dir)-len(".textbundle")] + notes = append(notes, vaultNote{file: name, key: key, dir: dir, title: path.Base(key)}) + seen[strings.ToLower(key)] = true + } + } + docwellExport := v.files["index.md"] != nil && hasPrefixFile(v.files, "_files/") + for name := range v.files { + lower := strings.ToLower(name) + ext := path.Ext(lower) + if ext != ".md" && ext != ".markdown" && ext != ".txt" { + continue + } + if strings.Contains(lower, ".textbundle/") || strings.HasSuffix(lower, ".excalidraw.md") { + continue + } + if docwellExport && (name == "index.md" || strings.HasPrefix(name, "_files/")) { + continue // Docwell's own space export: its index and files are not pages. + } + if ext == ".txt" && v.kind != VaultBear { + continue // Plain text files in a vault are attachments. + } + key := strings.TrimSuffix(name, path.Ext(name)) + if seen[strings.ToLower(key)] { + continue + } + seen[strings.ToLower(key)] = true + notes = append(notes, vaultNote{file: name, key: key, dir: path.Dir(name), title: path.Base(key)}) + } + // Folders that hold notes are pages, unless a note stands for them: + // "Guides.md" next to "Guides/", or "Guides/Guides.md". + dirs := map[string]bool{} + for _, n := range notes { + for d := path.Dir(n.key); d != "." && d != ""; d = path.Dir(d) { + dirs[d] = true + } + } + for d := range dirs { + if seen[strings.ToLower(d)] { + continue + } + inner := strings.ToLower(d + "/" + path.Base(d)) + folderNote := -1 + for i, n := range notes { + if strings.ToLower(n.key) == inner { + folderNote = i + } + } + if folderNote >= 0 { + // The note moves up to be the folder's page. + notes[folderNote].key = d + seen[strings.ToLower(d)] = true + continue + } + seen[strings.ToLower(d)] = true + notes = append(notes, vaultNote{key: d, title: path.Base(d), isDir: true}) + } + sort.Slice(notes, func(i, j int) bool { + di, dj := strings.Count(notes[i].key, "/"), strings.Count(notes[j].key, "/") + if di != dj { + return di < dj + } + return strings.ToLower(notes[i].key) < strings.ToLower(notes[j].key) + }) + return notes +} + +func hasPrefixFile(files map[string]*zip.File, prefix string) bool { + for name := range files { + if strings.HasPrefix(name, prefix) { + return true + } + } + return false +} + +func (v *vaultReader) readNote(n vaultNote, parent int) (NotionPage, error) { + data, err := v.read(v.files[n.file]) + if err != nil { + return NotionPage{}, err + } + data = bytes.TrimPrefix(data, []byte(utf8BOM)) + if !utf8.Valid(data) { + return NotionPage{}, errors.New("is not UTF-8 text") + } + text := strings.ReplaceAll(string(data), "\r\n", "\n") + meta, body := frontMatter(text) + v.refs = nil + md, inlineTags := v.prepare(body) + doc, err := FromMarkdownWith(md, ImportOptions{Resolve: func(u string) (string, bool) { return v.resolve(n.dir, u) }}) + if err != nil { + return NotionPage{}, err + } + title := n.title + if h1, rest := Title(doc); h1 != "" { + // Obsidian names a note by its file; Bear and most Markdown by the + // first heading. A heading that repeats the file name goes either way. + if v.kind != VaultObsidian || strings.EqualFold(strings.TrimSpace(h1), n.title) { + title, doc = strings.TrimSpace(h1), rest + } + } + if len(doc.Content) == 0 { + doc.Content = []Node{{Type: "paragraph"}} + } + page := NotionPage{Title: title, Parent: parent, Doc: doc} + tags, props := splitMeta(meta) + if t, ok := props["title"].(string); ok && strings.TrimSpace(t) != "" { + page.Title = strings.TrimSpace(t) + delete(props, "title") + } + page.Tags = uniqueFold(append(tags, inlineTags...)) + if len(props) > 0 { + page.Props = props + } + return page, nil +} + +// frontMatter splits YAML front matter ("---" lines around it, at the very +// start) off a note. Front matter that is not a YAML map is left in the text. +func frontMatter(text string) (map[string]any, string) { + lines := strings.Split(text, "\n") + if len(lines) < 2 || strings.TrimRight(lines[0], " \t") != "---" { + return nil, text + } + for j := 1; j < len(lines); j++ { + if l := strings.TrimRight(lines[j], " \t"); l != "---" && l != "..." { + continue + } + var meta map[string]any + if err := yaml.Unmarshal([]byte(strings.Join(lines[1:j], "\n")), &meta); err != nil { + return nil, text + } + return meta, strings.Join(lines[j+1:], "\n") + } + return nil, text +} + +// splitMeta turns front matter into tag names and property values. +func splitMeta(meta map[string]any) ([]string, map[string]any) { + var tags []string + props := map[string]any{} + keys := make([]string, 0, len(meta)) + for k := range meta { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + val := meta[k] + switch strings.ToLower(strings.TrimSpace(k)) { + case "tags", "tag": + for _, t := range metaList(val, true) { + if t = strings.TrimPrefix(strings.TrimSpace(t), "#"); t != "" { + tags = append(tags, t) + } + } + continue + case "aliases", "alias", "cssclass", "cssclasses", "position": + continue + } + if v, ok := metaValue(val); ok { + props[strings.TrimSpace(k)] = v + } + } + return tags, props +} + +var isoDateTime = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}(?:[T ][0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$`) + +// metaValue is a front matter value as an import keeps it: a string, +// float64, bool, a date ("YYYY-MM-DD"), or a list of strings. +func metaValue(v any) (any, bool) { + switch x := v.(type) { + case nil: + return nil, false + case string: + s := strings.TrimSpace(x) + if s == "" { + return nil, false + } + if isoDateTime.MatchString(s) { + return s[:10], true + } + return s, true + case bool: + return x, true + case int: + return float64(x), true + case int64: + return float64(x), true + case uint64: + return float64(x), true + case float64: + return x, true + case time.Time: + return x.Format(time.DateOnly), true + case []any: + list := metaList(x, false) + if len(list) == 0 { + return nil, false + } + return list, true + } + return nil, false // Maps and other shapes have no property type. +} + +// metaList reads a list of scalars; split also splits a single string at +// commas and spaces (how tags are often written). +func metaList(v any, split bool) []string { + var out []string + switch x := v.(type) { + case string: + if !split { + return []string{x} + } + out = append(out, strings.FieldsFunc(x, func(r rune) bool { return r == ',' || r == ' ' })...) + case []any: + for _, item := range x { + switch s := item.(type) { + case string: + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + case int, int64, float64, bool: + out = append(out, fmt.Sprint(s)) + } + } + } + return out +} + +func uniqueFold(list []string) []string { + var out []string + seen := map[string]bool{} + for _, s := range list { + if s = strings.TrimSpace(s); s == "" || seen[strings.ToLower(s)] { + continue + } + seen[strings.ToLower(s)] = true + out = append(out, s) + } + return out +} + +var ( + wikilink = regexp.MustCompile(`(!?)\[\[([^\[\]\n|]+?)(?:\|([^\[\]\n]*))?\]\]`) + obsidianNote = regexp.MustCompile(`(?s)%%.*?%%`) + blockID = regexp.MustCompile(`\s\^[A-Za-z0-9-]+$`) + inlineTag = regexp.MustCompile(`(?:^|\s)#([\p{L}\p{N}_][\p{L}\p{N}_/-]*)`) + bearLongTag = regexp.MustCompile(`(?:^|\s)#([\p{L}\p{N}_][^#\n]*?[^\s#])#(?:$|[\s.,;:!?)])`) + highlightMark = regexp.MustCompile(`==([^=\n]+)==`) + calloutLine = regexp.MustCompile(`^(\s*>\s*)\[!([A-Za-z-]+)\][+-]?\s*(.*)$`) + fence = regexp.MustCompile("^\\s{0,3}(`{3,}|~{3,})") + sizeOnly = regexp.MustCompile(`^\d+(?:x\d+)?$`) +) + +// prepare rewrites what Markdown readers do not know: wikilinks and embeds +// (to links whose target is "dwref:N", an entry of v.refs), Obsidian +// callouts and comments, highlights and block ids. It also collects #tags. +// Code blocks and inline code are left alone. +func (v *vaultReader) prepare(md string) (string, []string) { + md = obsidianNote.ReplaceAllString(md, "") + var tags []string + var out []string + open := "" + for _, line := range strings.Split(md, "\n") { + if open != "" { + if m := fence.FindStringSubmatch(line); m != nil && m[1][0] == open[0] && len(m[1]) >= len(open) && strings.TrimSpace(line[len(m[0]):]) == "" { + open = "" + } + out = append(out, line) + continue + } + if m := fence.FindStringSubmatch(line); m != nil { + open = m[1] + out = append(out, line) + continue + } + if m := calloutLine.FindStringSubmatch(line); m != nil { + out = append(out, m[1]+"[!"+calloutKind(m[2])+"]") + if title := strings.TrimSpace(m[3]); title != "" { + // The title is a paragraph of its own above the callout's text. + out = append(out, m[1]+"**"+title+"**") + line = strings.TrimRight(m[1], " ") + } else { + continue + } + } + line = blockID.ReplaceAllString(line, "") + line = outsideCode(line, func(s string) string { + scan := s + if v.kind == VaultBear { + for _, m := range bearLongTag.FindAllStringSubmatch(s, -1) { + tags = append(tags, m[1]) + } + scan = bearLongTag.ReplaceAllString(s, " ") + } + for _, m := range inlineTag.FindAllStringSubmatch(scan, -1) { + if !onlyDigits(m[1]) { + tags = append(tags, strings.TrimRight(m[1], "/-")) + } + } + s = highlightMark.ReplaceAllString(s, "$1") + return wikilink.ReplaceAllStringFunc(s, v.wikilink) + }) + out = append(out, line) + } + return strings.Join(out, "\n"), tags +} + +func onlyDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// calloutKind maps an Obsidian callout type to the GitHub alert it reads as. +func calloutKind(t string) string { + switch strings.ToLower(t) { + case "tip", "hint", "success", "check", "done": + return "TIP" + case "important", "question", "help", "faq", "example", "quote", "cite": + return "IMPORTANT" + case "warning", "caution", "attention": + return "WARNING" + case "failure", "fail", "missing", "danger", "error", "bug": + return "CAUTION" + } + return "NOTE" +} + +// outsideCode applies fn to the parts of a line that are not inline code. +func outsideCode(line string, fn func(string) string) string { + var b strings.Builder + i := 0 + for { + j := strings.IndexByte(line[i:], '`') + if j < 0 { + b.WriteString(fn(line[i:])) + return b.String() + } + j += i + b.WriteString(fn(line[i:j])) + n := j + for n < len(line) && line[n] == '`' { + n++ + } + ticks := line[j:n] + end := strings.Index(line[n:], ticks) + if end < 0 { + b.WriteString(line[j:]) + return b.String() + } + b.WriteString(line[j : n+end+len(ticks)]) + i = n + end + len(ticks) + } +} + +var linkTextEscape = strings.NewReplacer(`\`, `\\`, "`", "\\`", "*", `\*`, "_", `\_`, "[", `\[`, "]", `\]`, "<", `\<`, ">", `\>`, "#", `\#`, "!", `\!`, "|", `\|`, "~", `\~`) + +// wikilink rewrites one [[target|alias]] or ![[embed]] as a Markdown link. +func (v *vaultReader) wikilink(m string) string { + parts := wikilink.FindStringSubmatch(m) + embed, target, alias := parts[1] == "!", strings.TrimSuffix(strings.TrimSpace(parts[2]), `\`), strings.TrimSpace(parts[3]) + if target == "" { + return m + } + ref := "dwref:" + strconv.Itoa(len(v.refs)) + v.refs = append(v.refs, target) + name, heading, _ := strings.Cut(target, "#") + name = strings.TrimSpace(name) + text := alias + if text == "" || (embed && sizeOnly.MatchString(text)) { + text = path.Base(name) + if heading = strings.TrimPrefix(strings.TrimSpace(heading), "^"); heading != "" && !embed { + if name == "" { + text = heading + } else { + text = path.Base(name) + " > " + heading + } + } + } + if text == "" { + text = target + } + if embed && isImageName(name) { + return "![" + linkTextEscape.Replace(text) + "](" + ref + ")" + } + return "[" + linkTextEscape.Replace(text) + "](" + ref + ")" +} + +func isImageName(name string) bool { + switch strings.ToLower(path.Ext(name)) { + case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".avif": + return true + } + return false +} + +// resolve maps a link or image URL in a note whose links start at dir. +func (v *vaultReader) resolve(dir, raw string) (string, bool) { + raw = strings.TrimSpace(raw) + if rest, ok := strings.CutPrefix(raw, "dwref:"); ok { + n, err := strconv.Atoi(rest) + if err != nil || n >= len(v.refs) { + return "", true + } + return v.target(dir, v.refs[n]), true + } + u, err := url.Parse(raw) + if err != nil { + return "", true + } + if u.Scheme != "" || u.Host != "" { + return "", false // The usual check decides about outside links. + } + if u.Path == "" { + return "", false // An anchor in the same note. + } + if out := v.target(dir, u.Path); out != "" { + return out, true + } + return "", true // A file the archive left out. +} + +// target finds a note or file by a link's path: next to the note, from the +// archive's root, or failing those by its name alone (like Obsidian). +func (v *vaultReader) target(dir, target string) string { + name, _, _ := strings.Cut(target, "#") + name = strings.TrimSpace(strings.ReplaceAll(name, "\\", "/")) + if name == "" { + return "" + } + ext := strings.ToLower(path.Ext(name)) + isNote := ext == "" || ext == ".md" || ext == ".markdown" || (ext == ".txt" && v.kind == VaultBear) + if !isNote && !v.isFile(dir, name) && v.isNoteName(dir, name) { + isNote = true // "[[Meeting 2026.11.16]]": a dot in a note's name. + } + if isNote { + key := name + if ext == ".md" || ext == ".markdown" || ext == ".txt" { + key = strings.TrimSuffix(name, path.Ext(name)) + } + for _, k := range []string{path.Join(dir, key), strings.TrimPrefix(path.Clean("/"+key), "/")} { + if i, ok := v.byKey[strings.ToLower(k)]; ok { + return PageRef(i) + } + } + if list := v.byName[strings.ToLower(path.Base(key))]; len(list) > 0 { + return PageRef(list[0]) + } + return "" + } + for _, p := range []string{path.Join(dir, name), strings.TrimPrefix(path.Clean("/"+name), "/")} { + if _, ok := v.files[p]; ok { + return v.asset(p) + } + } + if list := v.fileFor[strings.ToLower(path.Base(name))]; len(list) > 0 { + return v.asset(list[0]) + } + return "" +} + +func (v *vaultReader) isFile(dir, name string) bool { + if _, ok := v.files[path.Join(dir, name)]; ok { + return true + } + return len(v.fileFor[strings.ToLower(path.Base(name))]) > 0 +} + +func (v *vaultReader) isNoteName(dir, name string) bool { + if _, ok := v.byKey[strings.ToLower(path.Join(dir, name))]; ok { + return true + } + return len(v.byName[strings.ToLower(path.Base(name))]) > 0 +} + +// asset is the placeholder of a file in the archive, read on first use. +func (v *vaultReader) asset(p string) string { + if ref, ok := v.assetAt[p]; ok { + return ref + } + if i, ok := v.pageAt[p]; ok { + return PageRef(i) + } + data, err := v.read(v.files[p]) + if err != nil { + if v.err == nil { + v.err = fmt.Errorf("%s: %w", v.shown(p), err) + } + return "" + } + ref := AssetRef(len(v.assets)) + v.assets = append(v.assets, Asset{Ref: ref, Name: path.Base(p), Data: data}) + v.assetAt[p] = ref + return ref +} diff --git a/Server/internal/convert/vault_test.go b/Server/internal/convert/vault_test.go new file mode 100644 index 0000000..5de99df --- /dev/null +++ b/Server/internal/convert/vault_test.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package convert + +import ( + "reflect" + "strings" + "testing" +) + +func pageNamed(t *testing.T, pages []NotionPage, title string) (int, NotionPage) { + t.Helper() + for i, p := range pages { + if p.Title == title { + return i, p + } + } + var titles []string + for _, p := range pages { + titles = append(titles, p.Title) + } + t.Fatalf("no page %q in %v", title, titles) + return -1, NotionPage{} +} + +func TestDetectArchive(t *testing.T) { + cases := map[string]struct { + files map[string][]byte + want VaultKind + }{ + "obsidian": {map[string][]byte{"Vault/.obsidian/app.json": []byte("{}"), "Vault/Note.md": []byte("x")}, VaultObsidian}, + "bear": {map[string][]byte{"Note.textbundle/text.markdown": []byte("# Note"), "Note.textbundle/info.json": []byte("{}")}, VaultBear}, + "notion": {map[string][]byte{"Home 0123456789abcdef0123456789abcdef.md": []byte("# Home")}, VaultNotion}, + "markdown": {map[string][]byte{"docs/a.md": []byte("# A"), "docs/b.md": []byte("# B")}, VaultMarkdown}, + "html": {map[string][]byte{"Home.html": []byte("

Home

")}, VaultNotion}, + } + for name, c := range cases { + got, err := DetectArchive(zipOf(t, c.files)) + if err != nil || got != c.want { + t.Errorf("%s: got %q, %v; want %q", name, got, err, c.want) + } + } +} + +func TestReadVaultObsidian(t *testing.T) { + img := pngOf(t, 4, 4) + data := zipOf(t, map[string][]byte{ + "My Vault/.obsidian/app.json": []byte("{}"), + "My Vault/.trash/Old.md": []byte("gone"), + "My Vault/Home.md": []byte("---\ntags: [project, \"#work\"]\nstatus: active\ndue: 2026-12-01\npriority: 2\ndone: false\naliases: [Start]\n---\n" + + "# Home\n\nSee [[Projects/Plan|the plan]] and [[Ideas#Later]], also [[Missing]].\n\n" + + "![[diagram.png|300]]\n\n> [!warning] Careful\n> Mind the gap.\n\nInline #idea and `#notatag` %%hidden%% text ^block1\n\n" + + "```\n[[not a link]] #nottag\n```\n"), + "My Vault/Ideas.md": []byte("Some ==marked== ideas. Link back to [Home](Home.md)."), + "My Vault/Projects/Plan.md": []byte("# Plan\n\nThe plan."), + "My Vault/Projects/Projects.md": []byte("Folder note for projects."), + "My Vault/Archive/2025/Old plan.md": []byte("old"), + "My Vault/attachments/diagram.png": img, + "My Vault/attachments/unused.pdf": []byte("%PDF"), + "My Vault/Drawing.excalidraw.md": []byte("excalidraw"), + "My Vault/Projects/notes for me.txt": []byte("an attachment, not a page"), + }) + pages, assets, err := ReadVault(data, VaultObsidian) + if err != nil { + t.Fatal(err) + } + if len(pages) != 7 { + var titles []string + for _, p := range pages { + titles = append(titles, p.Title) + } + t.Fatalf("got %d pages %v, want Home, Ideas, Projects, Archive, 2025, Old plan, Plan", len(pages), titles) + } + homeAt, home := pageNamed(t, pages, "Home") + ideasAt, _ := pageNamed(t, pages, "Ideas") + projectsAt, projects := pageNamed(t, pages, "Projects") + _, plan := pageNamed(t, pages, "Plan") + archiveAt, _ := pageNamed(t, pages, "Archive") + yearAt, year := pageNamed(t, pages, "2025") + _, old := pageNamed(t, pages, "Old plan") + if home.Parent != -1 || plan.Parent != projectsAt || projects.Parent != -1 || year.Parent != archiveAt || old.Parent != yearAt { + t.Errorf("tree: home %d plan %d projects %d year %d old %d", home.Parent, plan.Parent, projects.Parent, year.Parent, old.Parent) + } + if !strings.Contains(asJSON(t, projects.Doc), "Folder note for projects") { + t.Errorf("folder note is not the folder's page: %s", asJSON(t, projects.Doc)) + } + for i, p := range pages { + if p.Parent >= i { + t.Errorf("page %q comes before its parent", p.Title) + } + } + if want := []string{"project", "work", "idea"}; !reflect.DeepEqual(home.Tags, want) { + t.Errorf("tags = %v, want %v", home.Tags, want) + } + wantProps := map[string]any{"status": "active", "due": "2026-12-01", "priority": float64(2), "done": false} + if !reflect.DeepEqual(home.Props, wantProps) { + t.Errorf("props = %#v, want %#v", home.Props, wantProps) + } + j := asJSON(t, home.Doc) + for _, want := range []string{ + `"text":"the plan"`, `"href":"` + PageRef(planIndex(pages)) + `"`, + `"text":"Ideas \u003e Later"`, `"href":"` + PageRef(ideasAt) + `"`, + `"src":"asset:0"`, `"type":"callout"`, `"text":"Careful","marks":[{"type":"bold"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Mind the gap."`, + `[[not a link]] #nottag`, `#notatag`, + } { + if !strings.Contains(j, want) { + t.Errorf("Home lacks %s:\n%s", want, j) + } + } + for _, unwanted := range []string{"hidden", "^block1", `"text":"Home"`, "[[Missing]]"} { + if strings.Contains(j, unwanted) { + t.Errorf("Home still has %s:\n%s", unwanted, j) + } + } + if !strings.Contains(j, `also Missing.`) { + t.Errorf("an unresolved wikilink should keep its text:\n%s", j) + } + _, ideas := pageNamed(t, pages, "Ideas") + if ij := asJSON(t, ideas.Doc); !strings.Contains(ij, "Some marked ideas") || !strings.Contains(ij, `"href":"`+PageRef(homeAt)+`"`) { + t.Errorf("Ideas: %s", ij) + } + if len(assets) != 1 || assets[0].Name != "diagram.png" { + t.Errorf("assets = %v, want only diagram.png (used)", assets) + } +} + +func planIndex(pages []NotionPage) int { + for i, p := range pages { + if p.Title == "Plan" { + return i + } + } + return -1 +} + +func TestReadVaultMarkdownTitlesAndDocwellExport(t *testing.T) { + // A Docwell space export: index.md and _files/ are not pages, and + // "Guides.md" holds the pages in "Guides/". + data := zipOf(t, map[string][]byte{ + "index.md": []byte("# Space\n\n- [Guides](Guides.md)"), + "Guides.md": []byte("# Guides\n\nAll guides. ![pic](_files/pic.png)"), + "Guides/Setup.md": []byte("# Setting things up\n\nBack to [Guides](../Guides.md)."), + "_files/pic.png": pngOf(t, 2, 2), + "Guides/README.md": []byte("No heading here."), + }) + pages, assets, err := ReadVault(data, VaultMarkdown) + if err != nil { + t.Fatal(err) + } + if len(pages) != 3 || len(assets) != 1 { + t.Fatalf("got %d pages, %d assets", len(pages), len(assets)) + } + guidesAt, _ := pageNamed(t, pages, "Guides") + _, setup := pageNamed(t, pages, "Setting things up") // The heading names it, not the file. + _, readme := pageNamed(t, pages, "README") + if setup.Parent != guidesAt || readme.Parent != guidesAt { + t.Errorf("parents: %d %d, want %d", setup.Parent, readme.Parent, guidesAt) + } + if !strings.Contains(asJSON(t, setup.Doc), `"href":"`+PageRef(guidesAt)+`"`) { + t.Errorf("relative link not resolved: %s", asJSON(t, setup.Doc)) + } +} + +func TestReadVaultBear(t *testing.T) { + data := zipOf(t, map[string][]byte{ + "Groceries.textbundle/text.markdown": []byte("# Groceries\n\nMilk and eggs #shopping #home/kitchen #weekly plan#\n\n![](assets/list.png)\n\nSee [[Recipes]]."), + "Groceries.textbundle/info.json": []byte(`{"version":2}`), + "Groceries.textbundle/assets/list.png": pngOf(t, 2, 2), + "Recipes.textbundle/text.markdown": []byte("# Recipes\n\nPancakes."), + "Recipes.textbundle/assets/unused.jpeg": []byte("jpeg"), + }) + pages, assets, err := ReadVault(data, VaultBear) + if err != nil { + t.Fatal(err) + } + if len(pages) != 2 || len(assets) != 1 { + t.Fatalf("got %d pages, %d assets", len(pages), len(assets)) + } + recipesAt, _ := pageNamed(t, pages, "Recipes") + _, g := pageNamed(t, pages, "Groceries") + if want := []string{"weekly plan", "shopping", "home/kitchen"}; !reflect.DeepEqual(g.Tags, want) { + t.Errorf("tags = %v, want %v", g.Tags, want) + } + j := asJSON(t, g.Doc) + if !strings.Contains(j, `"src":"asset:0"`) || !strings.Contains(j, `"href":"`+PageRef(recipesAt)+`"`) { + t.Errorf("Groceries: %s", j) + } +} + +func TestFrontMatter(t *testing.T) { + meta, rest := frontMatter("---\ntitle: Hello\ncreated: 2026-01-02T10:00:00Z\nlinks:\n - a\n - b\nnested: {a: 1}\n---\nBody") + if rest != "Body" { + t.Errorf("rest = %q", rest) + } + tags, props := splitMeta(meta) + want := map[string]any{"title": "Hello", "created": "2026-01-02", "links": []string{"a", "b"}} + if len(tags) != 0 || !reflect.DeepEqual(props, want) { + t.Errorf("tags %v props %#v", tags, props) + } + for _, text := range []string{"--- not front matter\nx", "---\n: : bad yaml [\n---\nx", "No front matter"} { + if meta, rest := frontMatter(text); meta != nil || rest != text { + t.Errorf("%q: got %v, %q", text, meta, rest) + } + } +} diff --git a/Server/internal/directory/content.go b/Server/internal/directory/content.go index d2584cd..21cdfbb 100644 --- a/Server/internal/directory/content.go +++ b/Server/internal/directory/content.go @@ -24,6 +24,10 @@ const maxContentBytes = 8 << 20 type Docs interface { Content(ctx context.Context, page string) (json.RawMessage, error) Replace(ctx context.Context, page, user string, doc json.RawMessage, label string) error + // State is the page's document as one Yjs update. + State(ctx context.Context, page string) ([]byte, error) + // Apply merges a Yjs update into the page as an edit by user. + Apply(ctx context.Context, page, user string, update []byte) error // Kick reconnects the page's editors, so they pick up changed rights. Kick(page string) // Drop forgets a deleted page's live document. diff --git a/Server/internal/directory/importmeta.go b/Server/internal/directory/importmeta.go new file mode 100644 index 0000000..622d588 --- /dev/null +++ b/Server/internal/directory/importmeta.go @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "sort" + "strconv" + "strings" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/convert" +) + +// importMeta gives imported pages the tags and properties their files name +// (Obsidian front matter, #tags, a Readwise book's author): tags and +// properties are found by name, case aside, or made. A value that does not +// fit an existing property's type is left out; nothing here fails an import. +type importMeta struct { + s *Service + c access.Caller + ws string + loaded bool + tags map[string]string // lower-case name -> tag id + props map[string]*propertyRecord // lower-case name -> property +} + +func (s *Service) newImportMeta(c access.Caller, wsID string) *importMeta { + return &importMeta{s: s, c: c, ws: wsID} +} + +func (m *importMeta) load(ctx context.Context) { + if m.loaded { + return + } + m.loaded = true + m.tags, m.props = map[string]string{}, map[string]*propertyRecord{} + if rows, err := m.s.workspaceTags(ctx, m.ws); err == nil { + for _, r := range rows { + m.tags[strings.ToLower(r.Name)] = r.ID + } + } + if rows, err := m.s.workspaceProperties(ctx, m.ws); err == nil { + for i := range rows { + m.props[strings.ToLower(rows[i].Name)] = &rows[i] + } + } +} + +// apply sets the page's tags and property values. +func (m *importMeta) apply(ctx context.Context, pageID string, p convert.NotionPage) { + if len(p.Tags) == 0 && len(p.Props) == 0 { + return + } + m.load(ctx) + in := UpdatePageInput{} + var tagIDs []string + for _, name := range p.Tags { + if id := m.tag(ctx, name); id != "" && len(tagIDs) < maxTagsPerPage { + tagIDs = append(tagIDs, id) + } + } + if len(tagIDs) > 0 { + in.Tags = &tagIDs + } + keys := make([]string, 0, len(p.Props)) + for k := range p.Props { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + def := m.property(ctx, k, p.Props[k]) + if def == nil { + continue + } + if v, ok := m.value(ctx, def, p.Props[k]); ok { + if in.Properties == nil { + in.Properties = map[string]json.RawMessage{} + } + in.Properties[def.ID] = v + } + } + if in.Tags == nil && in.Properties == nil { + return + } + if _, err := m.s.UpdatePage(ctx, m.c, pageID, in); err != nil { + slog.Warn("import: tags and properties not set", "page", pageID, "err", err) + } +} + +func (m *importMeta) tag(ctx context.Context, name string) string { + name = strings.TrimSpace(name) + if r := []rune(name); len(r) > 60 { + name = string(r[:60]) + } + if name == "" { + return "" + } + if id, ok := m.tags[strings.ToLower(name)]; ok { + return id + } + t, err := m.s.CreateTag(ctx, m.c, m.ws, TagInput{Name: &name}) + if err != nil { + m.tags[strings.ToLower(name)] = "" // Guests cannot make tags; do not try again. + return "" + } + m.tags[strings.ToLower(name)] = t.ID + return t.ID +} + +// property finds the property named name, or makes one of the type the +// value suggests. +func (m *importMeta) property(ctx context.Context, name string, v any) *propertyRecord { + name = strings.TrimSpace(name) + if r := []rune(name); len(r) > maxPropertyName { + name = string(r[:maxPropertyName]) + } + if name == "" { + return nil + } + if def, ok := m.props[strings.ToLower(name)]; ok { + return def + } + typ := guessPropertyType(v) + created, err := m.s.CreateProperty(ctx, m.c, m.ws, PropertyInput{Name: &name, Type: &typ}) + if err != nil { + m.props[strings.ToLower(name)] = nil + return nil + } + rec := propertyRecord(created) + m.props[strings.ToLower(name)] = &rec + return &rec +} + +func guessPropertyType(v any) string { + switch x := v.(type) { + case bool: + return PropCheckbox + case float64: + return PropNumber + case []string: + return PropMultiSelect + case string: + if _, err := time.Parse(time.DateOnly, x); err == nil { + return PropDate + } + if (strings.HasPrefix(x, "https://") || strings.HasPrefix(x, "http://")) && validLink(x) { + return PropLink + } + } + return PropText +} + +// value is v as the property's type stores it. +func (m *importMeta) value(ctx context.Context, def *propertyRecord, v any) (json.RawMessage, bool) { + enc := func(x any) (json.RawMessage, bool) { + b, err := json.Marshal(x) + if err != nil { + return nil, false + } + if _, err := cleanValue(*def, b); err != nil { + return nil, false + } + return b, true + } + text := func() string { + switch x := v.(type) { + case []string: + return strings.Join(x, ", ") + case float64: + return strconv.FormatFloat(x, 'f', -1, 64) + } + return fmt.Sprint(v) + } + switch def.Type { + case PropText, PropLink, PropDate: + s := text() + if len(s) > maxTextValue { + s = s[:maxTextValue] + } + return enc(s) + case PropNumber: + switch x := v.(type) { + case float64: + return enc(x) + case string: + if f, err := strconv.ParseFloat(strings.ReplaceAll(x, ",", "."), 64); err == nil { + return enc(f) + } + } + case PropCheckbox: + switch x := v.(type) { + case bool: + return enc(x) + case string: + switch strings.ToLower(x) { + case "true", "yes", "x", "1": + return enc(true) + case "false", "no", "0": + return enc(false) + } + } + case PropSelect, PropMultiSelect: + var names []string + switch x := v.(type) { + case []string: + names = x + default: + names = []string{text()} + } + if def.Type == PropSelect && len(names) > 1 { + names = names[:1] + } + ids := m.options(ctx, def, names) + if len(ids) == 0 { + return nil, false + } + if def.Type == PropSelect { + return enc(ids[0]) + } + return enc(ids) + } + return nil, false +} + +// options returns the ids of the named choices, adding the missing ones. +func (m *importMeta) options(ctx context.Context, def *propertyRecord, names []string) []string { + var ids []string + var added bool + opts := append([]PropertyOption(nil), def.Options...) + for _, name := range names { + name = strings.TrimSpace(name) + if r := []rune(name); len(r) > 60 { + name = string(r[:60]) + } + if name == "" { + continue + } + found := "" + for _, o := range opts { + if strings.EqualFold(o.Name, name) { + found = o.ID + } + } + if found == "" { + if len(opts) >= maxOptions { + continue + } + found = newOptionID() + opts = append(opts, PropertyOption{ID: found, Name: name, Color: labelColors[2+len(opts)%(len(labelColors)-2)]}) + added = true + } + ids = append(ids, found) + } + if added { + updated, err := m.s.UpdateProperty(ctx, m.c, def.ID, PropertyInput{Options: &opts}) + if err != nil { + return nil + } + def.Options = updated.Options + } + return ids +} diff --git a/Server/internal/directory/snapshot.go b/Server/internal/directory/snapshot.go new file mode 100644 index 0000000..f1232f8 --- /dev/null +++ b/Server/internal/directory/snapshot.go @@ -0,0 +1,724 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "regexp" + "sort" + "strings" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Workspace snapshots --------------------------------------------------- +// +// A snapshot is one zip that restores a workspace as it was: its spaces and +// page tree, every page's document (pages/.ydoc, the Yjs state, and +// pages/.json, the same document as JSON), tags, properties, +// collections, comments, and every attached file (files/). snapshot.json +// holds the records. It covers what the person exporting can read: other +// people's journals and pages hidden from them are left out. Members, page +// sharing, share links, webhooks, AI settings and history are not part of +// it, since they belong to the instance more than to the content. +// +// Restoring makes a new workspace. Every record gets a new id, and the old +// ids are replaced wherever they appear (links, mentions, embedded pages, +// relations, property values), so a snapshot can be restored next to the +// workspace it came from. Documents come back from their Yjs state with the +// ids swapped in place (see remapBinary), so they are the same Yjs documents +// and comments stay anchored; the JSON copy is the fallback. + +const ( + snapshotFormat = "docwell-snapshot" + snapshotVersion = 1 + // MaxSnapshot caps a snapshot upload. + MaxSnapshot = 4 << 30 + // maxSnapshotRecords caps the records of each kind. + maxSnapshotRecords = 50000 +) + +type snapshotManifest struct { + Format string `json:"format"` + Version int `json:"version"` + Exported string `json:"exported"` + Workspace map[string]any `json:"workspace"` + Spaces []map[string]any `json:"spaces"` + Pages []map[string]any `json:"pages"` + Tags []map[string]any `json:"tags"` + Properties []map[string]any `json:"properties"` + Collections []map[string]any `json:"collections"` + Attachments []map[string]any `json:"attachments"` + Comments []map[string]any `json:"comments"` +} + +// The fields a snapshot keeps of each record. +var ( + snapWorkspaceFields = "name,settings,default_page_mode" + snapSpaceFields = "id,name,slug,icon,description,visibility,default_role,journal_owner,journal_template" + snapPageFields = "id,space,parent,title,icon,position,is_template,archived_at,pinned_at,restricted,full_width,font,default_mode,tags,properties,journal_date,creator,created,updated" + snapTagFields = "id,name,color" + snapPropertyFields = "id,name,type,options,visibility,position" + snapCollectionFields = "id,creator,name,icon,filter,include,exclude,shared" + snapAttachmentFields = "id,page,name,mime,size,created" + snapCommentFields = "id,page,parent,author,body,quote,anchor,reactions,resolved_at,resolved_by,edited_at,created" +) + +// Snapshot is a prepared workspace snapshot; WriteTo streams the zip. +type Snapshot struct { + Filename string + s *Service + manifest snapshotManifest +} + +// PrepareSnapshot lists what a snapshot of the workspace holds (workspace +// admin). +func (s *Service) PrepareSnapshot(ctx context.Context, c access.Caller, wsID string) (*Snapshot, error) { + ws, role, err := s.workspaceFor(ctx, c, wsID) + if err != nil { + return nil, err + } + if err := access.RenameWorkspace(role); err != nil { + return nil, err + } + m := snapshotManifest{Format: snapshotFormat, Version: snapshotVersion, Exported: time.Now().UTC().Format(time.RFC3339)} + byWS := pocketbase.ListOptions{Filter: fmt.Sprintf("workspace = '%s'", ws.ID)} + wsRec, err := pocketbase.Get[map[string]any](ctx, s.pb, "workspaces", ws.ID) + if err != nil { + return nil, mapPB(err, "workspace not found") + } + m.Workspace = pick(wsRec, snapWorkspaceFields) + + spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{Filter: byWS.Filter, Sort: "created"}) + if err != nil { + return nil, err + } + keep := map[string]bool{} + for _, sp := range spaces { + if sp.JournalOwner != "" && sp.JournalOwner != c.ID { + continue // Someone else's journal. + } + _, rules, err := s.spaceRules(ctx, c, sp.ID) + if err != nil { + continue + } + t, err := s.loadTree(ctx, sp.ID) + if err != nil { + return nil, err + } + var walk func(parent string) + walk = func(parent string) { + for _, p := range t.children[parent] { + if rules.role(p.ID) == "" { + continue // Hidden from the caller, with everything under it. + } + keep[p.ID] = true + walk(p.ID) + } + } + walk("") + raw, err := pocketbase.Get[map[string]any](ctx, s.pb, "spaces", sp.ID) + if err != nil { + return nil, err + } + m.Spaces = append(m.Spaces, pick(raw, snapSpaceFields)) + } + pages, err := listRaw(ctx, s, "pages", byWS.Filter+" && deleted_at = ''", snapPageFields) + if err != nil { + return nil, err + } + for _, p := range pages { + if keep[str(p["id"])] { + m.Pages = append(m.Pages, p) + } + } + for _, part := range []struct { + collection, fields string + into *[]map[string]any + }{ + {"tags", snapTagFields, &m.Tags}, + {"workspace_properties", snapPropertyFields, &m.Properties}, + {"page_collections", snapCollectionFields, &m.Collections}, + } { + if *part.into, err = listRaw(ctx, s, part.collection, byWS.Filter, part.fields); err != nil { + return nil, err + } + } + // Collections that are someone else's own are not shared with the caller. + shared := m.Collections[:0] + for _, col := range m.Collections { + if col["shared"] == true || str(col["creator"]) == c.ID { + shared = append(shared, col) + } + } + m.Collections = shared + for _, part := range []struct { + collection, fields string + into *[]map[string]any + }{ + {"attachments", snapAttachmentFields, &m.Attachments}, + {"comments", snapCommentFields, &m.Comments}, + } { + all, err := listRaw(ctx, s, part.collection, byWS.Filter, part.fields) + if err != nil { + return nil, err + } + for _, r := range all { + if keep[str(r["page"])] { + *part.into = append(*part.into, r) + } + } + } + stamp := time.Now().UTC().Format("2006-01-02") + return &Snapshot{Filename: exportName(ws.Name+" snapshot "+stamp, ".zip"), s: s, manifest: m}, nil +} + +// listRaw lists records as plain maps with the named fields. +func listRaw(ctx context.Context, s *Service, collection, filter, fields string) ([]map[string]any, error) { + rows, err := listAll[map[string]any](ctx, s, collection, pocketbase.ListOptions{Filter: filter, Fields: fields, Sort: "created"}) + if err != nil { + return nil, err + } + if len(rows) > maxSnapshotRecords { + return nil, apperr.Invalid(fmt.Sprintf("the workspace has more than %d %s", maxSnapshotRecords, collection)) + } + out := make([]map[string]any, len(rows)) + for i, r := range rows { + out[i] = pick(r, fields) + } + return out, nil +} + +// pick keeps the named fields of a record. +func pick(r map[string]any, fields string) map[string]any { + out := map[string]any{} + for _, f := range strings.Split(fields, ",") { + if v, ok := r[f]; ok { + out[f] = v + } + } + return out +} + +func str(v any) string { + s, _ := v.(string) + return s +} + +// WriteTo writes the zip. A page or file that fails to load is left out and +// logged, so one broken attachment does not lose the whole snapshot. +func (e *Snapshot) WriteTo(ctx context.Context, w io.Writer) error { + z := zip.NewWriter(w) + manifest, err := json.MarshalIndent(e.manifest, "", " ") + if err != nil { + return err + } + if err := writeZipFile(z, "snapshot.json", time.Now(), manifest); err != nil { + return err + } + for _, p := range e.manifest.Pages { + id := str(p["id"]) + mod := modTime(str(p["updated"])) + if raw, err := e.s.docs.Content(ctx, id); err != nil { + slog.Warn("snapshot: page content skipped", "page", id, "err", err) + } else if len(raw) > 0 && string(raw) != "null" { + if err := writeZipFile(z, "pages/"+id+".json", mod, raw); err != nil { + return err + } + } + if state, err := e.s.docs.State(ctx, id); err != nil { + slog.Warn("snapshot: page state skipped", "page", id, "err", err) + } else if len(state) > 0 { + if err := writeZipFile(z, "pages/"+id+".ydoc", mod, state); err != nil { + return err + } + } + } + for _, a := range e.manifest.Attachments { + rec := attachmentRecord{ID: str(a["id"])} + full, err := e.s.getAttachment(ctx, rec.ID) + if err != nil { + slog.Warn("snapshot: file skipped", "file", rec.ID, "err", err) + continue + } + if err := (&SpaceExport{s: e.s}).copyFile(ctx, z, exportedFile{rec: full, path: "files/" + rec.ID}); err != nil { + return err + } + } + return z.Close() +} + +// ---- Restore --------------------------------------------------------------- + +// RestoreInput names where a snapshot is restored and what it is. +type RestoreInput struct { + // Organization is required for superadmins (see CreateWorkspace). + Organization string + // Name is the new workspace's name; "" keeps the snapshot's. + Name string + File io.ReaderAt + Size int64 +} + +// pbID finds PocketBase record ids (15 lower-case letters and digits) in a +// JSON document. +var pbID = regexp.MustCompile(`\b[a-z0-9]{15}\b`) + +type idMap map[string]string + +// remap replaces old record ids in v (any JSON value) with the new ones. +func (m idMap) remap(v any) any { + raw, err := json.Marshal(v) + if err != nil { + return v + } + var out any + if json.Unmarshal(m.remapJSON(raw), &out) != nil { + return v + } + return out +} + +func (m idMap) remapJSON(raw []byte) []byte { + return pbID.ReplaceAllFunc(raw, func(b []byte) []byte { + if n, ok := m[string(b)]; ok { + return []byte(n) + } + return b + }) +} + +// ids maps a list of old ids, dropping the ones that were not restored. +func (m idMap) ids(v any) []string { + out := []string{} + list, _ := v.([]any) + for _, item := range list { + if n, ok := m[str(item)]; ok { + out = append(out, n) + } + } + return out +} + +// RestoreSnapshot makes a new workspace from a snapshot (org admins, in +// their organization; superadmins, in the one they name). The caller owns +// it through the cascade and is the creator of everything in it, except +// comments and collections by people who exist on this instance. +func (s *Service) RestoreSnapshot(ctx context.Context, c access.Caller, in RestoreInput) (Workspace, error) { + bad := func(msg string) (Workspace, error) { + return Workspace{}, apperr.InvalidFields(map[string]string{"file": msg}) + } + z, err := zip.NewReader(in.File, in.Size) + if err != nil { + return bad("The file is not a Docwell snapshot (.zip).") + } + files := map[string]*zip.File{} + for _, f := range z.File { + files[f.Name] = f + } + mf := files["snapshot.json"] + if mf == nil { + return bad("The zip holds no snapshot.json: it is not a Docwell snapshot.") + } + raw, err := readZipEntry(mf, 256<<20) + if err != nil { + return bad("snapshot.json could not be read.") + } + var m snapshotManifest + if json.Unmarshal(raw, &m) != nil || m.Format != snapshotFormat { + return bad("snapshot.json is not a Docwell snapshot.") + } + if m.Version > snapshotVersion { + return bad("The snapshot comes from a newer Docwell; update this server first.") + } + name := strings.TrimSpace(in.Name) + if name == "" { + name = str(m.Workspace["name"]) + } + ws, err := s.CreateWorkspace(ctx, c, CreateWorkspaceInput{Name: name, Organization: in.Organization}) + if err != nil { + return Workspace{}, err + } + r := &restorer{s: s, c: c, ws: ws.ID, files: files, ids: idMap{}, m: m} + if err := r.run(ctx); err != nil { + // Leave nothing half restored. + if derr := s.pb.Delete(context.WithoutCancel(ctx), "workspaces", ws.ID); derr != nil { + slog.Warn("snapshot restore: cleanup failed", "workspace", ws.ID, "err", derr) + } + return Workspace{}, err + } + full, err := s.getWorkspace(ctx, ws.ID) + if err != nil { + return Workspace{}, err + } + return full.view(ws.Role), nil +} + +func readZipEntry(f *zip.File, limit int64) ([]byte, error) { + if limit < 0 || f.UncompressedSize64 > uint64(limit) { + return nil, errors.New("too large") + } + rc, err := f.Open() + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + data, err := io.ReadAll(io.LimitReader(rc, limit+1)) + if err == nil && int64(len(data)) > limit { + err = errors.New("too large") + } + return data, err +} + +type restorer struct { + s *Service + c access.Caller + ws string + files map[string]*zip.File + ids idMap + m snapshotManifest + users map[string]bool // people of the snapshot who exist here +} + +func (r *restorer) create(ctx context.Context, collection string, body map[string]any) (string, error) { + rec, err := pocketbase.Create[struct { + ID string `json:"id"` + }](ctx, r.s.pb, collection, body) + if err != nil { + return "", fmt.Errorf("restoring %s: %w", collection, mapPB(err, "not found")) + } + return rec.ID, nil +} + +func (r *restorer) run(ctx context.Context) error { + if err := r.loadUsers(ctx); err != nil { + return err + } + patch := map[string]any{} + if v, ok := r.m.Workspace["settings"]; ok && v != nil { + patch["settings"] = v + } + if v := str(r.m.Workspace["default_page_mode"]); v != "" { + patch["default_page_mode"] = v + } + if len(patch) > 0 { + if _, err := pocketbase.Update[map[string]any](ctx, r.s.pb, "workspaces", r.ws, patch); err != nil { + return mapPB(err, "workspace not found") + } + } + for _, t := range r.m.Tags { + id, err := r.create(ctx, "tags", map[string]any{"workspace": r.ws, "name": t["name"], "color": t["color"]}) + if err != nil { + return err + } + r.ids[str(t["id"])] = id + } + for _, p := range r.m.Properties { + id, err := r.create(ctx, "workspace_properties", map[string]any{ + "workspace": r.ws, "name": p["name"], "type": p["type"], "options": p["options"], + "visibility": p["visibility"], "position": p["position"], + }) + if err != nil { + return err + } + r.ids[str(p["id"])] = id + } + for _, sp := range r.m.Spaces { + body := map[string]any{ + "workspace": r.ws, "name": sp["name"], "slug": sp["slug"], "icon": sp["icon"], + "description": sp["description"], "visibility": sp["visibility"], "default_role": sp["default_role"], + } + if owner := str(sp["journal_owner"]); owner != "" { + if !r.users[owner] { + owner = r.c.ID // The journal's owner is not on this instance: it becomes the restorer's. + } + body["journal_owner"] = owner + } + id, err := r.create(ctx, "spaces", body) + if err != nil { + return err + } + r.ids[str(sp["id"])] = id + } + if err := r.pages(ctx); err != nil { + return err + } + for _, sp := range r.m.Spaces { + if t := r.ids[str(sp["journal_template"])]; t != "" { + if _, err := pocketbase.Update[map[string]any](ctx, r.s.pb, "spaces", r.ids[str(sp["id"])], map[string]any{"journal_template": t}); err != nil { + return mapPB(err, "space not found") + } + } + } + if err := r.attachments(ctx); err != nil { + return err + } + if err := r.contents(ctx); err != nil { + return err + } + for _, col := range r.m.Collections { + creator := str(col["creator"]) + if !r.users[creator] { + creator = r.c.ID + } + if _, err := r.create(ctx, "page_collections", map[string]any{ + "workspace": r.ws, "creator": creator, "name": col["name"], "icon": col["icon"], + "filter": r.ids.remap(col["filter"]), "include": r.ids.ids(col["include"]), "exclude": r.ids.ids(col["exclude"]), + "shared": col["shared"], + }); err != nil { + return err + } + } + return r.comments(ctx) +} + +// loadUsers finds which people the snapshot names exist on this instance. +func (r *restorer) loadUsers(ctx context.Context) error { + want := map[string]bool{} + add := func(v any) { + if id := str(v); validID(id) { + want[id] = true + } + } + for _, sp := range r.m.Spaces { + add(sp["journal_owner"]) + } + for _, col := range r.m.Collections { + add(col["creator"]) + } + for _, cm := range r.m.Comments { + add(cm["author"]) + add(cm["resolved_by"]) + if re, ok := cm["reactions"].(map[string]any); ok { + for _, who := range re { + list, _ := who.([]any) + for _, id := range list { + add(id) + } + } + } + } + r.users = map[string]bool{r.c.ID: true} + ids := make([]string, 0, len(want)) + for id := range want { + ids = append(ids, id) + } + sort.Strings(ids) + for len(ids) > 0 { + n := min(len(ids), 50) + var parts []string + for _, id := range ids[:n] { + parts = append(parts, fmt.Sprintf("id = '%s'", id)) + } + ids = ids[n:] + found, err := listAll[struct { + ID string `json:"id"` + }](ctx, r.s, "users", pocketbase.ListOptions{Filter: strings.Join(parts, " || "), Fields: "id"}) + if err != nil { + return err + } + for _, u := range found { + r.users[u.ID] = true + } + } + return nil +} + +// pages creates the pages, parents first. +func (r *restorer) pages(ctx context.Context) error { + byID := map[string]map[string]any{} + for _, p := range r.m.Pages { + byID[str(p["id"])] = p + } + depth := func(p map[string]any) int { + d := 0 + for parent := str(p["parent"]); parent != "" && d < 1000; d++ { + next, ok := byID[parent] + if !ok { + break + } + parent = str(next["parent"]) + } + return d + } + order := append([]map[string]any(nil), r.m.Pages...) + sort.SliceStable(order, func(i, j int) bool { return depth(order[i]) < depth(order[j]) }) + for _, p := range order { + space := r.ids[str(p["space"])] + if space == "" { + continue + } + body := map[string]any{ + "workspace": r.ws, "space": space, "title": p["title"], "icon": p["icon"], "position": p["position"], + "creator": r.c.ID, "last_editor": r.c.ID, "mentions": []string{}, "links": []string{}, + "is_template": p["is_template"], "archived_at": p["archived_at"], "pinned_at": p["pinned_at"], + "restricted": p["restricted"], "full_width": p["full_width"], "font": p["font"], + "default_mode": p["default_mode"], "journal_date": p["journal_date"], + "tags": r.ids.ids(p["tags"]), + } + if parent := str(p["parent"]); parent != "" { + if body["parent"] = r.ids[parent]; body["parent"] == "" { + continue // Its parent was not restored either. + } + } + if props, ok := p["properties"].(map[string]any); ok && len(props) > 0 { + body["properties"] = r.ids.remap(props) + } + id, err := r.create(ctx, "pages", body) + if err != nil { + return err + } + r.ids[str(p["id"])] = id + } + return nil +} + +func (r *restorer) attachments(ctx context.Context) error { + for _, a := range r.m.Attachments { + page := r.ids[str(a["page"])] + f := r.files["files/"+str(a["id"])] + if page == "" || f == nil { + continue + } + name := cleanFilename(str(a["name"])) + rc, err := f.Open() + if err != nil { + return fmt.Errorf("restoring %s: %w", name, err) + } + rec, err := pocketbase.CreateWithFile[attachmentRecord](ctx, r.s.pb, "attachments", map[string]string{ + "workspace": r.ws, "page": page, "name": name, "mime": str(a["mime"]), "uploader": r.c.ID, + "size": fmt.Sprint(f.UncompressedSize64), + }, "file", name, rc) + _ = rc.Close() + if err != nil { + return fmt.Errorf("restoring %s: %w", name, mapPB(err, "page not found")) + } + r.ids[str(a["id"])] = rec.ID + } + return nil +} + +// contents writes every page's document with the new ids in it: its Yjs +// state where the snapshot has one, so comment anchors (Yjs positions) keep +// pointing at their text, otherwise its JSON. +func (r *restorer) contents(ctx context.Context) error { + for _, p := range r.m.Pages { + id := r.ids[str(p["id"])] + if id == "" { + continue + } + fail := func(err error) error { return fmt.Errorf("restoring %q: %w", str(p["title"]), err) } + if f := r.files["pages/"+str(p["id"])+".ydoc"]; f != nil { + state, err := readZipEntry(f, 256<<20) + if err != nil { + return fail(err) + } + if err := r.s.docs.Apply(ctx, id, r.c.ID, r.ids.remapBinary(state)); err == nil { + continue + } else { + slog.Warn("snapshot restore: Yjs state refused, using JSON", "page", id, "err", err) + } + } + f := r.files["pages/"+str(p["id"])+".json"] + if f == nil { + continue + } + raw, err := readZipEntry(f, 256<<20) + if err != nil { + return fail(err) + } + if !json.Valid(raw) { + return fail(errors.New("its document is not JSON")) + } + if err := r.s.docs.Replace(ctx, id, r.c.ID, r.ids.remapJSON(bytes.TrimSpace(raw)), "import"); err != nil { + return fail(err) + } + } + return nil +} + +// remapBinary swaps old ids for new ones in a Yjs update. Ids are 15 ASCII +// bytes both ways, so every string keeps its length (and every clock its +// value): the update stays valid byte for byte. +func (m idMap) remapBinary(data []byte) []byte { + out := append([]byte(nil), data...) + isID := func(b byte) bool { return b >= 'a' && b <= 'z' || b >= '0' && b <= '9' } + for i := 0; i < len(out); { + if !isID(out[i]) { + i++ + continue + } + j := i + for j < len(out) && isID(out[j]) { + j++ + } + // Within a run of id characters, look at every 15-byte window. + for k := i; k+15 <= j; k++ { + if n, ok := m[string(out[k:k+15])]; ok && len(n) == 15 { + copy(out[k:k+15], n) + k += 14 + } + } + i = j + } + return out +} + +// comments restores threads, then their replies. +func (r *restorer) comments(ctx context.Context) error { + for _, replies := range []bool{false, true} { + for _, cm := range r.m.Comments { + if (str(cm["parent"]) != "") != replies { + continue + } + page := r.ids[str(cm["page"])] + if page == "" { + continue + } + author := str(cm["author"]) + if !r.users[author] { + author = r.c.ID + } + body := map[string]any{ + "workspace": r.ws, "page": page, "author": author, "body": cm["body"], "quote": cm["quote"], + "anchor": r.ids.remap(cm["anchor"]), "resolved_at": cm["resolved_at"], "edited_at": cm["edited_at"], + } + if replies { + if body["parent"] = r.ids[str(cm["parent"])]; body["parent"] == "" { + continue + } + } + if by := str(cm["resolved_by"]); r.users[by] { + body["resolved_by"] = by + } + if re, ok := cm["reactions"].(map[string]any); ok { + kept := map[string][]string{} + for emoji, who := range re { + list, _ := who.([]any) + for _, id := range list { + if r.users[str(id)] { + kept[emoji] = append(kept[emoji], str(id)) + } + } + } + body["reactions"] = kept + } + id, err := r.create(ctx, "comments", body) + if err != nil { + return err + } + r.ids[str(cm["id"])] = id + } + } + return nil +} diff --git a/Server/internal/directory/snapshot_test.go b/Server/internal/directory/snapshot_test.go new file mode 100644 index 0000000..b23134f --- /dev/null +++ b/Server/internal/directory/snapshot_test.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "strings" + "testing" + + "docwell/server/internal/ycrdt" +) + +func TestRemapBinaryKeepsYjsUpdatesValid(t *testing.T) { + ctx := context.Background() + rt, err := ycrdt.New(ctx, "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rt.Close(ctx) }) + pool := ycrdt.NewPool(rt, 1) + + doc := `{"type":"doc","content":[{"type":"paragraph","content":[` + + `{"type":"text","text":"see ","marks":[]},` + + `{"type":"text","text":"the plan","marks":[{"type":"link","attrs":{"href":"/p/oldpage00000001"}}]}]},` + + `{"type":"image","attrs":{"src":"/api/v1/files/oldfile00000001","alt":"x"}},` + + `{"type":"paragraph","content":[{"type":"text","text":"unrelated words stay, page abcdefghijklmno too"}]}]}` + empty, err := pool.Compact(ctx, nil) + if err != nil { + t.Fatal(err) + } + update, err := pool.Replace(ctx, [][]byte{empty}, []byte(doc)) + if err != nil { + t.Fatal(err) + } + state, err := pool.Compact(ctx, [][]byte{empty, update}) + if err != nil { + t.Fatal(err) + } + m := idMap{"abcdefghijklmnp": "x", "oldpage00000001": "newpage00000001", "oldfile00000001": "newfile00000001"} + out, err := pool.Read(ctx, m.remapBinary(state)) + if err != nil { + t.Fatalf("remapped update is not readable: %v", err) + } + j := string(out.JSON) + for _, want := range []string{"/p/newpage00000001", "/api/v1/files/newfile00000001", "the plan", "page abcdefghijklmno too"} { + if !strings.Contains(j, want) { + t.Errorf("missing %s in %s", want, j) + } + } + if strings.Contains(j, "oldfile00000001") || strings.Contains(j, `/p/oldpage00000001"`) { + t.Errorf("old ids left in %s", j) + } +} + +func TestRemapJSONAndIDs(t *testing.T) { + m := idMap{"aaaaaaaaaaaaaaa": "bbbbbbbbbbbbbbb", "ccccccccccccccc": "ddddddddddddddd"} + got := string(m.remapJSON([]byte(`{"a":"/p/aaaaaaaaaaaaaaa#x","b":["ccccccccccccccc","eeeeeeeeeeeeeee"],"c":"aaaaaaaaaaaaaaaa"}`))) + want := `{"a":"/p/bbbbbbbbbbbbbbb#x","b":["ddddddddddddddd","eeeeeeeeeeeeeee"],"c":"aaaaaaaaaaaaaaaa"}` + if got != want { + t.Errorf("remapJSON = %s", got) + } + ids := m.ids([]any{"ccccccccccccccc", "zzzzzzzzzzzzzzz", 3}) + if len(ids) != 1 || ids[0] != "ddddddddddddddd" { + t.Errorf("ids = %v", ids) + } + props := m.remap(map[string]any{"aaaaaaaaaaaaaaa": []any{"opt1"}}) + if p, ok := props.(map[string]any); !ok || p["bbbbbbbbbbbbbbb"] == nil { + t.Errorf("remap = %v", props) + } +} diff --git a/Server/internal/directory/transfer.go b/Server/internal/directory/transfer.go index 1bae3a3..66ef94e 100644 --- a/Server/internal/directory/transfer.go +++ b/Server/internal/directory/transfer.go @@ -21,8 +21,8 @@ import ( // ---- Import and export ----------------------------------------------------- -// Import limits: one Markdown or HTML file, one Word file, one Notion -// export (zipped). +// Import limits: one Markdown, HTML or CSV file, one Word file, one archive +// (a zip, a Bear backup or an MHTML file). const ( maxImportBytes = 5 << 20 maxDocxBytes = 25 << 20 @@ -33,7 +33,7 @@ const ( maxPDFImage = 20 << 20 ) -// MaxImportFile is the largest file ImportPages accepts (a Notion export). +// MaxImportFile is the largest file ImportPages accepts (an archive). const MaxImportFile = maxZipBytes // SetPublicURL is docwell-server's external URL; exported files link @@ -156,8 +156,13 @@ type importBatch struct { // (editor) and returns the pages made at that level. Markdown (.md, // .markdown, .txt), HTML (.html, .htm) and Word (.docx) files become a page // each; a leading level-1 heading (or Word title) becomes the title, -// otherwise the file name does. A .zip is read as a Notion export and keeps -// its page tree, links between its pages and its images and files. +// otherwise the file name does. A CSV file becomes a page with a database, +// or, from Readwise, a page of highlights per book. An MHTML file (.mht, +// from OneNote) becomes a page per page it holds. A .zip is read as a Notion +// export, or as a folder of Markdown notes (an Obsidian vault, Bear's +// TextBundles, any Markdown with images); a Bear backup (.bear2bk) too. +// Archives keep their page tree, links between their pages, and their +// images and files; front matter and #tags become properties and tags. func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []ImportFile) ([]Page, error) { a, rules, err := s.spaceRules(ctx, c, spaceID) if err != nil { @@ -185,6 +190,7 @@ func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, par } out := []Page{} + meta := s.newImportMeta(c, a.space.Workspace) for _, b := range batches { created := make([]Page, len(b.pages)) for i, p := range b.pages { @@ -241,6 +247,7 @@ func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, par if err := s.docs.Replace(ctx, created[i].ID, c.ID, raw, "import"); err != nil { return out, err } + meta.apply(ctx, created[i].ID, p) } } return out, nil @@ -310,14 +317,59 @@ func readImport(f ImportFile) (importBatch, error) { return bad(" is not a Word document (.docx).") } return page(doc, assets), nil - case ".zip": + case ".csv": + if len(f.Data) > maxImportBytes { + return bad(" is larger than 5 MB.") + } + if !utf8.Valid(f.Data) { + return bad(" is not UTF-8 text.") + } + if convert.IsReadwiseCSV(f.Data) { + pages, err := convert.ReadReadwise(f.Data) + if err != nil { + return bad(" holds no Readwise highlights.") + } + return importBatch{pages: pages}, nil + } + doc, err := convert.FromCSV(f.Data) + if err != nil { + return bad(" could not be read as CSV.") + } + return page(doc, nil), nil + case ".mht", ".mhtml": if len(f.Data) > maxZipBytes { return bad(" is larger than 100 MB.") } - pages, assets, err := convert.ReadNotion(f.Data) + pages, assets, err := convert.ReadMHT(f.Data, name) switch { - case errors.Is(err, convert.ErrNotNotion): - return bad(" is not a Notion export: it holds no Markdown, HTML or CSV pages.") + case errors.Is(err, convert.ErrTooLarge): + return bad(" holds a part larger than 50 MB.") + case err != nil: + return bad(" is not a web archive (.mht) with pages in it.") + } + return importBatch{pages: pages, assets: assets}, nil + case ".zip", ".bear2bk": + if len(f.Data) > maxZipBytes { + return bad(" is larger than 100 MB.") + } + kind := convert.VaultBear + if ext == ".zip" { + var err error + if kind, err = convert.DetectArchive(f.Data); err != nil { + return bad(" is not a zip file.") + } + } + var pages []convert.NotionPage + var assets []convert.Asset + var err error + if kind == convert.VaultNotion { + pages, assets, err = convert.ReadNotion(f.Data) + } else { + pages, assets, err = convert.ReadVault(f.Data, kind) + } + switch { + case errors.Is(err, convert.ErrNotNotion), errors.Is(err, convert.ErrNoNotes): + return bad(" holds no Markdown, HTML or CSV pages.") case errors.Is(err, convert.ErrTooLarge): return bad(" unpacks to more than 512 MB, or holds a file larger than 50 MB.") case err != nil: @@ -325,5 +377,5 @@ func readImport(f ImportFile) (importBatch, error) { } return importBatch{pages: pages, assets: assets}, nil } - return bad(": only Markdown, HTML, Word (.docx) and Notion export (.zip) files can be imported.") + return bad(": only Markdown, HTML, Word (.docx), CSV, web archive (.mht), Bear backup (.bear2bk) and zip files can be imported.") } diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index 389c755..5e7e35c 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -59,17 +59,18 @@ func CurrentUser(ctx context.Context) (auth.User, bool) { } type api struct { - audit AuditService - auth AuthService - dir DirectoryService - settings SettingsService - files *auth.FileTokens - instance InstanceService - collab CollabHub - previews LinkPreviewer - push PushService - ai AIService - log *slog.Logger + audit AuditService + auth AuthService + dir DirectoryService + settings SettingsService + files *auth.FileTokens + instance InstanceService + collab CollabHub + previews LinkPreviewer + push PushService + ai AIService + calendars CalendarService + log *slog.Logger } // requireUser lets in a signed-in user, or an API token acting as its owner @@ -224,6 +225,7 @@ func (a *api) routes(mux *routeMux) { a.commentRoutes(mux) a.adminRoutes(mux) a.aiRoutes(mux) + a.calendarRoutes(mux) } func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool { diff --git a/Server/internal/httpapi/calendars.go b/Server/internal/httpapi/calendars.go new file mode 100644 index 0000000..b7bbee7 --- /dev/null +++ b/Server/internal/httpapi/calendars.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "net/http" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/calendar" +) + +// CalendarService reads people's calendars for their journals (ADR-16). +type CalendarService interface { + List(ctx context.Context, c access.Caller) ([]calendar.Account, error) + Create(ctx context.Context, c access.Caller, in calendar.AccountInput) (calendar.Account, error) + Update(ctx context.Context, c access.Caller, id string, in calendar.AccountInput) (calendar.Account, error) + Delete(ctx context.Context, c access.Caller, id string) error + Refresh(ctx context.Context, c access.Caller, id string) (calendar.Account, error) + Events(ctx context.Context, c access.Caller, from, to, tz string) ([]calendar.Event, error) +} + +var errNoCalendars = apperr.NotFound("calendars are not available on this server") + +func (a *api) withCalendars(next http.HandlerFunc) http.HandlerFunc { + return a.requireUser(func(w http.ResponseWriter, r *http.Request) { + if a.calendars == nil { + a.writeError(w, errNoCalendars) + return + } + next(w, r) + }) +} + +func (a *api) calendarRoutes(mux *routeMux) { + mux.HandleFunc("GET /api/v1/calendars", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + v, err := a.calendars.List(r.Context(), caller(r)) + a.respond(w, v, err) + })) + mux.HandleFunc("POST /api/v1/calendars", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + var in calendar.AccountInput + if !a.decode(w, r, &in) { + return + } + v, err := a.calendars.Create(r.Context(), caller(r), in) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("PATCH /api/v1/calendars/{id}", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + var in calendar.AccountInput + if !a.decode(w, r, &in) { + return + } + v, err := a.calendars.Update(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, v, err) + })) + mux.HandleFunc("DELETE /api/v1/calendars/{id}", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.calendars.Delete(r.Context(), caller(r), r.PathValue("id"))) + })) + mux.HandleFunc("POST /api/v1/calendars/{id}/refresh", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + v, err := a.calendars.Refresh(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("GET /api/v1/calendar/events", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + v, err := a.calendars.Events(r.Context(), caller(r), q.Get("from"), q.Get("to"), q.Get("tz")) + a.respond(w, v, err) + })) +} diff --git a/Server/internal/httpapi/router.go b/Server/internal/httpapi/router.go index b7556e5..ec5e414 100644 --- a/Server/internal/httpapi/router.go +++ b/Server/internal/httpapi/router.go @@ -41,9 +41,11 @@ type Deps struct { // Audit records changes and serves the audit log; nil turns both off. Audit AuditService // AI serves chat, writing actions, profiles and MCP; nil turns them off. - AI AIService - Admin http.Handler - Log *slog.Logger + AI AIService + // Calendars reads people's calendars for their journals; nil turns them off. + Calendars CalendarService + Admin http.Handler + Log *slog.Logger } // routeMux is a ServeMux that remembers its patterns, so a test can compare @@ -81,6 +83,9 @@ func newMux(d Deps) *routeMux { if d.AI != nil { a.ai = d.AI } + if d.Calendars != nil { + a.calendars = d.Calendars + } a.routes(mux) a.fileRoutes(mux, max(d.MaxUpload, 1<<20)) a.collabRoute(mux, d.CORSOrigins) diff --git a/Server/internal/httpapi/transfer.go b/Server/internal/httpapi/transfer.go index 9381691..4185499 100644 --- a/Server/internal/httpapi/transfer.go +++ b/Server/internal/httpapi/transfer.go @@ -18,6 +18,8 @@ type TransferService interface { ExportPage(ctx context.Context, c access.Caller, id, format string) (directory.Export, error) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []directory.ImportFile) ([]directory.Page, error) PrepareSpaceExport(ctx context.Context, c access.Caller, spaceID, format string) (*directory.SpaceExport, error) + PrepareSnapshot(ctx context.Context, c access.Caller, wsID string) (*directory.Snapshot, error) + RestoreSnapshot(ctx context.Context, c access.Caller, in directory.RestoreInput) (directory.Workspace, error) } // maxImportRequest caps one import request: up to 20 files, each within its @@ -54,6 +56,43 @@ func (a *api) transferRoutes(mux *routeMux) { a.log.Warn("space export failed", "space", r.PathValue("id"), "err", err) } })) + mux.HandleFunc("GET /api/v1/workspaces/{id}/snapshot", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + e, err := a.dir.PrepareSnapshot(r.Context(), caller(r), r.PathValue("id")) + if err != nil { + a.writeError(w, err) + return + } + h := w.Header() + h.Set("Content-Type", "application/zip") + h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename})) + h.Set("X-Content-Type-Options", "nosniff") + if err := e.WriteTo(r.Context(), w); err != nil { + a.log.Warn("snapshot failed", "workspace", r.PathValue("id"), "err", err) + } + })) + mux.HandleFunc("POST /api/v1/workspaces/restore", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, directory.MaxSnapshot+1<<20) + if err := r.ParseMultipartForm(32 << 20); err != nil { // The snapshot spills to a temporary file. + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data with a snapshot file"}) + return + } + defer func() { _ = r.MultipartForm.RemoveAll() }() + files := r.MultipartForm.File["file"] + if len(files) != 1 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "send one snapshot file"}) + return + } + f, err := files[0].Open() + if err != nil { + a.writeError(w, err) + return + } + defer func() { _ = f.Close() }() + ws, err := a.dir.RestoreSnapshot(r.Context(), caller(r), directory.RestoreInput{ + Organization: r.FormValue("organization"), Name: r.FormValue("name"), File: f, Size: files[0].Size, + }) + a.respondStatus(w, http.StatusCreated, ws, err) + })) mux.HandleFunc("POST /api/v1/spaces/{id}/import", a.requireUser(func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, maxImportRequest) if err := r.ParseMultipartForm(32 << 20); err != nil { // Larger uploads spill to temporary files. diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json index b8357c6..c0253c9 100644 --- a/Server/internal/pbschema/schema.json +++ b/Server/internal/pbschema/schema.json @@ -5185,5 +5185,210 @@ "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": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation2375276105", + "maxSelect": 1, + "minSelect": 0, + "name": "user", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1579384326", + "max": 80, + "min": 0, + "name": "name", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "select1002749145", + "maxSelect": 1, + "name": "kind", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": [ + "ics", + "caldav" + ] + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text4101391790", + "max": 2000, + "min": 0, + "name": "url", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text4166911607", + "max": 200, + "min": 0, + "name": "username", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1554180325", + "max": 2000, + "min": 0, + "name": "secret", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1716930793", + "max": 20, + "min": 0, + "name": "color", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "bool1358543748", + "name": "enabled", + "presentable": false, + "required": false, + "system": false, + "type": "bool" + }, + { + "help": "", + "hidden": false, + "id": "date3120574758", + "max": "", + "min": "", + "name": "last_sync", + "presentable": false, + "required": false, + "system": false, + "type": "date" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1066830442", + "max": 500, + "min": 0, + "name": "last_error", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "number1401378634", + "max": null, + "min": null, + "name": "events", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "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_1382459093", + "indexes": [ + "CREATE INDEX idx_calendar_accounts_user ON calendar_accounts (user)" + ], + "listRule": null, + "name": "calendar_accounts", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null } ] diff --git a/Web-App/frontend/package.json b/Web-App/frontend/package.json index 0189602..3b95a73 100644 --- a/Web-App/frontend/package.json +++ b/Web-App/frontend/package.json @@ -20,6 +20,7 @@ "@docwell/editor": "*", "@docwell/ui": "*", "dompurify": "^3.4.17", + "html-to-image": "^1.11.13", "marked": "^16.4.2", "pinia": "^4.1.0", "vue": "^3.5.44", diff --git a/Web-App/frontend/src/components/CalendarAccounts.vue b/Web-App/frontend/src/components/CalendarAccounts.vue new file mode 100644 index 0000000..8f6c767 --- /dev/null +++ b/Web-App/frontend/src/components/CalendarAccounts.vue @@ -0,0 +1,189 @@ + + + + diff --git a/Web-App/frontend/src/components/JournalEvents.vue b/Web-App/frontend/src/components/JournalEvents.vue new file mode 100644 index 0000000..46e4be5 --- /dev/null +++ b/Web-App/frontend/src/components/JournalEvents.vue @@ -0,0 +1,71 @@ + + + + diff --git a/Web-App/frontend/src/lib/pageImage.ts b/Web-App/frontend/src/lib/pageImage.ts new file mode 100644 index 0000000..d98f469 --- /dev/null +++ b/Web-App/frontend/src/lib/pageImage.ts @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// A page as a PNG: the article (title, properties, text) drawn the way it is +// on screen, in the current theme, without the editing controls around it. + +import { toBlob } from "html-to-image"; + +/** Elements left out of the picture: controls and notes, not content. */ +const skipped = [ + "[data-png-skip]", + // Controls, but not the callout's emoji, which is a button in the text. + "button:not([data-png-keep], .dw-callout__emoji)", + ".dw-callout__color", + ".drag-handle", + ".dw-drag-handle", + ".dw-block-menu", + ".dw-bubble", + ".tippy-box", + "[role=status]", + "[role=toolbar]", +]; + +function keep(node: Node): boolean { + if (!(node instanceof Element)) return true; + return !skipped.some((s) => node.matches(s)); +} + +/** + * Draws el as a PNG at twice its size (less for very long pages, so the + * picture stays within what browsers can draw). + */ +export async function elementPNG(el: HTMLElement): Promise { + const bg = getComputedStyle(document.body).backgroundColor || "#ffffff"; + const height = Math.max(el.scrollHeight, 1); + const pixelRatio = Math.max(0.5, Math.min(2, 16000 / height)); + const blob = await toBlob(el, { + backgroundColor: bg, + pixelRatio, + filter: keep, + // Room around the text, like the page on screen. + style: { margin: "0", padding: "32px 40px" }, + width: el.offsetWidth + 80, + height: height + 64, + // Fonts are part of the app; images come from the API with the file token. + cacheBust: false, + }); + if (!blob) throw new Error("could not draw the page"); + return blob; +} diff --git a/Web-App/frontend/src/locales/de.json b/Web-App/frontend/src/locales/de.json index 0ba50ca..d1e9583 100644 --- a/Web-App/frontend/src/locales/de.json +++ b/Web-App/frontend/src/locales/de.json @@ -187,7 +187,16 @@ "resend": "Erneut senden", "revoke": "Zurückziehen", "pageMode": "Neue Seiten öffnen als", - "pageModeHint": "Jede Seite lässt sich weiter umschalten, und jede Person kann für Seiten, die sie auf ihrem Gerät anlegt, anders wählen." + "pageModeHint": "Jede Seite lässt sich weiter umschalten, und jede Person kann für Seiten, die sie auf ihrem Gerät anlegt, anders wählen.", + "snapshotTitle": "Snapshot", + "snapshotHint": "Ein Zip mit den Bereichen, Seiten, Tags, Eigenschaften, Sammlungen, Kommentaren und Dateien, die du öffnen kannst. Stelle es als neuen Workspace wieder her, hier oder auf einem anderen Docwell-Server. Mitglieder, Freigaben, Webhooks und KI-Einstellungen sind nicht enthalten.", + "snapshotDownload": "Snapshot herunterladen", + "snapshotPreparing": "Snapshot wird erstellt…", + "restoreTitle": "Aus einem Snapshot wiederherstellen", + "restoreHint": "Erstellt einen neuen Workspace aus einem Snapshot-Zip. Der Name oben wird verwendet, wenn du ihn ausfüllst; sonst bleibt der Name des Snapshots.", + "restoreChoose": "Snapshot-Datei", + "restore": "Snapshot wiederherstellen", + "restoring": "Wird wiederhergestellt…" }, "space": { "new": "Neuer Bereich", @@ -226,7 +235,7 @@ }, "import": "Importieren", "importing": "Wird importiert…", - "importHint": "Markdown, HTML, Word (.docx) oder ein Notion-Export (.zip)", + "importHint": "Markdown, HTML, Word (.docx), CSV oder Readwise-CSV, OneNote (.mht), ein Bear-Backup (.bear2bk) oder ein Zip: Notion-Export, Obsidian-Vault, Bear-Notizen, Markdown-Ordner", "sharedWithYou": "Mit dir geteilt", "export": "Bereich exportieren", "exporting": "Wird exportiert…", @@ -306,7 +315,9 @@ "parentArchived": "Eine übergeordnete Seite ist archiviert, daher ist diese Seite schreibgeschützt.", "linkCopied": "Link kopiert", "openNewTab": "In neuem Tab öffnen", - "openBeside": "Daneben öffnen" + "openBeside": "Daneben öffnen", + "exportPng": "Als PNG exportieren", + "print": "Drucken" }, "trash": { "hint": "Unterseiten einer gelöschten Seite kommen mit zurück, wenn du sie wiederherstellst.", @@ -1435,5 +1446,33 @@ "summaryTitle": "Zusammenfassung von {name}", "transcript": "Transkript" } + }, + "calendars": { + "title": "Kalender", + "hint": "Abonniere deine Kalender, um ihre Termine auf deinen Journalseiten zu sehen. Nur du siehst sie, und Docwell liest sie nur.", + "none": "Noch keine Kalender.", + "new": "Kalender hinzufügen", + "add": "Hinzufügen", + "checking": "Wird geprüft…", + "cancel": "Abbrechen", + "kind": "Art", + "kinds": { + "ics": "iCal-Feed (.ics, webcal)", + "caldav": "CalDAV-Konto" + }, + "name": "Name", + "url": "Adresse", + "icsHint": "Eine webcal://- oder https://-Adresse einer .ics-Datei. Für Google Kalender die „Privatadresse im iCal-Format“ des Kalenders; für Outlook den ICS-Link eines veröffentlichten Kalenders.", + "caldavHint": "Dein CalDAV-Server oder die Adresse eines Kalenders, z. B. https://cloud.example.com/remote.php/dav für Nextcloud oder https://caldav.icloud.com mit einem app-spezifischen Passwort.", + "username": "Benutzername (optional)", + "password": "Passwort (optional)", + "color": "Farbe", + "show": "Anzeigen", + "refresh": "Aktualisieren", + "remove": "Entfernen", + "confirmRemove": "Den Kalender „{name}“ entfernen?", + "synced": "Gelesen {date} · {n} Termine", + "today": "Kalender", + "allDay": "Ganztägig" } } diff --git a/Web-App/frontend/src/locales/en.json b/Web-App/frontend/src/locales/en.json index d7b2718..e2dad91 100644 --- a/Web-App/frontend/src/locales/en.json +++ b/Web-App/frontend/src/locales/en.json @@ -187,7 +187,16 @@ "resend": "Resend", "revoke": "Revoke", "pageMode": "New pages open as", - "pageModeHint": "Each page can still be switched, and each person can choose otherwise for the pages they make on their device." + "pageModeHint": "Each page can still be switched, and each person can choose otherwise for the pages they make on their device.", + "snapshotTitle": "Snapshot", + "snapshotHint": "One zip with the spaces, pages, tags, properties, collections, comments and files you can open. Restore it as a new workspace, here or on another Docwell server. Members, sharing, webhooks and AI settings are not included.", + "snapshotDownload": "Download snapshot", + "snapshotPreparing": "Preparing snapshot…", + "restoreTitle": "Restore from a snapshot", + "restoreHint": "Makes a new workspace from a snapshot zip. The name above is used if you fill it in; otherwise the snapshot's name is kept.", + "restoreChoose": "Snapshot file", + "restore": "Restore snapshot", + "restoring": "Restoring…" }, "space": { "new": "New space", @@ -226,7 +235,7 @@ }, "import": "Import", "importing": "Importing…", - "importHint": "Markdown, HTML, Word (.docx) or a Notion export (.zip)", + "importHint": "Markdown, HTML, Word (.docx), CSV or Readwise CSV, OneNote (.mht), a Bear backup (.bear2bk), or a zip: Notion export, Obsidian vault, Bear notes, Markdown folder", "sharedWithYou": "Shared with you", "export": "Export space", "exporting": "Exporting…", @@ -306,7 +315,9 @@ "parentArchived": "A page above this one is archived, so this page is read-only.", "linkCopied": "Link copied", "openNewTab": "Open in new tab", - "openBeside": "Open beside" + "openBeside": "Open beside", + "exportPng": "Export as PNG", + "print": "Print" }, "trash": { "hint": "Pages inside a trashed page come back when you restore it.", @@ -1435,5 +1446,33 @@ "summaryTitle": "Summary of {name}", "transcript": "Transcript" } + }, + "calendars": { + "title": "Calendars", + "hint": "Subscribe to your calendars to see their events on your journal pages. Only you see them, and Docwell only reads them.", + "none": "No calendars yet.", + "new": "Add calendar", + "add": "Add", + "checking": "Checking…", + "cancel": "Cancel", + "kind": "Type", + "kinds": { + "ics": "iCal feed (.ics, webcal)", + "caldav": "CalDAV account" + }, + "name": "Name", + "url": "Address", + "icsHint": "A webcal:// or https:// address of an .ics file. For Google Calendar, use the calendar's “Secret address in iCal format”; for Outlook, a published calendar's ICS link.", + "caldavHint": "Your CalDAV server or one calendar's address, e.g. https://cloud.example.com/remote.php/dav for Nextcloud or https://caldav.icloud.com with an app-specific password.", + "username": "User name (optional)", + "password": "Password (optional)", + "color": "Colour", + "show": "Show", + "refresh": "Refresh", + "remove": "Remove", + "confirmRemove": "Remove the calendar “{name}”?", + "synced": "Read {date} · {n} events", + "today": "Calendar", + "allDay": "All day" } } diff --git a/Web-App/frontend/src/locales/es.json b/Web-App/frontend/src/locales/es.json index 1e9d5ac..0b0303a 100644 --- a/Web-App/frontend/src/locales/es.json +++ b/Web-App/frontend/src/locales/es.json @@ -187,7 +187,16 @@ "resend": "Reenviar", "revoke": "Revocar", "pageMode": "Las páginas nuevas se abren como", - "pageModeHint": "Cada página se puede cambiar igualmente, y cada persona puede elegir otra cosa para las páginas que cree en su dispositivo." + "pageModeHint": "Cada página se puede cambiar igualmente, y cada persona puede elegir otra cosa para las páginas que cree en su dispositivo.", + "snapshotTitle": "Instantánea", + "snapshotHint": "Un zip con los espacios, páginas, etiquetas, propiedades, colecciones, comentarios y archivos que puedes abrir. Restáuralo como un espacio de trabajo nuevo, aquí o en otro servidor Docwell. No incluye miembros, uso compartido, webhooks ni ajustes de IA.", + "snapshotDownload": "Descargar instantánea", + "snapshotPreparing": "Preparando instantánea…", + "restoreTitle": "Restaurar desde una instantánea", + "restoreHint": "Crea un espacio de trabajo nuevo a partir de un zip de instantánea. Se usa el nombre de arriba si lo rellenas; si no, se mantiene el de la instantánea.", + "restoreChoose": "Archivo de instantánea", + "restore": "Restaurar instantánea", + "restoring": "Restaurando…" }, "space": { "new": "Nuevo espacio", @@ -226,7 +235,7 @@ }, "import": "Importar", "importing": "Importando…", - "importHint": "Markdown, HTML, Word (.docx) o una exportación de Notion (.zip)", + "importHint": "Markdown, HTML, Word (.docx), CSV o CSV de Readwise, OneNote (.mht), una copia de Bear (.bear2bk) o un zip: exportación de Notion, bóveda de Obsidian, notas de Bear, carpeta de Markdown", "sharedWithYou": "Compartidas contigo", "export": "Exportar espacio", "exporting": "Exportando…", @@ -306,7 +315,9 @@ "parentArchived": "Una página superior está archivada, así que esta página es de solo lectura.", "linkCopied": "Enlace copiado", "openNewTab": "Abrir en una pestaña nueva", - "openBeside": "Abrir al lado" + "openBeside": "Abrir al lado", + "exportPng": "Exportar como PNG", + "print": "Imprimir" }, "trash": { "hint": "Las subpáginas de una página eliminada vuelven cuando la restauras.", @@ -1435,5 +1446,33 @@ "summaryTitle": "Resumen de {name}", "transcript": "Transcripción" } + }, + "calendars": { + "title": "Calendarios", + "hint": "Suscríbete a tus calendarios para ver sus eventos en tus páginas de diario. Solo tú los ves, y Docwell solo los lee.", + "none": "Aún no hay calendarios.", + "new": "Añadir calendario", + "add": "Añadir", + "checking": "Comprobando…", + "cancel": "Cancelar", + "kind": "Tipo", + "kinds": { + "ics": "Feed iCal (.ics, webcal)", + "caldav": "Cuenta CalDAV" + }, + "name": "Nombre", + "url": "Dirección", + "icsHint": "Una dirección webcal:// o https:// de un archivo .ics. Para Google Calendar, usa la «Dirección secreta en formato iCal» del calendario; para Outlook, el enlace ICS de un calendario publicado.", + "caldavHint": "Tu servidor CalDAV o la dirección de un calendario, p. ej. https://cloud.example.com/remote.php/dav para Nextcloud o https://caldav.icloud.com con una contraseña de aplicación.", + "username": "Usuario (opcional)", + "password": "Contraseña (opcional)", + "color": "Color", + "show": "Mostrar", + "refresh": "Actualizar", + "remove": "Quitar", + "confirmRemove": "¿Quitar el calendario «{name}»?", + "synced": "Leído {date} · {n} eventos", + "today": "Calendario", + "allDay": "Todo el día" } } diff --git a/Web-App/frontend/src/locales/fr.json b/Web-App/frontend/src/locales/fr.json index a3bad9a..5d1b1cc 100644 --- a/Web-App/frontend/src/locales/fr.json +++ b/Web-App/frontend/src/locales/fr.json @@ -187,7 +187,16 @@ "resend": "Renvoyer", "revoke": "Révoquer", "pageMode": "Les nouvelles pages s’ouvrent en", - "pageModeHint": "Chaque page peut toujours être basculée, et chacun peut choisir autrement pour les pages créées sur son appareil." + "pageModeHint": "Chaque page peut toujours être basculée, et chacun peut choisir autrement pour les pages créées sur son appareil.", + "snapshotTitle": "Instantané", + "snapshotHint": "Un zip avec les espaces, pages, tags, propriétés, collections, commentaires et fichiers que vous pouvez ouvrir. Restaurez-le comme nouvel espace de travail, ici ou sur un autre serveur Docwell. Les membres, partages, webhooks et réglages d'IA ne sont pas inclus.", + "snapshotDownload": "Télécharger l'instantané", + "snapshotPreparing": "Préparation de l'instantané…", + "restoreTitle": "Restaurer depuis un instantané", + "restoreHint": "Crée un nouvel espace de travail à partir d'un zip d'instantané. Le nom ci-dessus est utilisé s'il est rempli ; sinon celui de l'instantané est conservé.", + "restoreChoose": "Fichier d'instantané", + "restore": "Restaurer l'instantané", + "restoring": "Restauration…" }, "space": { "new": "Nouvel espace", @@ -226,7 +235,7 @@ }, "import": "Importer", "importing": "Importation…", - "importHint": "Markdown, HTML, Word (.docx) ou un export Notion (.zip)", + "importHint": "Markdown, HTML, Word (.docx), CSV ou CSV Readwise, OneNote (.mht), une sauvegarde Bear (.bear2bk) ou un zip : export Notion, coffre Obsidian, notes Bear, dossier Markdown", "sharedWithYou": "Partagées avec vous", "export": "Exporter l’espace", "exporting": "Exportation…", @@ -306,7 +315,9 @@ "parentArchived": "Une page parente est archivée, cette page est donc en lecture seule.", "linkCopied": "Lien copié", "openNewTab": "Ouvrir dans un nouvel onglet", - "openBeside": "Ouvrir à côté" + "openBeside": "Ouvrir à côté", + "exportPng": "Exporter en PNG", + "print": "Imprimer" }, "trash": { "hint": "Les sous-pages d’une page supprimée reviennent quand vous la restaurez.", @@ -1435,5 +1446,33 @@ "summaryTitle": "Résumé de {name}", "transcript": "Transcription" } + }, + "calendars": { + "title": "Agendas", + "hint": "Abonnez-vous à vos agendas pour voir leurs événements sur vos pages de journal. Vous seul les voyez, et Docwell ne fait que les lire.", + "none": "Aucun agenda pour l'instant.", + "new": "Ajouter un agenda", + "add": "Ajouter", + "checking": "Vérification…", + "cancel": "Annuler", + "kind": "Type", + "kinds": { + "ics": "Flux iCal (.ics, webcal)", + "caldav": "Compte CalDAV" + }, + "name": "Nom", + "url": "Adresse", + "icsHint": "Une adresse webcal:// ou https:// d'un fichier .ics. Pour Google Agenda, utilisez l'« adresse secrète au format iCal » de l'agenda ; pour Outlook, le lien ICS d'un calendrier publié.", + "caldavHint": "Votre serveur CalDAV ou l'adresse d'un agenda, par ex. https://cloud.example.com/remote.php/dav pour Nextcloud ou https://caldav.icloud.com avec un mot de passe pour app.", + "username": "Nom d'utilisateur (facultatif)", + "password": "Mot de passe (facultatif)", + "color": "Couleur", + "show": "Afficher", + "refresh": "Actualiser", + "remove": "Retirer", + "confirmRemove": "Retirer l'agenda « {name} » ?", + "synced": "Lu {date} · {n} événements", + "today": "Agenda", + "allDay": "Toute la journée" } } diff --git a/Web-App/frontend/src/locales/pl.json b/Web-App/frontend/src/locales/pl.json index 4a3fc0c..8e53bd1 100644 --- a/Web-App/frontend/src/locales/pl.json +++ b/Web-App/frontend/src/locales/pl.json @@ -187,7 +187,16 @@ "resend": "Wyślij ponownie", "revoke": "Cofnij", "pageMode": "Nowe strony otwieraj jako", - "pageModeHint": "Każdą stronę nadal można przełączyć, a każdy może wybrać inaczej dla stron tworzonych na swoim urządzeniu." + "pageModeHint": "Każdą stronę nadal można przełączyć, a każdy może wybrać inaczej dla stron tworzonych na swoim urządzeniu.", + "snapshotTitle": "Migawka", + "snapshotHint": "Jeden zip z przestrzeniami, stronami, tagami, właściwościami, kolekcjami, komentarzami i plikami, które możesz otworzyć. Przywróć go jako nowy obszar roboczy, tutaj lub na innym serwerze Docwell. Członkowie, udostępnienia, webhooki i ustawienia AI nie są uwzględnione.", + "snapshotDownload": "Pobierz migawkę", + "snapshotPreparing": "Przygotowywanie migawki…", + "restoreTitle": "Przywróć z migawki", + "restoreHint": "Tworzy nowy obszar roboczy z pliku zip migawki. Jeśli wpiszesz nazwę powyżej, zostanie użyta; w przeciwnym razie zostanie nazwa z migawki.", + "restoreChoose": "Plik migawki", + "restore": "Przywróć migawkę", + "restoring": "Przywracanie…" }, "space": { "new": "Nowa przestrzeń", @@ -226,7 +235,7 @@ }, "import": "Importuj", "importing": "Importowanie…", - "importHint": "Markdown, HTML, Word (.docx) lub eksport z Notion (.zip)", + "importHint": "Markdown, HTML, Word (.docx), CSV lub CSV z Readwise, OneNote (.mht), kopia Bear (.bear2bk) albo zip: eksport z Notion, sejf Obsidian, notatki Bear, folder Markdown", "sharedWithYou": "Udostępnione Tobie", "export": "Eksportuj przestrzeń", "exporting": "Eksportowanie…", @@ -306,7 +315,9 @@ "parentArchived": "Strona nadrzędna jest zarchiwizowana, więc ta strona jest tylko do odczytu.", "linkCopied": "Skopiowano link", "openNewTab": "Otwórz w nowej karcie", - "openBeside": "Otwórz obok" + "openBeside": "Otwórz obok", + "exportPng": "Eksportuj jako PNG", + "print": "Drukuj" }, "trash": { "hint": "Strony wewnątrz przywróconej strony wracają razem z nią.", @@ -1435,5 +1446,33 @@ "summaryTitle": "Podsumowanie: {name}", "transcript": "Transkrypcja" } + }, + "calendars": { + "title": "Kalendarze", + "hint": "Subskrybuj swoje kalendarze, aby widzieć ich wydarzenia na stronach dziennika. Widzisz je tylko ty, a Docwell jedynie je odczytuje.", + "none": "Brak kalendarzy.", + "new": "Dodaj kalendarz", + "add": "Dodaj", + "checking": "Sprawdzanie…", + "cancel": "Anuluj", + "kind": "Rodzaj", + "kinds": { + "ics": "Kanał iCal (.ics, webcal)", + "caldav": "Konto CalDAV" + }, + "name": "Nazwa", + "url": "Adres", + "icsHint": "Adres webcal:// lub https:// pliku .ics. W Kalendarzu Google użyj „Tajnego adresu w formacie iCal”; w Outlooku linku ICS opublikowanego kalendarza.", + "caldavHint": "Twój serwer CalDAV lub adres jednego kalendarza, np. https://cloud.example.com/remote.php/dav dla Nextcloud albo https://caldav.icloud.com z hasłem do aplikacji.", + "username": "Nazwa użytkownika (opcjonalnie)", + "password": "Hasło (opcjonalnie)", + "color": "Kolor", + "show": "Pokaż", + "refresh": "Odśwież", + "remove": "Usuń", + "confirmRemove": "Usunąć kalendarz „{name}”?", + "synced": "Odczytano {date} · wydarzeń: {n}", + "today": "Kalendarz", + "allDay": "Cały dzień" } } diff --git a/Web-App/frontend/src/style.css b/Web-App/frontend/src/style.css index 537c9c8..edb663c 100644 --- a/Web-App/frontend/src/style.css +++ b/Web-App/frontend/src/style.css @@ -6,3 +6,60 @@ /* Lets apps that reuse this source (Desktop-App) pick up its classes. */ @source "./"; + +/* + * Printing a page (the page menu's Print, or the browser's): only the page's + * article, at its full length, without the app around it or the editing + * controls in it. Long pages break between blocks where they can. + */ +@media print { + @page { + margin: 16mm 14mm; + } + html, + body { + background: #fff !important; + } + *:has(.dw-print-page) { + display: block !important; + position: static !important; + overflow: visible !important; + height: auto !important; + min-height: 0 !important; + max-height: none !important; + padding: 0 !important; + margin: 0 !important; + border: 0 !important; + box-shadow: none !important; + } + body *:not(.dw-print-page, .dw-print-page *, :has(.dw-print-page)) { + display: none !important; + } + .dw-print-page { + max-width: none !important; + padding: 0 !important; + } + .dw-print-page + :is( + button:not(.dw-callout__emoji), + .dw-callout__color, + [data-png-skip], + [role="status"], + [role="toolbar"], + .drag-handle, + .dw-drag-handle + ) { + display: none !important; + } + .dw-print-page :is(h1, h2, h3, h4, h5, h6) { + break-after: avoid; + } + .dw-print-page :is(pre, blockquote, figure, img, table tr, [data-type="callout"]) { + break-inside: avoid; + } + .dw-print-page a[href^="http"]::after { + content: " (" attr(href) ")"; + font-size: 0.8em; + color: var(--dw-ink-muted); + } +} diff --git a/Web-App/frontend/src/views/page/PageView.vue b/Web-App/frontend/src/views/page/PageView.vue index 374116d..fdb1495 100644 --- a/Web-App/frontend/src/views/page/PageView.vue +++ b/Web-App/frontend/src/views/page/PageView.vue @@ -22,6 +22,7 @@ import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; import { useApi, useToken } from "../../api"; 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 PageList from "../../components/PageList.vue"; @@ -32,6 +33,7 @@ import { useEditorLabels, useMentions, usePageLinks } from "../../composables/us import { useFileHost } from "../../composables/useFiles"; import { useSplit } from "../../composables/useSplit"; import { saveBlob } from "../../lib/download"; +import { elementPNG } from "../../lib/pageImage"; import { usePlatform, useRuntimeConfig } from "../../platform"; import { useAuthStore } from "../../stores/auth"; import { useFavoritesStore } from "../../stores/favorites"; @@ -560,6 +562,15 @@ const exportAs = (format: "markdown" | "html" | "pdf" | "docx") => saveBlob(blob, filename); }); +// The page as a picture, drawn in the browser from what is on screen. +const articleRef = ref(null); +const exportPNG = () => + run(async () => { + if (!articleRef.value) return; + await saveTitle(); + saveBlob(await elementPNG(articleRef.value), `${title.value.trim() || t("home.untitled")}.png`); + }); + const menu = computed(() => [ ...(mode.value === "page" ? [{ label: t("page.find"), icon: "search" as const, onSelect: () => editorRef.value?.openFind() }] @@ -627,6 +638,12 @@ const menu = computed(() => [ { label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") }, { label: t("page.exportPdf"), icon: "download", onSelect: () => exportAs("pdf") }, { label: t("page.exportDocx"), icon: "download", onSelect: () => exportAs("docx") }, + ...(mode.value === "page" && !props.record + ? [ + { label: t("page.exportPng"), icon: "download" as const, onSelect: exportPNG }, + { label: t("page.print"), icon: "file" as const, onSelect: () => window.print() }, + ] + : []), ]); const addChild = () => @@ -843,7 +860,8 @@ const purge = () =>
+ }} + +
diff --git a/Web-App/frontend/src/views/space/SpaceView.vue b/Web-App/frontend/src/views/space/SpaceView.vue index c03ffb9..48229e3 100644 --- a/Web-App/frontend/src/views/space/SpaceView.vue +++ b/Web-App/frontend/src/views/space/SpaceView.vue @@ -169,7 +169,7 @@ async function newPage() { ref="picker" type="file" multiple - accept=".md,.markdown,.txt,.html,.htm,.docx,.zip,text/markdown,text/html" + accept=".md,.markdown,.txt,.html,.htm,.docx,.csv,.mht,.mhtml,.zip,.bear2bk,text/markdown,text/html,text/csv" class="hidden" data-testid="import-input" @change="importPicked" diff --git a/Web-App/frontend/src/views/workspace/NewWorkspaceView.vue b/Web-App/frontend/src/views/workspace/NewWorkspaceView.vue index 9276e71..4d4b517 100644 --- a/Web-App/frontend/src/views/workspace/NewWorkspaceView.vue +++ b/Web-App/frontend/src/views/workspace/NewWorkspaceView.vue @@ -31,6 +31,27 @@ onMounted(async () => { } }); +// Restoring a snapshot makes the workspace from the file; the name is optional then. +const snapshot = ref(null); +const restoring = ref(false); +async function restore() { + if (!snapshot.value) return; + restoring.value = true; + errors.reset(); + try { + const ws = await api.workspaces.restore(snapshot.value, { + name: name.value.trim() || undefined, + organization: isSuperadmin.value ? organization.value : undefined, + }); + await workspaces.load(); + router.replace({ name: "workspace-settings", params: { id: ws.id } }); + } catch (e) { + errors.show(e); + } finally { + restoring.value = false; + } +} + async function submit() { busy.value = true; errors.reset(); @@ -62,5 +83,25 @@ async function submit() { {{ $t("workspace.create") }} +
+

{{ $t("workspace.restoreTitle") }}

+

{{ $t("workspace.restoreHint") }}

+ + + {{ $t(restoring ? "workspace.restoring" : "workspace.restore") }} + +
diff --git a/Web-App/frontend/src/views/workspace/WorkspaceSettingsView.vue b/Web-App/frontend/src/views/workspace/WorkspaceSettingsView.vue index 31a4c04..d5cd301 100644 --- a/Web-App/frontend/src/views/workspace/WorkspaceSettingsView.vue +++ b/Web-App/frontend/src/views/workspace/WorkspaceSettingsView.vue @@ -15,6 +15,7 @@ import WorkspaceWebhooks from "../../components/WorkspaceWebhooks.vue"; import { useFormErrors } from "../../composables/useFormErrors"; import { useAuthStore } from "../../stores/auth"; import { atLeast, grantableRoles, useWorkspacesStore } from "../../stores/workspaces"; +import { saveBlob } from "../../lib/download"; const props = defineProps<{ id: string }>(); const api = useApi(); @@ -98,6 +99,20 @@ async function copyLink(link: string) { setTimeout(() => (copied.value = false), 2000); } +const snapshotting = ref(false); +async function downloadSnapshot() { + snapshotting.value = true; + errors.reset(); + try { + const { blob, filename } = await api.workspaces.snapshot(props.id); + saveBlob(blob, filename); + } catch (e) { + errors.show(e); + } finally { + snapshotting.value = false; + } +} + async function removeWorkspace() { if (!ws.value || !confirm(t("workspace.confirmDelete", { name: ws.value.name }))) return; busy.value = true; @@ -259,6 +274,14 @@ async function removeWorkspace() { +
+

{{ $t("workspace.snapshotTitle") }}

+

{{ $t("workspace.snapshotHint") }}

+ + {{ $t(snapshotting ? "workspace.snapshotPreparing" : "workspace.snapshotDownload") }} + +
+

{{ $t("org.dangerTitle") }}

{{ $t("workspace.deleteHint") }}

diff --git a/Web-Clipper/README.md b/Web-Clipper/README.md new file mode 100644 index 0000000..02e530f --- /dev/null +++ b/Web-Clipper/README.md @@ -0,0 +1,29 @@ +# Docwell Web Clipper + +A browser extension (Manifest V3, Chrome, Edge and Firefox 128+) that saves the page you are reading to Docwell as a new page: the article on it (found with Mozilla's Readability), or only what you selected, as Markdown with its links and pictures, under a note saying where it came from. + +It reads a page only when you click it, turns it into Markdown inside the extension, and sends it to your Docwell server through the import API (`POST /api/v1/spaces/{id}/import`). It talks to no other server. + +## Build + +```sh +npm install +npm run build -w @docwell/web-clipper +``` + +The extension is in `Web-Clipper/dist/`. + +- **Chrome / Edge:** open `chrome://extensions`, turn on *Developer mode*, choose *Load unpacked* and pick `dist/`. +- **Firefox:** open `about:debugging#/runtime/this-firefox`, choose *Load Temporary Add-on…* and pick `dist/manifest.json`. For a lasting install, sign the zipped `dist/` folder through addons.mozilla.org. + +## Set up + +1. In Docwell, open *Account settings → API tokens* and create a token with *Read and write* access. +2. Open the clipper's options (right-click its button → *Options*), enter the address you open Docwell at and the token, and choose *Connect*. The browser asks once to let the clipper reach that server. +3. Pick the workspace and the space new clips go to, and save. + +The clipper finds the API through the web app's `/config.json`, so it works when docwell-web and docwell-server have different addresses. + +## Use + +Click the Docwell button in the toolbar. Check the title and the space, then *Clip article* (or *Clip selection* when text is selected), or *Whole page* to keep everything on the page. When it is saved, *Open in Docwell* opens the new page. diff --git a/Web-Clipper/package.json b/Web-Clipper/package.json new file mode 100644 index 0000000..4ab3e69 --- /dev/null +++ b/Web-Clipper/package.json @@ -0,0 +1,26 @@ +{ + "name": "@docwell/web-clipper", + "version": "0.1.0", + "private": true, + "license": "AGPL-3.0-or-later", + "type": "module", + "description": "Browser extension that saves web pages to Docwell as new pages", + "scripts": { + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@mozilla/readability": "0.6.0", + "turndown": "7.2.4", + "turndown-plugin-gfm": "1.0.2" + }, + "devDependencies": { + "@types/chrome": "0.3.7", + "@types/turndown": "5.0.6", + "jsdom": "^30.1.3", + "typescript": "~5.9.3", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } +} diff --git a/Web-Clipper/public/icons/icon-128.png b/Web-Clipper/public/icons/icon-128.png new file mode 100644 index 0000000..5dcbfd7 Binary files /dev/null and b/Web-Clipper/public/icons/icon-128.png differ diff --git a/Web-Clipper/public/icons/icon-16.png b/Web-Clipper/public/icons/icon-16.png new file mode 100644 index 0000000..081cae3 Binary files /dev/null and b/Web-Clipper/public/icons/icon-16.png differ diff --git a/Web-Clipper/public/icons/icon-32.png b/Web-Clipper/public/icons/icon-32.png new file mode 100644 index 0000000..7f5d3f8 Binary files /dev/null and b/Web-Clipper/public/icons/icon-32.png differ diff --git a/Web-Clipper/public/icons/icon-48.png b/Web-Clipper/public/icons/icon-48.png new file mode 100644 index 0000000..cf4d6fe Binary files /dev/null and b/Web-Clipper/public/icons/icon-48.png differ diff --git a/Web-Clipper/public/manifest.json b/Web-Clipper/public/manifest.json new file mode 100644 index 0000000..e2f568a --- /dev/null +++ b/Web-Clipper/public/manifest.json @@ -0,0 +1,23 @@ +{ + "manifest_version": 3, + "name": "Docwell Web Clipper", + "version": "0.1.0", + "description": "Save web pages, articles and selections to your Docwell server as new pages.", + "action": { + "default_title": "Clip to Docwell", + "default_popup": "popup.html", + "default_icon": { "16": "icons/icon-16.png", "32": "icons/icon-32.png", "48": "icons/icon-48.png" } + }, + "options_ui": { "page": "options.html", "open_in_tab": true }, + "icons": { + "16": "icons/icon-16.png", + "32": "icons/icon-32.png", + "48": "icons/icon-48.png", + "128": "icons/icon-128.png" + }, + "permissions": ["activeTab", "scripting", "storage"], + "optional_host_permissions": ["https://*/*", "http://*/*"], + "browser_specific_settings": { + "gecko": { "id": "web-clipper@docwell.app", "strict_min_version": "128.0" } + } +} diff --git a/Web-Clipper/src/api.ts b/Web-Clipper/src/api.ts new file mode 100644 index 0000000..6584603 --- /dev/null +++ b/Web-Clipper/src/api.ts @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The few Docwell API calls the clipper makes, with a personal API token +// (Account settings → API tokens, "Read and write"). + +export interface Settings { + /** The Docwell web app's address, as people open it. */ + webUrl: string; + /** The API's address, read from the web app's /config.json. */ + apiUrl: string; + token: string; + workspace: string; + space: string; +} + +export const emptySettings: Settings = { webUrl: "", apiUrl: "", token: "", workspace: "", space: "" }; + +export async function loadSettings(): Promise { + const stored = (await chrome.storage.local.get("settings")) as { settings?: Partial }; + return { ...emptySettings, ...stored.settings }; +} + +export async function saveSettings(s: Settings): Promise { + await chrome.storage.local.set({ settings: s }); +} + +export class ClipError extends Error {} + +/** The address without a trailing slash; https:// is added when missing. */ +export function cleanUrl(raw: string): string { + let v = raw.trim(); + if (v && !/^https?:\/\//i.test(v)) v = `https://${v}`; + const u = new URL(v); + return `${u.origin}${u.pathname.replace(/\/+$/, "")}`; +} + +/** + * Finds the API next to a web app: docwell-web tells it in /config.json + * (empty when it serves the API on its own address). + */ +export async function findApi(webUrl: string): Promise { + try { + const res = await fetch(`${webUrl}/config.json`, { headers: { Accept: "application/json" } }); + if (res.ok) { + const cfg = (await res.json()) as { apiUrl?: string }; + if (cfg.apiUrl) return cleanUrl(new URL(cfg.apiUrl, webUrl).href); + } + } catch { + // Not a docwell-web (or a desktop or server address): use it as is. + } + return webUrl; +} + +async function call(s: Pick, path: string, init: RequestInit = {}): Promise { + let res: Response; + try { + res = await fetch(`${s.apiUrl}${path}`, { + ...init, + headers: { Accept: "application/json", Authorization: `Bearer ${s.token}`, ...init.headers }, + }); + } catch { + throw new ClipError("Docwell could not be reached. Check the address in the options."); + } + const data = res.headers.get("content-type")?.includes("json") ? await res.json() : null; + if (!res.ok) { + const msg = (data as { message?: string; fields?: Record } | null) ?? {}; + const detail = msg.fields ? Object.values(msg.fields)[0] : msg.message; + if (res.status === 401) throw new ClipError("The API token was refused. Create a new one in Docwell."); + throw new ClipError(detail || `Docwell answered ${res.status}.`); + } + return data as T; +} + +export interface Me { + id: string; + name: string; + email: string; +} +export interface Workspace { + id: string; + name: string; +} +export interface Space { + id: string; + name: string; + role: string; + journal: boolean; +} +export interface Page { + id: string; + title: string; +} + +export const me = (s: Settings) => call(s, "/api/v1/auth/me"); +export const workspaces = (s: Settings) => call(s, "/api/v1/workspaces"); +export const spaces = (s: Settings, ws: string) => + call(s, `/api/v1/workspaces/${encodeURIComponent(ws)}/spaces`).then((list) => + list.filter((sp) => sp.role === "editor" || sp.role === "admin"), + ); + +/** Creates a page from a Markdown file; returns it. */ +export async function importMarkdown(s: Settings, filename: string, markdown: string): Promise { + const form = new FormData(); + form.append("file", new File([markdown], filename, { type: "text/markdown" })); + const pages = await call(s, `/api/v1/spaces/${encodeURIComponent(s.space)}/import`, { + method: "POST", + body: form, + }); + const page = pages[0]; + if (!page) throw new ClipError("Docwell made no page from the clip."); + return page; +} + +/** Where the new page opens in the web app. */ +export const pageLink = (s: Settings, id: string) => `${s.webUrl}/p/${encodeURIComponent(id)}`; diff --git a/Web-Clipper/src/env.d.ts b/Web-Clipper/src/env.d.ts new file mode 100644 index 0000000..57059ba --- /dev/null +++ b/Web-Clipper/src/env.d.ts @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +declare module "turndown-plugin-gfm" { + import type TurndownService from "turndown"; + export const gfm: TurndownService.Plugin; +} diff --git a/Web-Clipper/src/extract.test.ts b/Web-Clipper/src/extract.test.ts new file mode 100644 index 0000000..50a637f --- /dev/null +++ b/Web-Clipper/src/extract.test.ts @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { describe, expect, it } from "vitest"; +import { clipFilename, toClip } from "./extract"; + +const article = `How wells work | Water Weekly + +
+

How wells work

+

Groundwater fills the gaps between rocks. This paragraph is long enough for Readability to keep it as the article's + body, with a link to aquifers and bold words.

+

A second paragraph keeps going, so the page reads like an article rather than a menu. It mentions pumps, pipes, + and the water table, and how deep a well has to be to reach it in a dry summer.

+ A well +
print("hello")
+
DepthYield
10 mlow
+ +
+
© Water Weekly
+`; + +describe("toClip", () => { + const page = { + html: article, + url: "https://news.example.com/2026/wells", + title: "How wells work | Water Weekly", + selection: "", + }; + + it("keeps the article with absolute links and images", () => { + const c = toClip(page, "2026-11-16"); + expect(c.title).toBe("How wells work"); + expect( + c.markdown.startsWith( + "# How wells work\n\n> [!NOTE]\n> Clipped from [news.example.com](https://news.example.com/2026/wells) on 2026-11-16", + ), + ).toBe(true); + expect(c.markdown).toContain("[a link to aquifers](https://news.example.com/aquifers)"); + expect(c.markdown).toContain("**bold words**"); + expect(c.markdown).toContain("![A well](https://news.example.com/img/well.jpg)"); + expect(c.markdown).toContain('```python\nprint("hello")\n```'); + expect(c.markdown).toMatch(/\| Depth \| Yield \|/); + expect(c.markdown).not.toContain("alert(1)"); + expect(c.markdown).not.toContain("About"); + // The heading that repeats the title is not kept twice. + expect(c.markdown.match(/How wells work/g)?.length).toBe(1); + }); + + it("clips only the selection when there is one", () => { + const c = toClip({ ...page, selection: '

Just this part.

' }, "2026-11-16"); + expect(c.markdown).toContain("Just [this](https://news.example.com/x) part."); + expect(c.markdown).not.toContain("Groundwater"); + }); + + it("drops javascript: links", () => { + const c = toClip({ ...page, selection: '

bad ok

' }, "2026-11-16"); + expect(c.markdown).not.toContain("javascript:"); + expect(c.markdown).toContain("bad ok"); + }); +}); + +describe("clipFilename", () => { + it("makes a safe Markdown file name", () => { + expect(clipFilename('a/b: "c"?')).toBe("a b c.md"); + expect(clipFilename("")).toBe("Clip.md"); + }); +}); diff --git a/Web-Clipper/src/extract.ts b/Web-Clipper/src/extract.ts new file mode 100644 index 0000000..e1b434e --- /dev/null +++ b/Web-Clipper/src/extract.ts @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Turns a web page into the Markdown file Docwell imports: the article +// Readability finds (or the selection, when there is one) with links and +// images made absolute, under a title and a note saying where it came from. +// It runs in the extension's own page on HTML the tab sent, so nothing is +// injected into the site beyond reading it. + +import { Readability } from "@mozilla/readability"; +import TurndownService from "turndown"; +import { gfm } from "turndown-plugin-gfm"; + +/** What the tab sends: its HTML, address, title and the selected HTML. */ +export interface Grabbed { + html: string; + url: string; + title: string; + selection: string; +} + +export interface Clip { + title: string; + markdown: string; +} + +/** Runs in the tab (chrome.scripting): reads the page and the selection. */ +export function grab(): Grabbed { + let selection = ""; + const sel = window.getSelection(); + if (sel && sel.rangeCount > 0 && !sel.isCollapsed) { + const box = document.createElement("div"); + for (let i = 0; i < sel.rangeCount; i++) box.appendChild(sel.getRangeAt(i).cloneContents()); + selection = box.innerHTML; + } + return { html: document.documentElement.outerHTML, url: location.href, title: document.title, selection }; +} + +/** Parses html as a document whose relative links resolve against url. */ +function parse(html: string, url: string): Document { + const doc = new DOMParser().parseFromString(html, "text/html"); + let base = doc.querySelector("base"); + if (!base) { + base = doc.createElement("base"); + doc.head.prepend(base); + } + // A page's own may be relative to its address. + base.href = new URL(base.getAttribute("href") || url, url).href; + return doc; +} + +/** Makes every link and image under root absolute, and drops unsafe ones. */ +function absolutize(root: ParentNode, base: string) { + const fix = (v: string | null) => { + if (!v) return ""; + try { + const u = new URL(v, base); + return u.protocol === "http:" || u.protocol === "https:" || u.protocol === "mailto:" ? u.href : ""; + } catch { + return ""; + } + }; + for (const a of root.querySelectorAll("a[href]")) { + const href = fix(a.getAttribute("href")); + if (href) a.setAttribute("href", href); + else a.removeAttribute("href"); + } + for (const img of root.querySelectorAll("img")) { + // Lazy-loading sites keep the real picture in data-src or srcset. + const src = + fix(img.getAttribute("data-src")) || + fix(img.getAttribute("src")) || + fix(img.getAttribute("srcset")?.split(",").pop()?.trim().split(/\s+/)[0] ?? null); + if (src && !src.startsWith("mailto:")) img.setAttribute("src", src); + else img.remove(); + } +} + +function turndown(): TurndownService { + const td = new TurndownService({ + headingStyle: "atx", + codeBlockStyle: "fenced", + bulletListMarker: "-", + emDelimiter: "*", + hr: "---", + }); + td.use(gfm); + td.remove(["script", "style", "noscript", "iframe", "form", "button", "select", "input", "textarea"]); + // Keep the language of highlighted code blocks. + td.addRule("fencedLanguage", { + filter: (node) => node.nodeName === "PRE" && !!node.querySelector("code"), + replacement: (_content, node) => { + const code = (node as HTMLElement).querySelector("code")!; + const lang = /(?:language|lang)-([\w+#.-]+)/.exec(code.className)?.[1] ?? ""; + const text = code.textContent ?? ""; + const fence = text.includes("```") ? "~~~" : "```"; + return `\n\n${fence}${lang}\n${text.replace(/\n$/, "")}\n${fence}\n\n`; + }, + }); + return td; +} + +const mdEscape = (s: string) => s.replace(/([\\[\]()*_`#<>])/g, "\\$1"); + +/** + * The clip of a grabbed page: the selection when there is one, else the + * main article, else the whole body. today is the clip's date (YYYY-MM-DD). + */ +export function toClip(g: Grabbed, today: string, opts: { whole?: boolean } = {}): Clip { + const doc = parse(g.html, g.url); + const base = doc.baseURI || g.url; + let title = g.title.trim(); + let body: Element; + if (g.selection.trim() && !opts.whole) { + body = parse(`${g.selection}`, base).body; + } else { + const article = new Readability(doc.cloneNode(true) as Document, { keepClasses: true }).parse(); + if (article?.content) { + body = parse(`${article.content}`, base).body; + title = article.title?.trim() || title; + } else { + body = doc.body; + } + } + absolutize(body, base); + // The article's own heading beats a tab title with the site's name after + // it ("How wells work | Water Weekly"); a heading repeating the title goes. + const first = body.querySelector("h1") ?? doc.querySelector("h1"); + const heading = first?.textContent?.replace(/\s+/g, " ").trim() ?? ""; + if (heading && title !== heading && title.startsWith(heading)) title = heading; + if (first && body.contains(first) && heading === title) first.remove(); + if (!title) title = new URL(g.url).hostname; + + const content = turndown().turndown(body.innerHTML).trim(); + const site = new URL(g.url).hostname.replace(/^www\./, ""); + const source = `> [!NOTE]\n> Clipped from [${mdEscape(site)}](${g.url}) on ${today}`; + return { title, markdown: `# ${title.replace(/\n/g, " ")}\n\n${source}\n\n${content}\n` }; +} + +/** A file name for the clip (the server takes the title from its heading). */ +export function clipFilename(title: string): string { + const name = [...title] + .map((ch) => (ch.charCodeAt(0) < 32 ? " " : ch)) + .join("") + .replace(/[\\/:*?"<>|]+/g, " ") + .replace(/\s+/g, " ") + .trim() + .slice(0, 80); + return `${name || "Clip"}.md`; +} diff --git a/Web-Clipper/src/options.html b/Web-Clipper/src/options.html new file mode 100644 index 0000000..0515791 --- /dev/null +++ b/Web-Clipper/src/options.html @@ -0,0 +1,43 @@ + + + + + + Docwell Web Clipper options + + + +

Docwell Web Clipper

+
+ + +
+

+ +
+

+ The clipper reads a page only when you click it, turns the article into Markdown in this extension, and sends it + to your Docwell server. It talks to no other server. +

+ + + diff --git a/Web-Clipper/src/options.ts b/Web-Clipper/src/options.ts new file mode 100644 index 0000000..b748fba --- /dev/null +++ b/Web-Clipper/src/options.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { ClipError, cleanUrl, findApi, loadSettings, me, saveSettings, spaces, workspaces, type Settings } from "./api"; + +const $ = (id: string) => document.getElementById(id) as T; +const form = $("form"); +const webUrl = $("web-url"); +const token = $("token"); +const status = $("status"); +const pick = $("pick"); +const wsSelect = $("workspace"); +const spaceSelect = $("space"); + +let settings: Settings; + +function say(text: string, kind: "" | "error" | "ok" = "") { + status.textContent = text; + status.className = `status ${kind}`; +} + +function fill(select: HTMLSelectElement, items: { id: string; name: string }[], selected: string) { + select.replaceChildren( + ...items.map((i) => { + const o = document.createElement("option"); + o.value = i.id; + o.textContent = i.name; + o.selected = i.id === selected; + return o; + }), + ); +} + +async function loadSpaces() { + const list = (await spaces(settings, wsSelect.value)).filter((s) => !s.journal); + fill(spaceSelect, list, settings.space); + if (!list.length) say("You cannot add pages to any space of this workspace.", "error"); +} + +async function connect() { + say("Connecting…"); + const web = cleanUrl(webUrl.value); + const api = await findApi(web); + // The browser asks once to let the clipper reach this server. + const origins = [...new Set([new URL(web).origin, new URL(api).origin])].map((o) => `${o}/*`); + const granted = await chrome.permissions.request({ origins }); + if (!granted) throw new ClipError("The clipper needs permission to reach your Docwell server."); + settings = { ...settings, webUrl: web, apiUrl: api, token: token.value.trim() }; + const who = await me(settings); + const list = await workspaces(settings); + if (!list.length) throw new ClipError("Your account has no workspaces yet."); + fill(wsSelect, list, settings.workspace || list[0]!.id); + await loadSpaces(); + pick.hidden = false; + say(`Connected as ${who.name || who.email}.`, "ok"); +} + +form.addEventListener("submit", (e) => { + e.preventDefault(); + connect().catch((err: unknown) => say(err instanceof Error ? err.message : String(err), "error")); +}); +wsSelect.addEventListener("change", () => { + loadSpaces().catch((err: unknown) => say(err instanceof Error ? err.message : String(err), "error")); +}); +$("save").addEventListener("click", async () => { + if (!spaceSelect.value) return say("Pick a space.", "error"); + settings = { ...settings, workspace: wsSelect.value, space: spaceSelect.value }; + await saveSettings(settings); + say("Saved. Click the Docwell button in the toolbar on any page to clip it.", "ok"); +}); + +void (async () => { + settings = await loadSettings(); + webUrl.value = settings.webUrl; + token.value = settings.token; + if (settings.webUrl && settings.token) { + connect().catch((err: unknown) => say(err instanceof Error ? err.message : String(err), "error")); + } +})(); diff --git a/Web-Clipper/src/popup.html b/Web-Clipper/src/popup.html new file mode 100644 index 0000000..0e6502e --- /dev/null +++ b/Web-Clipper/src/popup.html @@ -0,0 +1,36 @@ + + + + + + Clip to Docwell + + + +

Clip to Docwell

+ + +

+

Options

+ + + diff --git a/Web-Clipper/src/popup.ts b/Web-Clipper/src/popup.ts new file mode 100644 index 0000000..9bf07c1 --- /dev/null +++ b/Web-Clipper/src/popup.ts @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { ClipError, importMarkdown, loadSettings, pageLink, saveSettings, spaces, type Settings } from "./api"; +import { clipFilename, grab, toClip, type Grabbed } from "./extract"; + +const $ = (id: string) => document.getElementById(id) as T; +const status = $("status"); +const titleInput = $("title"); +const spaceSelect = $("space"); +const clipButton = $("clip"); +const wholeButton = $("clip-whole"); + +function say(text: string, kind: "" | "error" | "ok" = "") { + status.textContent = text; + status.className = `status ${kind}`; +} +const fail = (err: unknown) => say(err instanceof Error ? err.message : String(err), "error"); + +const openOptions = (e?: Event) => { + e?.preventDefault(); + void chrome.runtime.openOptionsPage(); +}; +$("open-options").addEventListener("click", openOptions); +$("options-link").addEventListener("click", openOptions); + +function today(): string { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +} + +let settings: Settings; +let page: Grabbed | null = null; + +async function readTab(): Promise { + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab?.id || !/^https?:/.test(tab.url ?? "")) throw new ClipError("Only web pages can be clipped."); + const [res] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: grab }); + if (!res?.result) throw new ClipError("The page could not be read."); + return res.result as Grabbed; +} + +async function clip(whole: boolean) { + if (!page) return; + clipButton.disabled = wholeButton.disabled = true; + say("Clipping…"); + try { + const c = toClip(page, today(), { whole }); + const title = titleInput.value.trim() || c.title; + const markdown = c.markdown.replace(/^# .*\n/, `# ${title.replace(/\n/g, " ")}\n`); + settings = { ...settings, space: spaceSelect.value }; + await saveSettings(settings); + const created = await importMarkdown(settings, clipFilename(title), markdown); + const link = pageLink(settings, created.id); + status.className = "status ok"; + status.replaceChildren("Saved. "); + const a = document.createElement("a"); + a.href = link; + a.textContent = "Open in Docwell"; + a.addEventListener("click", (e) => { + e.preventDefault(); + void chrome.tabs.create({ url: link }); + }); + status.append(a); + } catch (err) { + fail(err); + clipButton.disabled = wholeButton.disabled = false; + } +} +clipButton.addEventListener("click", () => void clip(false)); +wholeButton.addEventListener("click", () => void clip(true)); + +void (async () => { + settings = await loadSettings(); + if (!settings.apiUrl || !settings.token || !settings.workspace) { + $("setup").hidden = false; + return; + } + $("clipper").hidden = false; + try { + const [list, grabbed] = await Promise.all([spaces(settings, settings.workspace), readTab()]); + page = grabbed; + for (const sp of list.filter((s) => !s.journal)) { + const o = document.createElement("option"); + o.value = sp.id; + o.textContent = sp.name; + o.selected = sp.id === settings.space; + spaceSelect.append(o); + } + $("page-title").textContent = grabbed.title || grabbed.url; + $("page-url").textContent = new URL(grabbed.url).hostname; + titleInput.value = grabbed.title; + if (grabbed.selection.trim()) { + $("selection-note").hidden = false; + clipButton.textContent = "Clip selection"; + } + } catch (err) { + clipButton.disabled = wholeButton.disabled = true; + fail(err); + } +})(); diff --git a/Web-Clipper/src/style.css b/Web-Clipper/src/style.css new file mode 100644 index 0000000..d92c9c7 --- /dev/null +++ b/Web-Clipper/src/style.css @@ -0,0 +1,132 @@ +/* SPDX-License-Identifier: AGPL-3.0-or-later */ +/* Docwell's colours (see Packages/ui/src/theme.css), light and dark. */ +:root { + --surface: #fbfaf7; + --raised: #ffffff; + --line: #dfe3df; + --ink: #17201e; + --muted: #5b6a66; + --primary: #12403c; + --on-primary: #ffffff; + --danger: #b3261e; + --success: #2f6b2f; + color-scheme: light; + font: + 14px/1.45 "Inter", + system-ui, + -apple-system, + "Segoe UI", + sans-serif; +} +@media (prefers-color-scheme: dark) { + :root { + --surface: #0f1716; + --raised: #18221f; + --line: #2a3735; + --ink: #e8efed; + --muted: #a3b3ae; + --primary: #5fc4b3; + --on-primary: #0b1211; + --danger: #ff8a80; + --success: #8fd18f; + color-scheme: dark; + } +} +body { + margin: 0; + background: var(--surface); + color: var(--ink); +} +.popup { + width: 340px; + padding: 14px; +} +.options { + max-width: 560px; + margin: 32px auto; + padding: 0 16px; +} +h1 { + font-size: 16px; + margin: 0 0 10px; + display: flex; + align-items: center; + gap: 8px; +} +h1 img { + width: 20px; + height: 20px; +} +label { + display: flex; + flex-direction: column; + gap: 4px; + margin: 10px 0; + font-weight: 600; + font-size: 13px; +} +input, +select { + font: inherit; + font-weight: 400; + padding: 6px 8px; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--raised); + color: var(--ink); +} +.hint { + color: var(--muted); + font-size: 12px; + font-weight: 400; + margin: 2px 0 0; +} +.row { + display: flex; + gap: 8px; + margin-top: 12px; +} +button { + font: inherit; + font-weight: 600; + padding: 7px 12px; + border-radius: 6px; + border: 1px solid var(--line); + background: var(--raised); + color: var(--ink); + cursor: pointer; +} +button.primary { + background: var(--primary); + border-color: var(--primary); + color: var(--on-primary); + flex: 1; +} +button:disabled { + opacity: 0.55; + cursor: default; +} +.status { + margin: 10px 0 0; + font-size: 13px; + min-height: 1em; +} +.status.error { + color: var(--danger); +} +.status.ok { + color: var(--success); +} +.title { + font-weight: 600; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.muted { + color: var(--muted); + font-size: 12px; +} +a { + color: var(--primary); +} diff --git a/Web-Clipper/tsconfig.json b/Web-Clipper/tsconfig.json new file mode 100644 index 0000000..480328e --- /dev/null +++ b/Web-Clipper/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "types": ["chrome", "vite/client"] + }, + "include": ["src/**/*.ts"] +} diff --git a/Web-Clipper/vite.config.ts b/Web-Clipper/vite.config.ts new file mode 100644 index 0000000..9cbcd6f --- /dev/null +++ b/Web-Clipper/vite.config.ts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { resolve } from "node:path"; +import { defineConfig } from "vitest/config"; + +// The extension's pages (popup and options) as ES modules; public/ holds the +// manifest and icons, copied as they are. Load dist/ as an unpacked extension. +export default defineConfig({ + root: "src", + publicDir: "../public", + base: "./", + build: { + outDir: "../dist", + emptyOutDir: true, + target: "es2022", + // Extension stores review the code: keep it readable. + minify: false, + rollupOptions: { + input: { + popup: resolve(import.meta.dirname, "src/popup.html"), + options: resolve(import.meta.dirname, "src/options.html"), + }, + }, + }, + test: { + root: ".", + environment: "jsdom", + }, +}); diff --git a/api/openapi.yaml b/api/openapi.yaml index 1af566d..865a8c1 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -626,6 +626,61 @@ paths: schema: { $ref: "#/components/schemas/Workspace" } "400": { $ref: "#/components/responses/Error" } "403": { $ref: "#/components/responses/Error" } + /api/v1/workspaces/{id}/snapshot: + parameters: + - { name: id, in: path, required: true, schema: { type: string } } + get: + operationId: exportWorkspaceSnapshot + tags: [workspaces] + summary: Download a snapshot of the workspace that restores 1:1 (workspace admin or above) + description: >- + One zip: snapshot.json (the workspace's settings, spaces, pages and their place in the + tree, tags, properties, shared collections, comments and the attachments' details), + pages/.ydoc (each page's Yjs state), pages/.json (the same document as JSON) + and files/ (each attachment). It holds what the caller can open: other people's + journals and pages hidden from the caller are left out, as are trashed pages. Members, + page sharing, share links, webhooks, AI settings and page history are not included. + security: [{ bearer: [] }] + responses: + "200": + description: The zip, streamed as it is built + content: + application/zip: + schema: { type: string, format: binary } + "403": { $ref: "#/components/responses/Error" } + "404": { $ref: "#/components/responses/Error" } + /api/v1/workspaces/restore: + post: + operationId: restoreWorkspaceSnapshot + tags: [workspaces] + summary: Make a new workspace from a snapshot (organization admin or superadmin) + description: >- + Every record gets a new id and old ids are replaced wherever they appear (links, + mentions, embedded pages, database relations, property values, collection rules), so + a snapshot can be restored next to its original. Pages come back from their Yjs state, + so comments stay anchored to their text. People named in the snapshot keep their + comments and collections when they exist on this server; everything else is the + caller's. On any error nothing is left behind. Up to 4 GB. + security: [{ bearer: [] }] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [file] + properties: + file: { type: string, format: binary } + name: { type: string, description: The new workspace's name; empty keeps the snapshot's } + organization: { type: string, description: Organization id (required for superadmins) } + responses: + "201": + description: The new workspace + content: + application/json: + schema: { $ref: "#/components/schemas/Workspace" } + "400": { $ref: "#/components/responses/Error" } + "403": { $ref: "#/components/responses/Error" } /api/v1/workspaces/{id}: parameters: - { name: id, in: path, required: true, schema: { type: string } } @@ -1835,15 +1890,23 @@ paths: post: operationId: importPages tags: [pages] - summary: Create pages from Markdown, HTML, Word files or a Notion export (editor) + summary: Create pages from Markdown, HTML, Word, CSV, OneNote, Notion, Obsidian or Bear files (editor) description: >- One page per Markdown, HTML or Word file (.md, .markdown, .txt, .html, .htm up to 5 MB; .docx up to 25 MB). A leading level-1 heading (a Word title) becomes the title, - otherwise the file name. A .zip (up to 100 MB) is read as a Notion export, Markdown & - CSV or HTML: its page tree, links between its pages, images and files are kept, and - each database becomes a page listing its rows with the row pages under it. At most 20 - files and 2000 pages at once. Content is reduced to what the editor supports; scripts - and styles are dropped. The response lists the pages created at the parent's level. + otherwise the file name. A .csv (up to 5 MB) becomes a page with a database, or, when + it is a Readwise export, a "Readwise" page with a page of highlights per book. A .mht or + .mhtml web archive (up to 100 MB; OneNote's "Single File Web Page" export) becomes a page + per page it holds, with its images. A .zip (up to 100 MB) is read as a Notion export + (Markdown & CSV or HTML; each database becomes a page listing its rows with the row pages + under it) or as a folder of Markdown notes: an Obsidian vault, Bear TextBundles, or any + Markdown with its images, Docwell's own space export included. Folders become pages + (a note named like its folder is that page), [[wikilinks]] and ![[embeds]] are found by + name, YAML front matter becomes properties (made when missing) and tags, and #tags are + added to the page's tags. A Bear backup (.bear2bk) is read the same way. Page trees, + links between pages, images and files are kept. At most 20 files and 2000 pages at once. + Content is reduced to what the editor supports; scripts and styles are dropped. The + response lists the pages created at the parent's level. security: [{ bearer: [] }] requestBody: required: true @@ -2556,6 +2619,107 @@ paths: schema: { $ref: "#/components/schemas/Collection" } "403": { $ref: "#/components/responses/Error" } "404": { $ref: "#/components/responses/Error" } + /api/v1/calendars: + get: + operationId: listCalendars + tags: [calendars] + summary: The caller's calendar subscriptions (passwords are never returned) + security: [{ bearer: [] }] + responses: + "200": + description: OK + content: + application/json: + schema: { type: array, items: { $ref: "#/components/schemas/CalendarAccount" } } + "404": { $ref: "#/components/responses/Error" } + post: + operationId: createCalendar + tags: [calendars] + summary: Subscribe to an iCalendar feed or a CalDAV account (read once first, to check it) + description: >- + kind "ics" reads an .ics or webcal:// address (Google Calendar's secret address in iCal + format, Outlook's published calendar, any feed), with an optional user name and password. + kind "caldav" reads a CalDAV calendar, or every event calendar of the account when the + address is the server or the account's home (Nextcloud, iCloud with an app password, + Fastmail…). Addresses follow the webhook rules: loopback and link-local addresses are + refused unless DOCWELL_WEBHOOKS_ALLOW_LOCAL is on. At most 20 calendars per person. + security: [{ bearer: [] }] + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/CalendarAccountInput" } + responses: + "201": + description: Created + content: + application/json: + schema: { $ref: "#/components/schemas/CalendarAccount" } + "400": { $ref: "#/components/responses/Error" } + /api/v1/calendars/{id}: + parameters: + - { name: id, in: path, required: true, schema: { type: string } } + patch: + operationId: updateCalendar + tags: [calendars] + summary: Rename, recolour, turn off or change the address or sign-in of a calendar + security: [{ bearer: [] }] + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/CalendarAccountInput" } + responses: + "200": + description: OK + content: + application/json: + schema: { $ref: "#/components/schemas/CalendarAccount" } + "400": { $ref: "#/components/responses/Error" } + "404": { $ref: "#/components/responses/Error" } + delete: + operationId: deleteCalendar + tags: [calendars] + summary: Remove a calendar subscription + security: [{ bearer: [] }] + responses: + "204": { description: Deleted } + "404": { $ref: "#/components/responses/Error" } + /api/v1/calendars/{id}/refresh: + parameters: + - { name: id, in: path, required: true, schema: { type: string } } + post: + operationId: refreshCalendar + tags: [calendars] + summary: Read a calendar from its source now (events are otherwise kept for 15 minutes) + security: [{ bearer: [] }] + responses: + "200": + description: The calendar with its new sync time or error + content: + application/json: + schema: { $ref: "#/components/schemas/CalendarAccount" } + "404": { $ref: "#/components/responses/Error" } + /api/v1/calendar/events: + get: + operationId: listCalendarEvents + tags: [calendars] + summary: The caller's events between two days, from their enabled calendars + description: >- + Repeating events are expanded, changed and cancelled occurrences applied. All-day events + come first. A calendar that cannot be read is left out (its lastError says why). + security: [{ bearer: [] }] + parameters: + - { name: from, in: query, required: true, schema: { type: string, format: date } } + - { name: to, in: query, required: true, description: Inclusive; at most 92 days after from, schema: { type: string, format: date } } + - { name: tz, in: query, description: "IANA time zone the days are in (default UTC)", schema: { type: string } } + responses: + "200": + description: OK + content: + application/json: + schema: { type: array, items: { $ref: "#/components/schemas/CalendarEvent" } } + "400": { $ref: "#/components/responses/Error" } /api/v1/workspaces/{id}/journals: parameters: - { name: id, in: path, required: true, schema: { type: string } } @@ -4420,6 +4584,46 @@ components: What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids. + CalendarAccount: + type: object + required: [id, name, kind, url, username, hasPassword, color, enabled, lastSync, lastError, events, created] + properties: + id: { type: string } + name: { type: string } + kind: { type: string, enum: [ics, caldav] } + url: { type: string } + username: { type: string } + hasPassword: { type: boolean } + color: { $ref: "#/components/schemas/LabelColor" } + enabled: { type: boolean, description: Whether its events show on journal pages } + lastSync: { type: string, description: When the source was last read } + lastError: { type: string, description: Why the last read failed; empty when it worked } + events: { type: integer, description: Events the source held then (repeating ones once) } + created: { type: string } + CalendarAccountInput: + type: object + properties: + name: { type: string, maxLength: 80 } + kind: { type: string, enum: [ics, caldav] } + url: { type: string, maxLength: 2000, description: "http, https or webcal address" } + username: { type: string, maxLength: 200 } + password: { type: string, maxLength: 1000, description: Empty keeps the stored one } + clearPassword: { type: boolean } + color: { $ref: "#/components/schemas/LabelColor" } + enabled: { type: boolean } + CalendarEvent: + type: object + required: [id, calendar, title, location, url, start, end, allDay, color] + properties: + id: { type: string } + calendar: { type: string, description: The calendar account's id } + title: { type: string } + location: { type: string } + url: { type: string } + start: { type: string, description: "RFC 3339 time, or a date (YYYY-MM-DD) for all-day events" } + end: { type: string, description: "Exclusive; a date for all-day events" } + allDay: { type: boolean } + color: { $ref: "#/components/schemas/LabelColor" } LabelColor: type: string enum: ["", gray, red, orange, yellow, green, teal, blue, purple, pink] diff --git a/package-lock.json b/package-lock.json index 80cdb74..533df7e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,8 @@ "Server/admin", "Web-App/frontend", "Desktop-App/frontend", - "Docs-Site" + "Docs-Site", + "Web-Clipper" ], "devDependencies": { "@eslint/js": "^10.0.1", @@ -735,6 +736,10 @@ "resolved": "Web-App/frontend", "link": true }, + "node_modules/@docwell/web-clipper": { + "resolved": "Web-Clipper", + "link": true + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.10.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", @@ -1461,6 +1466,21 @@ "langium": "3.3.1" } }, + "node_modules/@mixmark-io/domino": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", + "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==", + "license": "BSD-2-Clause" + }, + "node_modules/@mozilla/readability": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz", + "integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@napi-rs/canvas": { "version": "0.1.100", "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.100.tgz", @@ -4230,6 +4250,16 @@ "assertion-error": "^2.0.1" } }, + "node_modules/@types/chrome": { + "version": "0.3.7", + "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.3.7.tgz", + "integrity": "sha512-jWZgbHqWbTL1a5+PoyN0OJutNyejWgyZ5MdcvKo6iJE1TNRtXR3FxsC4WzNl52yZWPidfWC8NV/VUNZf+OFKcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/har-format": "*" + } + }, "node_modules/@types/d3": { "version": "7.4.3", "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", @@ -4509,6 +4539,13 @@ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", "license": "MIT" }, + "node_modules/@types/har-format": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@types/har-format/-/har-format-1.2.16.tgz", + "integrity": "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/hast": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", @@ -4575,6 +4612,13 @@ "license": "MIT", "optional": true }, + "node_modules/@types/turndown": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.6.tgz", + "integrity": "sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/unist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", @@ -7116,6 +7160,12 @@ "node": "^22.13.0 || >=24.0.0" } }, + "node_modules/html-to-image": { + "version": "1.11.13", + "resolved": "https://registry.npmjs.org/html-to-image/-/html-to-image-1.11.13.tgz", + "integrity": "sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==", + "license": "MIT" + }, "node_modules/html-void-elements": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", @@ -9660,6 +9710,25 @@ "zustand": "^4.3.2" } }, + "node_modules/turndown": { + "version": "7.2.4", + "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.4.tgz", + "integrity": "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==", + "license": "MIT", + "dependencies": { + "@mixmark-io/domino": "^2.2.0" + }, + "engines": { + "node": ">=18", + "npm": ">=9" + } + }, + "node_modules/turndown-plugin-gfm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/turndown-plugin-gfm/-/turndown-plugin-gfm-1.0.2.tgz", + "integrity": "sha512-vwz9tfvF7XN/jE0dGoBei3FXWuvll78ohzCZQuOb+ZjWrs3a0XhQVomJEb2Qh4VHTPNRO4GPZh0V7VRbiWwkRg==", + "license": "MIT" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -11667,6 +11736,7 @@ "@docwell/editor": "*", "@docwell/ui": "*", "dompurify": "^3.4.17", + "html-to-image": "^1.11.13", "marked": "^16.4.2", "pinia": "^4.1.0", "vue": "^3.5.44", @@ -11684,6 +11754,24 @@ "vitest": "^5.0.5", "vue-tsc": "^3.3.14" } + }, + "Web-Clipper": { + "name": "@docwell/web-clipper", + "version": "0.1.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@mozilla/readability": "0.6.0", + "turndown": "7.2.4", + "turndown-plugin-gfm": "1.0.2" + }, + "devDependencies": { + "@types/chrome": "0.3.7", + "@types/turndown": "5.0.6", + "jsdom": "^30.1.3", + "typescript": "~5.9.3", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } } } } diff --git a/package.json b/package.json index 8546e5b..27e9bd7 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "Server/admin", "Web-App/frontend", "Desktop-App/frontend", - "Docs-Site" + "Docs-Site", + "Web-Clipper" ], "scripts": { "build:packages": "npm run build -w @docwell/api-client", @@ -26,7 +27,8 @@ "format": "prettier --write .", "format:check": "prettier --check .", "dev:docs": "npm run dev -w @docwell/docs", - "build:docs": "npm run build -w @docwell/docs" + "build:docs": "npm run build -w @docwell/docs", + "build:clipper": "npm run build -w @docwell/web-clipper" }, "engines": { "node": ">=22"