diff --git a/CHANGELOG.md b/CHANGELOG.md index 260e520..a19d375 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,22 @@ What changed in each Docwell release. The release workflow copies a version's se manager sends goes out in the recipient's language. New-login alerts, which PocketBase sends without being asked, use the language of the last email it sent. +### Calendars + +- Events can now be added, changed and deleted from journal pages, on the web and in the phone app, for CalDAV + calendars and Google Calendar. The change goes to the calendar straight away. If the event was changed somewhere + else since Docwell last read it, Docwell overwrites nothing: it says so and shows the event as it is now. iCal feed + subscriptions and repeating events stay read-only. +- Account settings show which calendar new events go to, when an account has several. + +### Upgrading + +- **Google Calendar:** add the `https://www.googleapis.com/auth/calendar.events` scope to your Google OAuth consent + screen. It is a sensitive scope; an app used beyond its test users needs Google's verification. Google accounts + connected before this release stay read-only until their owner chooses **Connect again** in account settings. +- The first calendar sync after the upgrade rewrites every stored event once, to record where it lives in its + calendar. + ## 0.3.0 — 2026-11-17 The AFFiNE parity work ([docs/AFFINE.md](docs/AFFINE.md), phases A–G), the integrations, and the last v2 rows of diff --git a/Database/pb_migrations/1764800000_calendar_writes.js b/Database/pb_migrations/1764800000_calendar_writes.js new file mode 100644 index 0000000..50e49d7 --- /dev/null +++ b/Database/pb_migrations/1764800000_calendar_writes.js @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Writing to calendars (ADR-19): events of CalDAV and Google accounts can be +// added, changed and deleted from journal pages. +// +// - calendar_accounts.can_write: the account takes changes (CalDAV, or a +// Google account signed in with the events scope). +// - calendar_accounts.targets: the calendars of the account new events can go +// to, as [{id, name}] (CalDAV collection paths, Google calendar ids); +// write_to is the one chosen, empty for the first. +// - calendar_events.cal, ref, etag: where an occurrence's event is at the +// source (calendar, CalDAV object path or Google event id) and the ETag +// last read, sent as If-Match so a change made elsewhere is not +// overwritten. recurring marks occurrences of repeating events, which stay +// read-only. + +migrate( + (app) => { + const accounts = app.findCollectionByNameOrId("calendar_accounts"); + accounts.fields.add(new BoolField({ name: "can_write" })); + accounts.fields.add(new JSONField({ name: "targets", maxSize: 200000 })); + accounts.fields.add(new TextField({ name: "write_to", max: 2000 })); + app.save(accounts); + + const events = app.findCollectionByNameOrId("calendar_events"); + events.fields.add(new TextField({ name: "cal", max: 2000 })); + events.fields.add(new TextField({ name: "ref", max: 2000 })); + events.fields.add(new TextField({ name: "etag", max: 500 })); + events.fields.add(new BoolField({ name: "recurring" })); + events.indexes.push("CREATE INDEX idx_calendar_events_user_key ON calendar_events (user, key)"); + app.save(events); + }, + (app) => { + const accounts = app.findCollectionByNameOrId("calendar_accounts"); + for (const name of ["can_write", "targets", "write_to"]) { + accounts.fields.removeByName(name); + } + app.save(accounts); + const events = app.findCollectionByNameOrId("calendar_events"); + for (const name of ["cal", "ref", "etag", "recurring"]) { + events.fields.removeByName(name); + } + events.indexes = events.indexes.filter((i) => !i.includes("idx_calendar_events_user_key")); + app.save(events); + }, +); diff --git a/Docs-Site/guide/configuration.md b/Docs-Site/guide/configuration.md index 670bfb6..6c89fd7 100644 --- a/Docs-Site/guide/configuration.md +++ b/Docs-Site/guide/configuration.md @@ -34,7 +34,7 @@ Docwell's collections in it when it starts. Change the image with `DB_IMAGE`. | `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers, the passwords and Google sign-ins of people's calendars, and their Readwise tokens. 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_GOOGLE_CLIENT_ID`, `DOCWELL_GOOGLE_CLIENT_SECRET` | — | A Google OAuth app (web application) people sign in to for **Connect Google Calendar**. Enable the Google Calendar API in its project, add the scope `calendar.readonly`, and register `{DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback` as a redirect URI. Blank turns it off. | +| `DOCWELL_GOOGLE_CLIENT_ID`, `DOCWELL_GOOGLE_CLIENT_SECRET` | — | A Google OAuth app (web application) people sign in to for **Connect Google Calendar**. Enable the Google Calendar API in its project, add the scopes `calendar.readonly` and `calendar.events` (the second lets people add and change events from journal pages; it is a sensitive scope, so an app used beyond its test users needs Google's verification), and register `{DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback` as a redirect URI. Blank turns it off. | | `DOCWELL_MICROSOFT_CLIENT_ID`, `DOCWELL_MICROSOFT_CLIENT_SECRET` | — | A Microsoft Entra app registration (web platform, a client secret, delegated permissions `Notes.Read`, `User.Read`, `offline_access`) for importing OneNote notebooks. Register `{DOCWELL_PUBLIC_URL}/api/v1/oauth/microsoft/callback` as a redirect URI. Blank turns it off. | | `DOCWELL_MICROSOFT_TENANT` | `common` | Who may sign in to the Microsoft app: `common` (work, school and personal accounts), `organizations`, `consumers`, or your tenant id. | | `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. | diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index 63722a2..e83b3eb 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -210,10 +210,12 @@ page new journal pages start from in the Info panel, under **Journal**; any page 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, on the web and in the phone app (**Today's journal** on its home screen). Only you -see them, and Docwell only reads them. +see them. -- **Google Calendar:** **Connect Google Calendar** signs in to Google (read-only access to your calendars) and adds - every calendar shown in your Google Calendar list. Connecting the same account again renews its access. The button +- **Google Calendar:** **Connect Google Calendar** signs in to Google (reading your calendars and managing their + events) and adds every calendar shown in your Google Calendar list. Connecting the same account again renews its + access; an account connected read-only (before Docwell could write, or with the events box unticked) shows + **Connect again**. The button appears when your server has a Google app set up; without one, use the calendar's **Secret address in iCal format** (Settings → the calendar → Integrate calendar) as an iCal feed. - **iCal feed:** any `.ics` or `webcal://` address; for Outlook, publish the calendar and use its ICS link. @@ -226,6 +228,14 @@ each calendar's events (three months back, a year ahead) and reads the calendar with **Refresh**; journals show the copy, so they open at once and still show events while a calendar's server is down. The list says when a calendar was last read, or why it could not be. +**Adding and changing events.** For CalDAV and Google calendars, **Add event** on a journal page (the **+** in the phone +app) adds an event, timed or all-day, to the calendar you pick; an account with several calendars puts new events in the +one chosen under **New events go to** in account settings. Click an event to change its title, time or place, or to +delete it. The change goes to the calendar at once. If the event was changed somewhere else since Docwell last read +it, Docwell does not overwrite that: it says so and shows the event as it is now, so you can make your change again. +Events of iCal feeds, repeating events and calendars shared with you read-only can only be changed in their own +calendar app. + ## Sharing **Share** in the page header shows who can open the page through its space and copies the page's link. Editors can diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 76b9492..3d5d2d1 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -94,6 +94,8 @@ export type Tag = Schemas["Tag"]; export type CalendarAccount = Schemas["CalendarAccount"]; export type CalendarAccountInput = Schemas["CalendarAccountInput"]; export type CalendarEvent = Schemas["CalendarEvent"]; +export type CalendarEventInput = Schemas["CalendarEventInput"]; +export type CalendarTarget = Schemas["CalendarTarget"]; export type Integrations = Schemas["Integrations"]; export type OneNoteNotebook = Schemas["OneNoteNotebook"]; export type OneNoteConnection = Schemas["OneNoteConnection"]; @@ -692,6 +694,12 @@ export function createClient(opts: ClientOptions) { /** 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 })}`), + /** Adds an event to a calendar whose canWrite is true; written to the source at once. */ + createEvent: (input: CalendarEventInput) => post("/api/v1/calendar/events", input), + /** Changes an editable event. 409 when it changed in its calendar since the last sync. */ + updateEvent: (id: string, patch: CalendarEventInput) => + request("PATCH", `/api/v1/calendar/events/${encodeURIComponent(id)}`, patch), + removeEvent: (id: string) => request("DELETE", `/api/v1/calendar/events/${encodeURIComponent(id)}`), }, tags: { diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index 5882352..a8b90ff 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -2358,8 +2358,8 @@ export interface paths { cookie?: never; }; /** - * Where to send the browser to connect a Google account's calendars (read-only) - * @description Needs DOCWELL_GOOGLE_CLIENT_ID and DOCWELL_GOOGLE_CLIENT_SECRET. Afterwards the browser returns to account settings. + * Where to send the browser to connect a Google account's calendars + * @description Needs DOCWELL_GOOGLE_CLIENT_ID and DOCWELL_GOOGLE_CLIENT_SECRET. Asks to read calendars and to manage events; when the person leaves events unticked, the account stays read-only (canWrite false). Connecting the same Google account again replaces its sign-in. Afterwards the browser returns to account settings. */ get: operations["connectGoogleCalendar"]; put?: never; @@ -2562,13 +2562,43 @@ export interface paths { */ get: operations["listCalendarEvents"]; put?: never; - post?: never; + /** + * Add an event to one of the caller's calendars + * @description Written to the source at once (CalDAV PUT, Google Calendar API), into the account's writeTo calendar. Needs a calendar whose canWrite is true. Timed events are stored in UTC. + */ + post: operations["createCalendarEvent"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; + "/api/v1/calendar/events/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Delete an event (editable ones only) from its calendar + * @description Guarded by the event's ETag like a change; 409 when it changed in its calendar since. + */ + delete: operations["deleteCalendarEvent"]; + options?: never; + head?: never; + /** + * Change an event (editable ones only) at its source + * @description Sent with the ETag the last sync read. When the event changed in its calendar since, nothing is overwritten: the answer is 409, the calendar is read again and the journal shows it as it is now. Moving an event changes its id. Repeating events cannot be changed here. + */ + patch: operations["updateCalendarEvent"]; + trace?: never; + }; "/api/v1/workspaces/{id}/journals": { parameters: { query?: never; @@ -4559,6 +4589,32 @@ export interface components { /** @description Events the source held then (repeating ones once) */ events: number; created: string; + /** @description Events can be added to and changed in this calendar */ + canWrite: boolean; + /** @description A Google account connected read-only; connecting it again allows editing */ + needsReconnect: boolean; + /** @description The account's calendars new events can go to (filled by a sync) */ + targets: components["schemas"]["CalendarTarget"][]; + /** @description The target new events go to; empty when there is none */ + writeTo: string; + }; + CalendarTarget: { + /** @description A CalDAV collection path or a Google calendar id */ + id: string; + /** @description Empty when the account is a single CalDAV calendar */ + name: string; + }; + /** @description Creating needs calendar, title and start; changing sends only what changes. */ + CalendarEventInput: { + /** @description The calendar account's id (creating only) */ + calendar?: string; + title?: string; + location?: string; + /** @description RFC 3339 time, or a date (YYYY-MM-DD) when allDay */ + start?: string; + /** @description Exclusive, written like start; missing is an hour (or a day) after start, or the old length when moving */ + end?: string; + allDay?: boolean; }; CalendarAccountInput: { name?: string; @@ -4572,6 +4628,8 @@ export interface components { clearPassword?: boolean; color?: components["schemas"]["LabelColor"]; enabled?: boolean; + /** @description One of the account's targets (changing only); empty for the first */ + writeTo?: string; }; CalendarEvent: { id: string; @@ -4586,6 +4644,8 @@ export interface components { end: string; allDay: boolean; color: components["schemas"]["LabelColor"]; + /** @description Can be changed and deleted here: a single event in a calendar that takes changes */ + editable: boolean; }; /** * @description A colour of the editor palette, drawn from the theme; empty for none @@ -9455,6 +9515,84 @@ export interface operations { 400: components["responses"]["Error"]; }; }; + createCalendarEvent: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CalendarEventInput"]; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarEvent"]; + }; + }; + 400: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + deleteCalendarEvent: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 400: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + 409: components["responses"]["Error"]; + }; + }; + updateCalendarEvent: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CalendarEventInput"]; + }; + }; + responses: { + /** @description The event as it is now */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CalendarEvent"]; + }; + }; + 400: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + 409: components["responses"]["Error"]; + }; + }; getJournal: { parameters: { query: { diff --git a/Phone-App/lib/api/docwell_api.dart b/Phone-App/lib/api/docwell_api.dart index a044de4..e4005dd 100644 --- a/Phone-App/lib/api/docwell_api.dart +++ b/Phone-App/lib/api/docwell_api.dart @@ -150,6 +150,29 @@ class DocwellApi { ), ); + /// The caller's calendars (ADR-16); the ones with canWrite take new events. + Future> calendars() async => (await _getList( + '/api/v1/calendars', + )).map((e) => CalendarAccount.fromJson(e as Map)).toList(); + + /// Adds an event to a calendar, written to its source at once (ADR-19). + Future createCalendarEvent(CalendarEventInput input) async => + CalendarEvent.fromJson( + await _send('POST', '/api/v1/calendar/events', input.toJson()), + ); + + /// Changes an editable event; a 409 means it changed in its calendar since + /// the last sync, and nothing was overwritten. + Future updateCalendarEvent( + String id, + CalendarEventInput input, + ) async => CalendarEvent.fromJson( + await _send('PATCH', '/api/v1/calendar/events/${_id(id)}', input.toJson()), + ); + + Future deleteCalendarEvent(String id) => + _send('DELETE', '/api/v1/calendar/events/${_id(id)}'); + /// The caller's calendar events from day from to day to (inclusive, UTC). Future> calendarEvents(String from, String to) async => (await _getList( @@ -384,6 +407,9 @@ class DocwellApi { code: data['error'] as String? ?? 'unknown', challenge: data['challenge'] as String? ?? '', message: data['message'] as String? ?? '', + fields: (data['fields'] as Map? ?? const {}).map( + (k, v) => MapEntry(k, '$v'), + ), ); } return text; @@ -443,6 +469,7 @@ class DocwellApiException implements Exception { this.code = 'unknown', this.challenge = '', this.message = '', + this.fields = const {}, }); final int status; @@ -456,6 +483,12 @@ class DocwellApiException implements Exception { /// The server's human-readable explanation, when it sent one. final String message; + /// Per-field explanations of a "validation" error. + final Map fields; + + /// The most specific explanation the server gave, or ''. + String get explanation => fields.values.firstOrNull ?? message; + @override String toString() => 'Docwell API error $status ($code)'; } diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 8e8722e..5984470 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -4597,6 +4597,10 @@ class CalendarAccount { required this.lastError, required this.events, required this.created, + required this.canWrite, + required this.needsReconnect, + required this.targets, + required this.writeTo, }); factory CalendarAccount.fromJson(Map json) => @@ -4613,6 +4617,12 @@ class CalendarAccount { lastError: json['lastError'] as String, events: (json['events'] as num).toInt(), created: json['created'] as String, + canWrite: json['canWrite'] as bool, + needsReconnect: json['needsReconnect'] as bool, + targets: (json['targets'] as List) + .map((e) => CalendarTarget.fromJson(e as Map)) + .toList(), + writeTo: json['writeTo'] as String, ); final String id; @@ -4644,6 +4654,18 @@ class CalendarAccount { final String created; + /// Events can be added to and changed in this calendar + final bool canWrite; + + /// A Google account connected read-only; connecting it again allows editing + final bool needsReconnect; + + /// The account's calendars new events can go to (filled by a sync) + final List targets; + + /// The target new events go to; empty when there is none + final String writeTo; + Map toJson() => { 'id': id, 'name': name, @@ -4657,6 +4679,71 @@ class CalendarAccount { 'lastError': lastError, 'events': events, 'created': created, + 'canWrite': canWrite, + 'needsReconnect': needsReconnect, + 'targets': targets.map((e) => e.toJson()).toList(), + 'writeTo': writeTo, + }; +} + +class CalendarTarget { + const CalendarTarget({required this.id, required this.name}); + + factory CalendarTarget.fromJson(Map json) => + CalendarTarget(id: json['id'] as String, name: json['name'] as String); + + /// A CalDAV collection path or a Google calendar id + final String id; + + /// Empty when the account is a single CalDAV calendar + final String name; + + Map toJson() => {'id': id, 'name': name}; +} + +/// Creating needs calendar, title and start; changing sends only what changes. +class CalendarEventInput { + const CalendarEventInput({ + this.calendar, + this.title, + this.location, + this.start, + this.end, + this.allDay, + }); + + factory CalendarEventInput.fromJson(Map json) => + CalendarEventInput( + calendar: json['calendar'] == null ? null : json['calendar'] as String, + title: json['title'] == null ? null : json['title'] as String, + location: json['location'] == null ? null : json['location'] as String, + start: json['start'] == null ? null : json['start'] as String, + end: json['end'] == null ? null : json['end'] as String, + allDay: json['allDay'] == null ? null : json['allDay'] as bool, + ); + + /// The calendar account's id (creating only) + final String? calendar; + + final String? title; + + final String? location; + + /// RFC 3339 time, or a date (YYYY-MM-DD) when allDay + final String? start; + + /// Exclusive, written like start; missing is an hour (or a day) after start, or the old length when moving + final String? end; + + final bool? allDay; + + Map toJson() => { + 'calendar': ?calendar, + 'title': ?title, + 'location': ?location, + 'start': ?start, + 'end': ?end, + 'allDay': ?allDay, }; } @@ -4686,6 +4773,7 @@ class CalendarAccountInput { this.clearPassword, this.color, this.enabled, + this.writeTo, }); factory CalendarAccountInput.fromJson(Map json) => @@ -4704,6 +4792,7 @@ class CalendarAccountInput { ? null : LabelColor.fromJson(json['color'] as String), enabled: json['enabled'] == null ? null : json['enabled'] as bool, + writeTo: json['writeTo'] == null ? null : json['writeTo'] as String, ); final String? name; @@ -4724,6 +4813,9 @@ class CalendarAccountInput { final bool? enabled; + /// One of the account's targets (changing only); empty for the first + final String? writeTo; + Map toJson() => { 'name': ?name, 'kind': ?kind?.toJson(), @@ -4733,6 +4825,7 @@ class CalendarAccountInput { 'clearPassword': ?clearPassword, 'color': ?color?.toJson(), 'enabled': ?enabled, + 'writeTo': ?writeTo, }; } @@ -4747,6 +4840,7 @@ class CalendarEvent { required this.end, required this.allDay, required this.color, + required this.editable, }); factory CalendarEvent.fromJson(Map json) => CalendarEvent( @@ -4759,6 +4853,7 @@ class CalendarEvent { end: json['end'] as String, allDay: json['allDay'] as bool, color: LabelColor.fromJson(json['color'] as String), + editable: json['editable'] as bool, ); final String id; @@ -4782,6 +4877,9 @@ class CalendarEvent { final LabelColor color; + /// Can be changed and deleted here: a single event in a calendar that takes changes + final bool editable; + Map toJson() => { 'id': id, 'calendar': calendar, @@ -4792,6 +4890,7 @@ class CalendarEvent { 'end': end, 'allDay': allDay, 'color': color.toJson(), + 'editable': editable, }; } diff --git a/Phone-App/lib/l10n.dart b/Phone-App/lib/l10n.dart index bed0c76..3fd9d99 100644 --- a/Phone-App/lib/l10n.dart +++ b/Phone-App/lib/l10n.dart @@ -37,6 +37,21 @@ String tr(String key, [Map args = const {}]) { const appStrings = >{ 'en': { + 'addEvent': 'Add event', + 'editEvent': 'Change event', + 'eventTitle': 'Title', + 'eventStart': 'Starts', + 'eventEnd': 'Ends', + 'eventLastDay': 'Last day', + 'eventLocation': 'Place (optional)', + 'eventCalendar': 'Calendar', + 'saveEvent': 'Save', + 'deleteEvent': 'Delete', + 'confirmDeleteEvent': 'Delete “{title}” from its calendar?', + 'eventStale': + 'This event was changed in its calendar meanwhile. Make your change again.', + 'eventGone': 'This event is no longer in its calendar.', + 'eventSaveFailed': 'The calendar did not take the change.', 'journalToday': "Today's journal", 'journalTodayHint': "Your daily page, with your calendar's events", 'calendar': 'Calendar', @@ -185,6 +200,21 @@ const appStrings = >{ 'redo': 'Redo', }, 'pl': { + 'addEvent': 'Dodaj wydarzenie', + 'editEvent': 'Zmień wydarzenie', + 'eventTitle': 'Tytuł', + 'eventStart': 'Początek', + 'eventEnd': 'Koniec', + 'eventLastDay': 'Ostatni dzień', + 'eventLocation': 'Miejsce (opcjonalnie)', + 'eventCalendar': 'Kalendarz', + 'saveEvent': 'Zapisz', + 'deleteEvent': 'Usuń', + 'confirmDeleteEvent': 'Usunąć „{title}” z kalendarza?', + 'eventStale': + 'To wydarzenie zmieniono w międzyczasie w jego kalendarzu. Wprowadź zmianę jeszcze raz.', + 'eventGone': 'Tego wydarzenia nie ma już w jego kalendarzu.', + 'eventSaveFailed': 'Kalendarz nie przyjął zmiany.', 'journalToday': 'Dzisiejszy dziennik', 'journalTodayHint': 'Twoja strona dnia z wydarzeniami z kalendarza', 'calendar': 'Kalendarz', @@ -333,6 +363,21 @@ const appStrings = >{ 'redo': 'Ponów', }, 'de': { + 'addEvent': 'Termin hinzufügen', + 'editEvent': 'Termin ändern', + 'eventTitle': 'Titel', + 'eventStart': 'Beginn', + 'eventEnd': 'Ende', + 'eventLastDay': 'Letzter Tag', + 'eventLocation': 'Ort (optional)', + 'eventCalendar': 'Kalender', + 'saveEvent': 'Speichern', + 'deleteEvent': 'Löschen', + 'confirmDeleteEvent': '„{title}“ aus seinem Kalender löschen?', + 'eventStale': + 'Dieser Termin wurde inzwischen in seinem Kalender geändert. Nimm deine Änderung noch einmal vor.', + 'eventGone': 'Dieser Termin ist nicht mehr in seinem Kalender.', + 'eventSaveFailed': 'Der Kalender hat die Änderung nicht übernommen.', 'journalToday': 'Heutiges Journal', 'journalTodayHint': 'Deine Tagesseite mit den Terminen aus deinem Kalender', 'calendar': 'Kalender', @@ -484,6 +529,21 @@ const appStrings = >{ 'redo': 'Wiederholen', }, 'fr': { + 'addEvent': 'Ajouter un événement', + 'editEvent': 'Modifier l’événement', + 'eventTitle': 'Titre', + 'eventStart': 'Début', + 'eventEnd': 'Fin', + 'eventLastDay': 'Dernier jour', + 'eventLocation': 'Lieu (facultatif)', + 'eventCalendar': 'Agenda', + 'saveEvent': 'Enregistrer', + 'deleteEvent': 'Supprimer', + 'confirmDeleteEvent': 'Supprimer « {title} » de son agenda ?', + 'eventStale': + 'Cet événement a été modifié entre-temps dans son agenda. Refaites votre modification.', + 'eventGone': 'Cet événement n’est plus dans son agenda.', + 'eventSaveFailed': 'L’agenda n’a pas accepté la modification.', 'journalToday': 'Journal du jour', 'journalTodayHint': 'Votre page du jour, avec les événements de votre agenda', @@ -636,6 +696,21 @@ const appStrings = >{ 'redo': 'Rétablir', }, 'es': { + 'addEvent': 'Añadir evento', + 'editEvent': 'Cambiar evento', + 'eventTitle': 'Título', + 'eventStart': 'Empieza', + 'eventEnd': 'Termina', + 'eventLastDay': 'Último día', + 'eventLocation': 'Lugar (opcional)', + 'eventCalendar': 'Calendario', + 'saveEvent': 'Guardar', + 'deleteEvent': 'Eliminar', + 'confirmDeleteEvent': '¿Eliminar «{title}» de su calendario?', + 'eventStale': + 'Este evento se cambió mientras tanto en su calendario. Vuelve a hacer tu cambio.', + 'eventGone': 'Este evento ya no está en su calendario.', + 'eventSaveFailed': 'El calendario no aceptó el cambio.', 'journalToday': 'Diario de hoy', 'journalTodayHint': 'Tu página del día, con los eventos de tu calendario', 'calendar': 'Calendario', diff --git a/Phone-App/lib/screens/event_editor.dart b/Phone-App/lib/screens/event_editor.dart new file mode 100644 index 0000000..0302ce3 --- /dev/null +++ b/Phone-App/lib/screens/event_editor.dart @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'package:flutter/material.dart'; + +import '../api/docwell_api.dart'; +import '../l10n.dart'; + +/// What [showEventEditor] did, so the journal knows to read its events again. +enum EventEditResult { saved, deleted, stale } + +/// Opens a sheet to add an event on [day] to one of [calendars] (those whose +/// canWrite is true), or to change or delete [event] (ADR-19). The change +/// goes to the calendar at once. When it changed in its calendar since the +/// last sync, the server refuses and the sheet closes with +/// [EventEditResult.stale] after saying so. +Future showEventEditor( + BuildContext context, { + required DocwellApi api, + required DateTime day, + required List calendars, + CalendarEvent? event, +}) => showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + builder: (_) => + EventEditor(api: api, day: day, calendars: calendars, event: event), +); + +DateTime _date(DateTime d) => DateTime(d.year, d.month, d.day); + +String _two(int n) => n.toString().padLeft(2, '0'); + +/// A date as the server takes it for all-day events. +String eventDay(DateTime d) => '${d.year}-${_two(d.month)}-${_two(d.day)}'; + +/// The input sent for an event: all-day ones as dates (lastDay inclusive on +/// screen, exclusive on the wire), timed ones as UTC instants. +CalendarEventInput eventInput({ + String? calendar, + required String title, + required String location, + required bool allDay, + required DateTime start, + required DateTime end, +}) { + if (allDay) { + final first = _date(start); + var last = _date(end); + if (last.isBefore(first)) last = first; + return CalendarEventInput( + calendar: calendar, + title: title.trim(), + location: location.trim(), + allDay: true, + start: eventDay(first), + end: eventDay(last.add(const Duration(days: 1))), + ); + } + return CalendarEventInput( + calendar: calendar, + title: title.trim(), + location: location.trim(), + allDay: false, + start: start.toUtc().toIso8601String(), + end: end.toUtc().toIso8601String(), + ); +} + +class EventEditor extends StatefulWidget { + const EventEditor({ + super.key, + required this.api, + required this.day, + required this.calendars, + this.event, + }); + + final DocwellApi api; + final DateTime day; + final List calendars; + final CalendarEvent? event; + + @override + State createState() => _EventEditorState(); +} + +class _EventEditorState extends State { + late final TextEditingController _title; + late final TextEditingController _location; + late bool _allDay; + // For all-day events, _end is the last day (inclusive). + late DateTime _start; + late DateTime _end; + String? _calendar; + bool _busy = false; + String _error = ''; + + @override + void initState() { + super.initState(); + final e = widget.event; + _title = TextEditingController(text: e?.title ?? ''); + _location = TextEditingController(text: e?.location ?? ''); + _allDay = e?.allDay ?? false; + if (e == null) { + final hour = (DateTime.now().hour + 1).clamp(0, 23); + _start = DateTime( + widget.day.year, + widget.day.month, + widget.day.day, + hour, + ); + _end = _start.add(const Duration(hours: 1)); + _calendar = widget.calendars.isEmpty ? null : widget.calendars.first.id; + } else if (e.allDay) { + _start = DateTime.parse(e.start); + _end = DateTime.parse(e.end).subtract(const Duration(days: 1)); + } else { + _start = DateTime.parse(e.start).toLocal(); + _end = DateTime.parse(e.end).toLocal(); + } + _title.addListener(() => setState(() {})); + } + + @override + void dispose() { + _title.dispose(); + _location.dispose(); + super.dispose(); + } + + bool get _valid => + _title.text.trim().isNotEmpty && (_allDay || _end.isAfter(_start)); + + Future _pickDate(bool start) async { + final current = start ? _start : _end; + final picked = await showDatePicker( + context: context, + initialDate: current, + firstDate: DateTime(current.year - 5), + lastDate: DateTime(current.year + 5), + ); + if (picked == null || !mounted) return; + setState(() { + final moved = DateTime( + picked.year, + picked.month, + picked.day, + current.hour, + current.minute, + ); + if (start) { + // Keep the length when the start moves. + final length = _end.difference(_start); + _start = moved; + _end = moved.add(length); + } else { + _end = moved; + } + }); + } + + Future _pickTime(bool start) async { + final current = start ? _start : _end; + final picked = await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(current), + ); + if (picked == null || !mounted) return; + setState(() { + final moved = DateTime( + current.year, + current.month, + current.day, + picked.hour, + picked.minute, + ); + if (start) { + final length = _end.difference(_start); + _start = moved; + _end = moved.add(length); + } else { + _end = moved; + } + }); + } + + Future _run( + Future Function() action, + EventEditResult done, + ) async { + setState(() { + _busy = true; + _error = ''; + }); + try { + await action(); + if (mounted) Navigator.of(context).pop(done); + } on DocwellApiException catch (e) { + if (!mounted) return; + if (e.status == 409 || e.status == 404) { + // Nothing was overwritten; the journal reads the calendar again. + final messenger = ScaffoldMessenger.of(context); + Navigator.of(context).pop(EventEditResult.stale); + messenger.showSnackBar( + SnackBar( + content: Text( + e.explanation.isNotEmpty + ? e.explanation + : tr(e.status == 409 ? 'eventStale' : 'eventGone'), + ), + ), + ); + return; + } + setState( + () => _error = e.explanation.isNotEmpty + ? e.explanation + : tr('eventSaveFailed'), + ); + } catch (_) { + if (mounted) setState(() => _error = tr('errOffline')); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _save() { + final input = eventInput( + calendar: widget.event == null ? _calendar : null, + title: _title.text, + location: _location.text, + allDay: _allDay, + start: _start, + end: _end, + ); + final e = widget.event; + return _run( + () => e == null + ? widget.api.createCalendarEvent(input) + : widget.api.updateCalendarEvent(e.id, input), + EventEditResult.saved, + ); + } + + Future _delete() async { + final e = widget.event!; + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + content: Text(tr('confirmDeleteEvent', {'title': e.title})), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text(tr('cancel')), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: Text(tr('deleteEvent')), + ), + ], + ), + ); + if (ok != true || !mounted) return; + await _run( + () => widget.api.deleteCalendarEvent(e.id), + EventEditResult.deleted, + ); + } + + @override + Widget build(BuildContext context) { + final loc = MaterialLocalizations.of(context); + final h24 = MediaQuery.of(context).alwaysUse24HourFormat; + String date(DateTime d) => loc.formatMediumDate(d); + String time(DateTime d) => loc.formatTimeOfDay( + TimeOfDay.fromDateTime(d), + alwaysUse24HourFormat: h24, + ); + Widget row(String label, bool start) { + final d = start ? _start : _end; + return Row( + children: [ + Expanded(child: Text(label)), + TextButton( + key: Key(start ? 'event-start-date' : 'event-end-date'), + onPressed: _busy ? null : () => _pickDate(start), + child: Text(date(d)), + ), + if (!_allDay) + TextButton( + key: Key(start ? 'event-start-time' : 'event-end-time'), + onPressed: _busy ? null : () => _pickTime(start), + child: Text(time(d)), + ), + ], + ); + } + + return Padding( + padding: EdgeInsets.fromLTRB( + 16, + 0, + 16, + 16 + MediaQuery.of(context).viewInsets.bottom, + ), + child: SingleChildScrollView( + child: Column( + key: const Key('event-editor'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + tr(widget.event == null ? 'addEvent' : 'editEvent'), + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + TextField( + key: const Key('event-title'), + controller: _title, + autofocus: widget.event == null, + textCapitalization: TextCapitalization.sentences, + decoration: InputDecoration(labelText: tr('eventTitle')), + ), + SwitchListTile( + key: const Key('event-all-day'), + contentPadding: EdgeInsets.zero, + title: Text(tr('allDay')), + value: _allDay, + onChanged: _busy ? null : (v) => setState(() => _allDay = v), + ), + row(tr('eventStart'), true), + row(tr(_allDay ? 'eventLastDay' : 'eventEnd'), false), + TextField( + controller: _location, + decoration: InputDecoration(labelText: tr('eventLocation')), + ), + if (widget.event == null && widget.calendars.length > 1) + DropdownButtonFormField( + initialValue: _calendar, + decoration: InputDecoration(labelText: tr('eventCalendar')), + items: [ + for (final c in widget.calendars) + DropdownMenuItem(value: c.id, child: Text(c.name)), + ], + onChanged: _busy ? null : (v) => setState(() => _calendar = v), + ), + if (_error.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + _error, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + const SizedBox(height: 12), + Row( + children: [ + if (widget.event != null) + TextButton( + key: const Key('event-delete'), + onPressed: _busy ? null : _delete, + child: Text(tr('deleteEvent')), + ), + const Spacer(), + TextButton( + onPressed: _busy ? null : () => Navigator.of(context).pop(), + child: Text(tr('cancel')), + ), + const SizedBox(width: 8), + FilledButton( + key: const Key('event-save'), + onPressed: _busy || !_valid ? null : _save, + child: Text(tr('saveEvent')), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/Phone-App/lib/screens/journal_events.dart b/Phone-App/lib/screens/journal_events.dart index 784ccbf..80a1fc6 100644 --- a/Phone-App/lib/screens/journal_events.dart +++ b/Phone-App/lib/screens/journal_events.dart @@ -4,9 +4,12 @@ import 'package:flutter/material.dart'; import '../api/docwell_api.dart'; import '../l10n.dart'; +import 'event_editor.dart'; /// The signed-in person's calendar events on a journal day (ADR-16), above -/// the journal page. Shows nothing when there are none or calendars are off. +/// the journal page. Events of calendars that take changes can be added, +/// changed and deleted here (ADR-19). Shows nothing when there are no events +/// and no calendar to add one to, or calendars are off. class JournalEvents extends StatefulWidget { const JournalEvents({super.key, required this.api, required this.date}); @@ -50,6 +53,7 @@ String _day(DateTime d) => '${d.year}-${_two(d.month)}-${_two(d.day)}'; class _JournalEventsState extends State { List _events = const []; + List _writable = const []; @override void initState() { @@ -73,12 +77,44 @@ class _JournalEventsState extends State { _day(day.subtract(const Duration(days: 1))), _day(day.add(const Duration(days: 1))), ); - if (mounted) setState(() => _events = eventsOn(list, day)); + List writable = const []; + try { + writable = (await widget.api.calendars()) + .where((c) => c.enabled && c.canWrite) + .toList(); + } catch (_) {} + if (mounted) { + setState(() { + _events = eventsOn(list, day); + _writable = writable; + }); + } } catch (_) { // Calendars are a help on the journal; their problems stay quiet here. } } + Future _edit([CalendarEvent? event]) async { + final day = DateTime.tryParse(widget.date); + if (day == null) return; + final done = await showEventEditor( + context, + api: widget.api, + day: day, + calendars: _writable, + event: event, + ); + if (done == null) return; + await _load(); + // After a refused change the server reads the calendar again; look once + // more when it has. + if (done == EventEditResult.stale) { + Future.delayed(const Duration(seconds: 4), () { + if (mounted) _load(); + }); + } + } + String _time(BuildContext context, String iso) => MaterialLocalizations.of(context).formatTimeOfDay( TimeOfDay.fromDateTime(DateTime.parse(iso).toLocal()), @@ -87,7 +123,7 @@ class _JournalEventsState extends State { @override Widget build(BuildContext context) { - if (_events.isEmpty) return const SizedBox.shrink(); + if (_events.isEmpty && _writable.isEmpty) return const SizedBox.shrink(); final theme = Theme.of(context); return Material( key: const Key('journal-events'), @@ -98,38 +134,62 @@ class _JournalEventsState extends State { shrinkWrap: true, padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), children: [ - Text( - tr('calendar').toUpperCase(), - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), + Row( + children: [ + Expanded( + child: Text( + tr('calendar').toUpperCase(), + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + if (_writable.isNotEmpty) + IconButton( + key: const Key('journal-event-add'), + visualDensity: VisualDensity.compact, + tooltip: tr('addEvent'), + icon: const Icon(Icons.add, size: 20), + onPressed: () => _edit(), + ), + ], ), for (final e in _events) - Padding( - padding: const EdgeInsets.only(top: 4), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - width: 104, - child: Text( - e.allDay - ? tr('allDay') - : '${_time(context, e.start)}–${_time(context, e.end)}', - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, + InkWell( + key: Key('journal-event-${e.id}'), + onTap: e.editable ? () => _edit(e) : null, + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 104, + child: Text( + e.allDay + ? tr('allDay') + : '${_time(context, e.start)}–${_time(context, e.end)}', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), ), ), - ), - Expanded( - child: Text( - e.location.isEmpty - ? e.title - : '${e.title} · ${e.location}', - style: theme.textTheme.bodyMedium, + Expanded( + child: Text( + e.location.isEmpty + ? e.title + : '${e.title} · ${e.location}', + style: theme.textTheme.bodyMedium, + ), ), - ), - ], + if (e.editable) + Icon( + Icons.edit_outlined, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), ), ), ], diff --git a/Phone-App/test/journal_events_test.dart b/Phone-App/test/journal_events_test.dart index 81e0cc4..9f61343 100644 --- a/Phone-App/test/journal_events_test.dart +++ b/Phone-App/test/journal_events_test.dart @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import 'package:docwell_mobile/api/docwell_api.dart'; +import 'package:docwell_mobile/screens/event_editor.dart'; import 'package:docwell_mobile/screens/journal_events.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -19,6 +20,7 @@ CalendarEvent ev( 'end': end, 'allDay': allDay, 'color': 'blue', + 'editable': false, }); String local(int day, int hour) => @@ -46,4 +48,50 @@ void main() { ).map((e) => e.title).toList(); expect(got, ['Holiday', 'Overnight', 'Morning', 'Late']); }); + + test('sends all-day events as dates with an exclusive end', () { + final input = eventInput( + calendar: 'c1', + title: ' Trip ', + location: '', + allDay: true, + start: DateTime(2026, 11, 20, 15), + end: DateTime(2026, 11, 22, 9), // the last day, shown inclusive + ); + expect(input.toJson(), { + 'calendar': 'c1', + 'title': 'Trip', + 'location': '', + 'start': '2026-11-20', + 'end': '2026-11-23', + 'allDay': true, + }); + // A last day before the first is one day. + final one = eventInput( + title: 'x', + location: '', + allDay: true, + start: DateTime(2026, 11, 20), + end: DateTime(2026, 11, 19), + ); + expect(one.end, '2026-11-21'); + expect(one.toJson().containsKey('calendar'), isFalse); + }); + + test('sends timed events as UTC instants', () { + final start = DateTime(2026, 11, 20, 9, 30); + final input = eventInput( + title: 'Call', + location: 'Room 1', + allDay: false, + start: start, + end: start.add(const Duration(minutes: 45)), + ); + expect(DateTime.parse(input.start!).isAtSameMomentAs(start), isTrue); + expect(input.start!.endsWith('Z'), isTrue); + expect( + DateTime.parse(input.end!).difference(DateTime.parse(input.start!)), + const Duration(minutes: 45), + ); + }); } diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index ab33cf1..8cd4b3f 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -1537,6 +1537,9 @@ type BrandingSettings struct { // CalendarAccount defines model for CalendarAccount. type CalendarAccount struct { + // CanWrite Events can be added to and changed in this calendar + CanWrite bool `json:"canWrite"` + // Color A colour of the editor palette, drawn from the theme; empty for none Color LabelColor `json:"color"` Created string `json:"created"` @@ -1558,8 +1561,17 @@ type CalendarAccount struct { // LastSync When the source was last read LastSync string `json:"lastSync"` Name string `json:"name"` - Url string `json:"url"` - Username string `json:"username"` + + // NeedsReconnect A Google account connected read-only; connecting it again allows editing + NeedsReconnect bool `json:"needsReconnect"` + + // Targets The account's calendars new events can go to (filled by a sync) + Targets []CalendarTarget `json:"targets"` + Url string `json:"url"` + Username string `json:"username"` + + // WriteTo The target new events go to; empty when there is none + WriteTo string `json:"writeTo"` } // CalendarAccountKind google accounts are connected with /calendars/google/connect @@ -1581,6 +1593,9 @@ type CalendarAccountInput struct { // Url http, https or webcal address Url *string `json:"url,omitempty"` Username *string `json:"username,omitempty"` + + // WriteTo One of the account's targets (changing only); empty for the first + WriteTo *string `json:"writeTo,omitempty"` } // CalendarAccountInputKind defines model for CalendarAccountInput.Kind. @@ -1596,6 +1611,9 @@ type CalendarEvent struct { // Color A colour of the editor palette, drawn from the theme; empty for none Color LabelColor `json:"color"` + // Editable Can be changed and deleted here: a single event in a calendar that takes changes + Editable bool `json:"editable"` + // End Exclusive; a date for all-day events End string `json:"end"` Id string `json:"id"` @@ -1607,6 +1625,31 @@ type CalendarEvent struct { Url string `json:"url"` } +// CalendarEventInput Creating needs calendar, title and start; changing sends only what changes. +type CalendarEventInput struct { + AllDay *bool `json:"allDay,omitempty"` + + // Calendar The calendar account's id (creating only) + Calendar *string `json:"calendar,omitempty"` + + // End Exclusive, written like start; missing is an hour (or a day) after start, or the old length when moving + End *string `json:"end,omitempty"` + Location *string `json:"location,omitempty"` + + // Start RFC 3339 time, or a date (YYYY-MM-DD) when allDay + Start *string `json:"start,omitempty"` + Title *string `json:"title,omitempty"` +} + +// CalendarTarget defines model for CalendarTarget. +type CalendarTarget struct { + // Id A CalDAV collection path or a Google calendar id + Id string `json:"id"` + + // Name Empty when the account is a single CalDAV calendar + Name string `json:"name"` +} + // Collection defines model for Collection. type Collection struct { CanEdit bool `json:"canEdit"` @@ -3568,6 +3611,12 @@ type ConfirmVerificationJSONRequestBody ConfirmVerificationJSONBody // RequestVerificationJSONRequestBody defines body for RequestVerification for application/json ContentType. type RequestVerificationJSONRequestBody = EmailRequest +// CreateCalendarEventJSONRequestBody defines body for CreateCalendarEvent for application/json ContentType. +type CreateCalendarEventJSONRequestBody = CalendarEventInput + +// UpdateCalendarEventJSONRequestBody defines body for UpdateCalendarEvent for application/json ContentType. +type UpdateCalendarEventJSONRequestBody = CalendarEventInput + // CreateCalendarJSONRequestBody defines body for CreateCalendar for application/json ContentType. type CreateCalendarJSONRequestBody = CalendarAccountInput diff --git a/Server/internal/calendar/calendar.go b/Server/internal/calendar/calendar.go index 622f7d9..99b55cb 100644 --- a/Server/internal/calendar/calendar.go +++ b/Server/internal/calendar/calendar.go @@ -1,13 +1,18 @@ // 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, Outlook's published calendar, any feed), a CalDAV account -// (Nextcloud, iCloud, Fastmail…) or a Google account signed in with OAuth. -// Each person sees only their own. The calendars.sync job copies the events -// of every account, a few months back and a year ahead, into -// calendar_events every 15 minutes, so journals on the web and on phones -// read them at once and still show them when a source is down. +// ADR-16): subscriptions to an iCalendar feed (an .ics or webcal address, +// Outlook's published calendar, any feed), a CalDAV account (Nextcloud, +// iCloud, Fastmail…) or a Google account signed in with OAuth. Each person +// sees only their own. The calendars.sync job copies the events of every +// account, a few months back and a year ahead, into calendar_events every +// 15 minutes, so journals on the web and on phones read them at once and +// still show them when a source is down. +// +// CalDAV and Google accounts can also be written to (write.go, ADR-19): +// events are created, changed and deleted at the source straight away, +// guarded by the ETag last read, so a change made elsewhere since is never +// overwritten. Feeds and repeating events stay read-only. package calendar import ( @@ -181,6 +186,37 @@ type record struct { LastError string `json:"last_error"` Events float64 `json:"events"` Created string `json:"created"` + // CanWrite: events can be added and changed (CalDAV, or Google signed in + // with the events scope). Targets are the calendars new events can go + // to; WriteTo the one chosen ("" = the first). + CanWrite bool `json:"can_write"` + Targets []Target `json:"targets"` + WriteTo string `json:"write_to"` +} + +// Target is a calendar of an account that new events can be added to: a +// CalDAV collection's path or a Google calendar's id. +type Target struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// target is the calendar new events of r go to, or "" when r has none. +func (r record) target() string { + for _, t := range r.Targets { + if t.ID == r.WriteTo { + return t.ID + } + } + if len(r.Targets) > 0 { + return r.Targets[0].ID + } + return "" +} + +// writable reports whether events of r can be added and changed. +func (r record) writable() bool { + return r.Enabled && r.CanWrite && r.Kind != KindICS && r.target() != "" } // Account is a calendar subscription as its owner sees it, without the password. @@ -199,13 +235,25 @@ type Account struct { // Events counts the events (repeating ones once) the source held then. Events int `json:"events"` Created string `json:"created"` + // CanWrite tells whether events can be added to and changed in this + // calendar; a Google account connected before writing existed needs to + // be connected again (NeedsReconnect). + CanWrite bool `json:"canWrite"` + NeedsReconnect bool `json:"needsReconnect"` + Targets []Target `json:"targets"` + WriteTo string `json:"writeTo"` } func (r record) view() Account { + targets := r.Targets + if targets == nil { + targets = []Target{} + } 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, + Created: r.Created, CanWrite: r.Kind != KindICS && r.CanWrite && len(targets) > 0, + NeedsReconnect: r.Kind == KindGoogle && !r.CanWrite, Targets: targets, WriteTo: r.target(), } } @@ -220,6 +268,8 @@ type AccountInput struct { ClearPassword bool `json:"clearPassword"` Color *string `json:"color"` Enabled *bool `json:"enabled"` + // WriteTo picks the calendar new events go to (one of the account's targets). + WriteTo *string `json:"writeTo"` } func signedIn(c access.Caller) error { @@ -322,6 +372,16 @@ func (s *Service) patch(in AccountInput, old record) (map[string]any, record, er if in.Enabled != nil { p["enabled"], next.Enabled = *in.Enabled, *in.Enabled } + if in.WriteTo != nil { + ok := *in.WriteTo == "" + for _, t := range old.Targets { + ok = ok || t.ID == *in.WriteTo + } + if !ok { + return bad("writeTo", "Pick one of the account's calendars.") + } + p["write_to"], next.WriteTo = *in.WriteTo, *in.WriteTo + } return p, next, nil } @@ -342,6 +402,7 @@ func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput) if len(rows) >= maxAccounts { return Account{}, apperr.Invalid(fmt.Sprintf("you can add at most %d calendars", maxAccounts)) } + in.WriteTo = nil // The calendars are known once it has been read. if in.Color == nil { color := colors[(len(rows)+6)%len(colors)] in.Color = &color @@ -359,19 +420,19 @@ func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput) // add reads a new account, then stores it and (in the background) its events. func (s *Service) add(ctx context.Context, user string, body map[string]any, next record) (Account, error) { - items, count, err := s.collect(ctx, next) + read, err := s.collect(ctx, next) if err != nil { return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()}) } body["user"] = user body["last_sync"] = pbTime(time.Now()) body["last_error"] = "" - body["events"] = count + read.into(body, next.Kind) rec, err := pocketbase.Create[record](ctx, s.pb, "calendar_accounts", body) if err != nil { return Account{}, err } - s.storeLater(rec, items) + s.storeLater(rec, read.items) return rec.view(), nil } @@ -388,21 +449,21 @@ func (s *Service) Update(ctx context.Context, c access.Caller, id string, in Acc if len(body) == 0 { return old.view(), nil } - var items []item + var read reading changed := sourceKey(next) != sourceKey(old) if changed { - var count int - if items, count, err = s.collect(ctx, next); err != nil { + if read, err = s.collect(ctx, next); err != nil { return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()}) } - body["last_sync"], body["last_error"], body["events"] = pbTime(time.Now()), "", count + body["last_sync"], body["last_error"] = pbTime(time.Now()), "" + read.into(body, next.Kind) } rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", old.ID, body) if err != nil { return Account{}, err } if changed { - s.storeLater(rec, items) + s.storeLater(rec, read.items) } return rec.view(), nil } @@ -451,25 +512,70 @@ type item struct { key, title, location, url string allDay bool start, end time.Time + // Where the event is at the source, to change it: the calendar (CalDAV + // collection path or Google calendar id), the event (CalDAV object path + // or Google event id) and its ETag. recurring marks an occurrence of a + // repeating event, which is changed in its own calendar app. + cal, ref, etag string + recurring bool } // hash tells a changed occurrence from an unchanged one. func (it item) hash() string { - h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%s\x00%t\x00%d\x00%d", it.title, it.location, it.url, it.allDay, it.start.Unix(), it.end.Unix()))) + h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%s\x00%t\x00%d\x00%d\x00%s\x00%s\x00%s\x00%t", it.title, it.location, it.url, it.allDay, + it.start.Unix(), it.end.Unix(), it.cal, it.ref, it.etag, it.recurring))) return hex.EncodeToString(h[:12]) } +// body is the stored record of it (without account, user and key). +func (it item) body() map[string]any { + return map[string]any{ + "hash": it.hash(), "title": clip(it.title, 1000), "location": clip(it.location, 1000), "url": clip(it.url, 2000), + "all_day": it.allDay, "start_at": pbTime(it.start), "end_at": pbTime(it.end), + "cal": clip(it.cal, 2000), "ref": clip(it.ref, 2000), "etag": clip(it.etag, 500), "recurring": it.recurring, + } +} + +// reading is what one read of an account's source found. +type reading struct { + items []item + count int // events the source holds (repeating ones once) + targets []Target // calendars new events can go to +} + +// into writes what the read tells about the account into its record body. +func (rd reading) into(body map[string]any, kind string) { + body["events"] = rd.count + if kind == KindICS { + return + } + targets := rd.targets + if targets == nil { + targets = []Target{} + } + body["targets"] = targets + if kind == KindCalDAV { + // Google's write access comes from its sign-in (GoogleCallback). + body["can_write"] = len(targets) > 0 + } +} + type eventRecord struct { - ID string `json:"id"` - Account string `json:"account"` - Key string `json:"key"` - Hash string `json:"hash"` - Title string `json:"title"` - Location string `json:"location"` - URL string `json:"url"` - AllDay bool `json:"all_day"` - StartAt string `json:"start_at"` - EndAt string `json:"end_at"` + ID string `json:"id"` + Account string `json:"account"` + Key string `json:"key"` + Hash string `json:"hash"` + Title string `json:"title"` + Location string `json:"location"` + URL string `json:"url"` + AllDay bool `json:"all_day"` + StartAt string `json:"start_at"` + EndAt string `json:"end_at"` + Cal string `json:"cal"` + Ref string `json:"ref"` + ETag string `json:"etag"` + Recurring bool `json:"recurring"` + User string `json:"user"` } // window is the stretch of time stored for each account. @@ -480,7 +586,7 @@ func window(now time.Time) (time.Time, time.Time) { // collect reads an account's source: its occurrences in the window, and how // many events it holds (repeating ones once). -func (s *Service) collect(ctx context.Context, r record) ([]item, int, error) { +func (s *Service) collect(ctx context.Context, r record) (reading, error) { ctx, cancel := context.WithTimeout(ctx, 2*fetchTimeout) defer cancel() from, to := window(time.Now()) @@ -489,17 +595,31 @@ func (s *Service) collect(ctx context.Context, r record) ([]item, int, error) { } password, err := s.open(r.Secret) if err != nil { - return nil, 0, err - } - data, err := fetch(ctx, s.client, source{kind: r.Kind, url: r.URL, username: r.Username, password: password}) - if err != nil { - return nil, 0, err + return reading{}, err } + src := source{kind: r.Kind, url: r.URL, username: r.Username, password: password} // All-day dates are read at 00:00 UTC, so they stay the same date // whatever zone a journal is read in. - f, err := parseFeed(bytes.NewReader(data), time.UTC) - if err != nil { - return nil, 0, err + var f *feed + var targets []Target + if r.Kind == KindCalDAV { + objects, ts, err := fetchCalDAV(ctx, s.client, src) + if err != nil { + return reading{}, err + } + targets = ts + f = &feed{overrides: map[string]map[int64]*eventDef{}} + for _, o := range objects { + _ = f.addObject(o.obj.Data, time.UTC, objRef{cal: o.cal, path: o.obj.Path, etag: o.obj.ETag}) + } + } else { + data, err := fetch(ctx, s.client, src) + if err != nil { + return reading{}, err + } + if f, err = parseFeed(bytes.NewReader(data), time.UTC); err != nil { + return reading{}, err + } } occ := f.between(from, to) items := make([]item, 0, len(occ)) @@ -507,9 +627,11 @@ func (s *Service) collect(ctx context.Context, r record) ([]item, int, error) { items = append(items, item{ key: eventID(o.def.uid, o.start), title: o.def.title, location: o.def.location, url: safeLink(o.def.link), allDay: o.def.allDay, start: o.start.UTC(), end: o.end.UTC(), + cal: o.def.obj.cal, ref: o.def.obj.path, etag: o.def.obj.etag, + recurring: o.def.set != nil || !o.def.recurrenceID.IsZero(), }) } - return items, f.count(), nil + return reading{items: items, count: f.count(), targets: targets}, nil } // Sync reads an account and stores its events. A failed read keeps the @@ -528,7 +650,7 @@ func (s *Service) Sync(ctx context.Context, r record) error { s.mu.Unlock() }() - items, count, err := s.collect(ctx, r) + read, err := s.collect(ctx, r) patch := map[string]any{"last_sync": pbTime(time.Now()), "last_error": ""} if err != nil { msg := err.Error() @@ -537,8 +659,8 @@ func (s *Service) Sync(ctx context.Context, r record) error { } patch["last_error"] = msg } else { - patch["events"] = count - err = s.store(ctx, r, items) + read.into(patch, r.Kind) + err = s.store(ctx, r, read.items) } 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) @@ -590,15 +712,11 @@ func (s *Service) store(ctx context.Context, r record, items []item) error { continue } seen[it.key] = true - hash := it.hash() prev, ok := old[it.key] - if ok && prev.Hash == hash { + if ok && prev.Hash == it.hash() { continue } - body := map[string]any{ - "hash": hash, "title": clip(it.title, 1000), "location": clip(it.location, 1000), "url": clip(it.url, 2000), - "all_day": it.allDay, "start_at": pbTime(it.start), "end_at": pbTime(it.end), - } + body := it.body() if ok { if _, err := pocketbase.Update[eventRecord](ctx, s.pb, "calendar_events", prev.ID, body); err != nil { return err @@ -675,6 +793,9 @@ type Event struct { End string `json:"end"` AllDay bool `json:"allDay"` Color string `json:"color"` + // Editable: the event can be changed and deleted here (a single event + // in a calendar that can be written to). + Editable bool `json:"editable"` } func parsePB(v string) (time.Time, error) { @@ -714,10 +835,12 @@ func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz stri return nil, err } color := map[string]string{} + writable := map[string]bool{} var ids []string for _, r := range rows { if r.Enabled { color[r.ID] = r.Color + writable[r.ID] = r.writable() ids = append(ids, fmt.Sprintf("account = '%s'", r.ID)) } } @@ -740,19 +863,7 @@ func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz stri if err1 != nil || err2 != nil { continue } - ev := Event{ - ID: e.Key, Calendar: e.Account, Title: e.Title, Location: e.Location, URL: e.URL, - AllDay: e.AllDay, Color: color[e.Account], - } - if ev.Title == "" { - ev.Title = "(no title)" - } - if e.AllDay { - ev.Start, ev.End = st.Format(time.DateOnly), en.Format(time.DateOnly) - } else { - ev.Start, ev.End = st.UTC().Format(time.RFC3339), en.UTC().Format(time.RFC3339) - } - out = append(out, ev) + out = append(out, e.view(color[e.Account], writable[e.Account], st, en)) } if page >= res.TotalPages || len(res.Items) == 0 || len(out) >= 2000 { break @@ -770,6 +881,23 @@ func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz stri return out, nil } +// view is a stored event as its owner sees it. +func (e eventRecord) view(color string, writable bool, st, en time.Time) Event { + ev := Event{ + ID: e.Key, Calendar: e.Account, Title: e.Title, Location: e.Location, URL: e.URL, + AllDay: e.AllDay, Color: color, Editable: writable && e.Ref != "" && !e.Recurring, + } + if ev.Title == "" { + ev.Title = "(no title)" + } + if e.AllDay { + ev.Start, ev.End = st.Format(time.DateOnly), en.Format(time.DateOnly) + } else { + ev.Start, ev.End = st.UTC().Format(time.RFC3339), en.UTC().Format(time.RFC3339) + } + return ev +} + func eventID(uid string, start time.Time) string { h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d", uid, start.Unix()))) return hex.EncodeToString(h[:8]) diff --git a/Server/internal/calendar/fetch.go b/Server/internal/calendar/fetch.go index 3942459..eac3c91 100644 --- a/Server/internal/calendar/fetch.go +++ b/Server/internal/calendar/fetch.go @@ -13,7 +13,6 @@ import ( "strings" "time" - "github.com/emersion/go-ical" "github.com/emersion/go-webdav" "github.com/emersion/go-webdav/caldav" ) @@ -41,16 +40,12 @@ func feedURL(raw string) (*url.URL, error) { return u, nil } -// fetch reads the source as iCalendar data (CalDAV objects are joined into -// one stream of VCALENDARs). +// fetch reads an iCalendar feed. 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 @@ -86,17 +81,34 @@ func fetch(ctx context.Context, client *http.Client, src source) ([]byte, error) 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) { +// davClient is an HTTP client for a CalDAV account: answers capped, signed +// in with the account's user name and password. +func davClient(client *http.Client, src source) webdav.HTTPClient { 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()) + return hc +} + +// davObject is one CalDAV object and the calendar collection it is in. +type davObject struct { + cal string + obj caldav.CalendarObject +} + +// fetchCalDAV reads the events of the calendar at src.url, or of every +// calendar of the account when it is the server or the account's home: a +// year back and two years ahead. It also lists the calendars, the ones new +// events can go to. +func fetchCalDAV(ctx context.Context, client *http.Client, src source) ([]davObject, []Target, error) { + u, err := feedURL(src.url) if err != nil { - return nil, err + return nil, nil, err + } + c, err := caldav.NewClient(davClient(client, src), u.String()) + if err != nil { + return nil, nil, err } now := time.Now() query := &caldav.CalendarQuery{ @@ -105,39 +117,50 @@ func fetchCalDAV(ctx context.Context, client *http.Client, u *url.URL, src sourc {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) + // Each answer is capped at 20 MB (limitedClient). + var out []davObject + keep := func(cal string, objects []caldav.CalendarObject) error { + for _, o := range objects { + if o.Data == nil { + continue } - objects = append(objects, got...) + if len(out) >= 4*maxStored { + return errors.New("the calendars hold too many events") + } + out = append(out, davObject{cal: cal, obj: o}) } + return nil } - 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") - } + collection := strings.TrimSuffix(u.Path, "/") + "/" + objects, err := c.QueryCalendar(ctx, u.Path, query) + if err == nil { + return out, []Target{{ID: collection, Name: ""}}, keep(collection, objects) } - return buf.Bytes(), nil + // Not a calendar itself: find the account's calendars. + cals, err := discover(ctx, c, u) + if err != nil { + return nil, nil, err + } + var targets []Target + for _, cal := range cals { + path := strings.TrimSuffix(cal.Path, "/") + "/" + got, err := c.QueryCalendar(ctx, cal.Path, query) + if err != nil { + return nil, nil, friendly(err) + } + if err := keep(path, got); err != nil { + return nil, nil, err + } + name := strings.TrimSpace(cal.Name) + if name == "" { + name = path + } + targets = append(targets, Target{ID: path, Name: name}) + } + return out, targets, nil } -func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]string, error) { +func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]caldav.Calendar, error) { principal, err := c.FindCurrentUserPrincipal(ctx) if err != nil { return nil, friendly(fmt.Errorf("no CalDAV account at this address: %w", err)) @@ -150,20 +173,20 @@ func discover(ctx context.Context, c *caldav.Client, u *url.URL) ([]string, erro if err != nil { return nil, friendly(err) } - var paths []string + var out []caldav.Calendar 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) + out = append(out, cal) } } - if len(paths) == 0 { + if len(out) == 0 { return nil, errors.New("the CalDAV account has no event calendars") } - return paths, nil + return out, nil } // limitedClient caps every CalDAV answer. diff --git a/Server/internal/calendar/google.go b/Server/internal/calendar/google.go index 99c0c6e..b5462f1 100644 --- a/Server/internal/calendar/google.go +++ b/Server/internal/calendar/google.go @@ -3,6 +3,7 @@ package calendar import ( + "bytes" "context" "encoding/json" "errors" @@ -11,6 +12,7 @@ import ( "log/slog" "net/http" "net/url" + "slices" "strings" "time" @@ -22,15 +24,25 @@ import ( // ---- Google Calendar ------------------------------------------------------------- // -// People connect a Google account with OAuth (read-only calendar scope). The -// account's secret is its sealed refresh token; every calendar shown in the -// person's Google Calendar list is read through the Calendar API, with -// repeating events expanded by Google (singleEvents). +// People connect a Google account with OAuth: the read-only calendar scope +// to list calendars and read events, and the events scope to add and change +// them. The account's secret is its sealed refresh token; every calendar +// shown in the person's Google Calendar list is read through the Calendar +// API, with repeating events expanded by Google (singleEvents). Accounts +// connected before Docwell wrote to calendars have only the read-only scope +// (can_write false) until they are connected again. // PurposeGoogle names the OAuth state of a Google Calendar sign-in. const PurposeGoogle = "google-calendar" -var googleScopes = []string{"openid", "email", "https://www.googleapis.com/auth/calendar.readonly"} +const googleEventsScope = "https://www.googleapis.com/auth/calendar.events" + +var googleScopes = []string{"openid", "email", "https://www.googleapis.com/auth/calendar.readonly", googleEventsScope} + +// grantsEvents reports whether a token's scopes include writing events. +func grantsEvents(scope string) bool { + return slices.Contains(strings.Fields(scope), googleEventsScope) +} // GoogleEnabled reports whether the server has a Google OAuth app. func (s *Service) GoogleEnabled() bool { return s.google.Enabled() } @@ -86,9 +98,14 @@ func (s *Service) GoogleCallback(ctx context.Context, st oauth.State, code, prov return done(err) } sealed := s.seal(tok.RefreshToken) + // People can leave the events box unticked on Google's consent screen; + // the account then stays read-only. + canWrite := grantsEvents(tok.Scope) for _, r := range rows { if r.Kind == KindGoogle && strings.EqualFold(r.Username, email) { - rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", r.ID, map[string]any{"secret": sealed, "last_error": ""}) + rec, err := pocketbase.Update[record](ctx, s.pb, "calendar_accounts", r.ID, map[string]any{ + "secret": sealed, "last_error": "", "can_write": canWrite, + }) if err != nil { return done(err) } @@ -103,10 +120,10 @@ func (s *Service) GoogleCallback(ctx context.Context, st oauth.State, code, prov if len(rows) >= maxAccounts { return done(fmt.Errorf("you can add at most %d calendars", maxAccounts)) } - next := record{Kind: KindGoogle, URL: "https://calendar.google.com", Username: email, Secret: sealed} + next := record{Kind: KindGoogle, URL: "https://calendar.google.com", Username: email, Secret: sealed, CanWrite: canWrite} body := map[string]any{ "name": "Google · " + email, "kind": KindGoogle, "url": next.URL, "username": email, "secret": sealed, - "color": colors[(len(rows)+6)%len(colors)], "enabled": true, + "color": colors[(len(rows)+6)%len(colors)], "enabled": true, "can_write": canWrite, } _, err = s.add(ctx, st.User, body, next) return done(err) @@ -114,16 +131,38 @@ func (s *Service) GoogleCallback(ctx context.Context, st oauth.State, code, prov // googleGet reads one Calendar API answer into out. func (s *Service) googleGet(ctx context.Context, access, path string, q url.Values, out any) error { + return s.googleDo(ctx, http.MethodGet, access, path, q, nil, "", out) +} + +// googleDo sends one Calendar API request with body in (nil for none) and +// reads the answer into out (nil to drop it). ifMatch, when set, is the ETag +// the change is meant for. For changes, a 412 answer is errStale, 404 and +// 410 errGone. +func (s *Service) googleDo(ctx context.Context, method, access, path string, q url.Values, in any, ifMatch string, out any) error { u := s.googleAPI + path if len(q) > 0 { u += "?" + q.Encode() } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + var reqBody io.Reader + if in != nil { + raw, err := json.Marshal(in) + if err != nil { + return err + } + reqBody = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, u, reqBody) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+access) req.Header.Set("Accept", "application/json") + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + if ifMatch != "" { + req.Header.Set("If-Match", ifMatch) + } res, err := s.client.Do(req) if err != nil { return friendly(err) @@ -133,7 +172,15 @@ func (s *Service) googleGet(ctx context.Context, access, path string, q url.Valu if err != nil { return friendly(err) } - if res.StatusCode != http.StatusOK { + if method != http.MethodGet { + switch res.StatusCode { + case http.StatusPreconditionFailed: + return errStale + case http.StatusNotFound, http.StatusGone: + return errGone + } + } + if res.StatusCode < 200 || res.StatusCode >= 300 { var e struct { Error struct { Message string `json:"message"` @@ -145,6 +192,9 @@ func (s *Service) googleGet(ctx context.Context, access, path string, q url.Valu } return fmt.Errorf("the Google Calendar API answered: %s", e.Error.Message) } + if out == nil || len(body) == 0 { + return nil + } return json.Unmarshal(body, out) } @@ -162,8 +212,8 @@ func (s *Service) googleEmail(ctx context.Context, access string) (string, error } type googleTime struct { - Date string `json:"date"` - DateTime string `json:"dateTime"` + Date string `json:"date,omitempty"` + DateTime string `json:"dateTime,omitempty"` } func (t googleTime) parse() (time.Time, bool, error) { @@ -175,69 +225,110 @@ func (t googleTime) parse() (time.Time, bool, error) { return d.UTC(), false, err } -// googleItems reads the occurrences of every calendar the person shows in -// Google Calendar. -func (s *Service) googleItems(ctx context.Context, r record, from, to time.Time) ([]item, int, error) { +// googleAccess is a fresh access token for a Google account. +func (s *Service) googleAccess(ctx context.Context, r record) (string, error) { refresh, err := s.open(r.Secret) if err != nil { - return nil, 0, err + return "", err } if refresh == "" { - return nil, 0, oauth.ErrRevoked + return "", oauth.ErrRevoked } tok, err := s.google.Refresh(ctx, s.client, refresh, nil) if err != nil { - return nil, 0, err + return "", err + } + return tok.AccessToken, nil +} + +// googleEvent is an event as the Calendar API has it. +type googleEvent struct { + ID string `json:"id"` + ETag string `json:"etag"` + Status string `json:"status"` + Summary string `json:"summary"` + Location string `json:"location"` + HTMLLink string `json:"htmlLink"` + RecurringEventID string `json:"recurringEventId"` + Start googleTime `json:"start"` + End googleTime `json:"end"` +} + +// item is e as stored, from calendar cal; false for a cancelled or +// unreadable event. +func (e googleEvent) item(cal string) (item, bool) { + if e.Status == "cancelled" { + return item{}, false + } + start, allDay, err1 := e.Start.parse() + end, _, err2 := e.End.parse() + if err1 != nil || err2 != nil { + return item{}, false + } + return item{ + key: eventID(cal+"\x00"+e.ID, start), title: e.Summary, location: e.Location, + url: safeLink(e.HTMLLink), allDay: allDay, start: start, end: end, + cal: cal, ref: e.ID, etag: e.ETag, recurring: e.RecurringEventID != "", + }, true +} + +// googleItems reads the occurrences of every calendar the person shows in +// Google Calendar, and lists the ones they may add events to (their primary +// calendar first). +func (s *Service) googleItems(ctx context.Context, r record, from, to time.Time) (reading, error) { + access, err := s.googleAccess(ctx, r) + if err != nil { + return reading{}, err } var list struct { Items []struct { - ID string `json:"id"` - Selected bool `json:"selected"` - Primary bool `json:"primary"` - Hidden bool `json:"hidden"` + ID string `json:"id"` + Summary string `json:"summary"` + Selected bool `json:"selected"` + Primary bool `json:"primary"` + Hidden bool `json:"hidden"` + AccessRole string `json:"accessRole"` } `json:"items"` } - if err := s.googleGet(ctx, tok.AccessToken, "/calendar/v3/users/me/calendarList", url.Values{"minAccessRole": {"reader"}, "maxResults": {"250"}}, &list); err != nil { - return nil, 0, err + if err := s.googleGet(ctx, access, "/calendar/v3/users/me/calendarList", url.Values{"minAccessRole": {"reader"}, "maxResults": {"250"}}, &list); err != nil { + return reading{}, err } var items []item + var targets []Target for _, cal := range list.Items { if cal.Hidden || (!cal.Selected && !cal.Primary) { continue } + writer := cal.AccessRole == "owner" || cal.AccessRole == "writer" + if writer { + t := Target{ID: cal.ID, Name: cal.Summary} + if cal.Primary { + targets = append([]Target{t}, targets...) + } else { + targets = append(targets, t) + } + } q := url.Values{ "singleEvents": {"true"}, "timeMin": {from.Format(time.RFC3339)}, "timeMax": {to.Format(time.RFC3339)}, "maxResults": {"2500"}, "showDeleted": {"false"}, } for pages := 0; pages < 20; pages++ { var res struct { - Items []struct { - ID string `json:"id"` - Status string `json:"status"` - Summary string `json:"summary"` - Location string `json:"location"` - HTMLLink string `json:"htmlLink"` - Start googleTime `json:"start"` - End googleTime `json:"end"` - } `json:"items"` - NextPageToken string `json:"nextPageToken"` + Items []googleEvent `json:"items"` + NextPageToken string `json:"nextPageToken"` } - if err := s.googleGet(ctx, tok.AccessToken, "/calendar/v3/calendars/"+url.PathEscape(cal.ID)+"/events", q, &res); err != nil { - return nil, 0, err + if err := s.googleGet(ctx, access, "/calendar/v3/calendars/"+url.PathEscape(cal.ID)+"/events", q, &res); err != nil { + return reading{}, err } for _, e := range res.Items { - if e.Status == "cancelled" { + it, ok := e.item(cal.ID) + if !ok { continue } - start, allDay, err1 := e.Start.parse() - end, _, err2 := e.End.parse() - if err1 != nil || err2 != nil { - continue + if !writer { + it.ref = "" // Someone else's calendar, shown read-only. } - items = append(items, item{ - key: eventID(cal.ID+"\x00"+e.ID, start), title: e.Summary, location: e.Location, - url: safeLink(e.HTMLLink), allDay: allDay, start: start, end: end, - }) + items = append(items, it) } if res.NextPageToken == "" || len(items) >= maxStored { break @@ -245,5 +336,5 @@ func (s *Service) googleItems(ctx context.Context, r record, from, to time.Time) q.Set("pageToken", res.NextPageToken) } } - return items, len(items), nil + return reading{items: items, count: len(items), targets: targets}, nil } diff --git a/Server/internal/calendar/google_test.go b/Server/internal/calendar/google_test.go index b1b7eed..cb02ddc 100644 --- a/Server/internal/calendar/google_test.go +++ b/Server/internal/calendar/google_test.go @@ -68,10 +68,11 @@ func TestGoogleItems(t *testing.T) { Google: oauth.Provider{Name: "google", ClientID: "c", ClientSecret: "s", AuthURL: g.URL + "/auth", TokenURL: g.URL + "/token"}, }) from, to := window(time.Date(2026, 11, 16, 0, 0, 0, 0, time.UTC)) - items, n, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("refresh-1")}, from, to) + read, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("refresh-1")}, from, to) if err != nil { t.Fatal(err) } + items, n := read.items, read.count if n != 3 || len(items) != 3 { t.Fatalf("items = %+v", items) } @@ -88,7 +89,7 @@ func TestGoogleItems(t *testing.T) { if byTitle["Retro"].location != "Room 1" { t.Errorf("retro = %+v", byTitle["Retro"]) } - if _, _, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("revoked")}, from, to); err == nil || !strings.Contains(err.Error(), "revoked") { + if _, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("revoked")}, from, to); err == nil || !strings.Contains(err.Error(), "revoked") { t.Errorf("revoked token: %v", err) } } @@ -105,7 +106,8 @@ func TestGoogleConnectURL(t *testing.T) { // GoogleConnectURL needs the account list from PocketBase; check the URL parts directly. u, _ := url.Parse(s.google.AuthCodeURL(s.states.Sign(oauth.State{User: "u1", Purpose: PurposeGoogle}), s.googleRedirect(), googleScopes)) q := u.Query() - if q.Get("redirect_uri") != "https://api.example.com/api/v1/oauth/google/callback" || !strings.Contains(q.Get("scope"), "calendar.readonly") { + if q.Get("redirect_uri") != "https://api.example.com/api/v1/oauth/google/callback" || !strings.Contains(q.Get("scope"), "calendar.readonly") || + !strings.Contains(q.Get("scope"), "calendar.events") { t.Errorf("auth url = %s", u) } if st, err := s.states.Verify(q.Get("state"), PurposeGoogle); err != nil || st.User != "u1" { diff --git a/Server/internal/calendar/ics.go b/Server/internal/calendar/ics.go index d408a4c..93b27a0 100644 --- a/Server/internal/calendar/ics.go +++ b/Server/internal/calendar/ics.go @@ -30,6 +30,14 @@ type eventDef struct { cancelled bool set *rrule.Set // nil for an event that does not repeat recurrenceID time.Time + // obj is the CalDAV object the event is in (zero for a feed). + obj objRef +} + +// objRef locates a CalDAV object, so its event can be changed: the calendar +// collection's path, the object's path and its ETag. +type objRef struct { + cal, path, etag string } // feed is a parsed calendar: its events by UID, with each repeating event's @@ -139,6 +147,11 @@ func parseFeed(r io.Reader, loc *time.Location) (*feed, error) { } func (f *feed) add(cal *ical.Calendar, loc *time.Location) error { + return f.addObject(cal, loc, objRef{}) +} + +// addObject is add for the VCALENDAR of one CalDAV object. +func (f *feed) addObject(cal *ical.Calendar, loc *time.Location, obj objRef) error { z := &zones{defs: map[string]*ical.Component{}, seen: map[string]*time.Location{}} for _, c := range cal.Children { if c.Name == ical.CompTimezone { @@ -155,6 +168,7 @@ func (f *feed) add(cal *ical.Calendar, loc *time.Location) error { if err != nil { continue // One broken event does not hide the rest. } + e.obj = obj if !e.recurrenceID.IsZero() { if f.overrides[e.uid] == nil { f.overrides[e.uid] = map[int64]*eventDef{} diff --git a/Server/internal/calendar/write.go b/Server/internal/calendar/write.go new file mode 100644 index 0000000..c6ea3c2 --- /dev/null +++ b/Server/internal/calendar/write.go @@ -0,0 +1,610 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/emersion/go-ical" + "github.com/emersion/go-webdav" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Writing events (ADR-19) ----------------------------------------------------- +// +// A change goes to the source at once: a CalDAV PUT or DELETE, or a Google +// Calendar API call, with If-Match set to the ETag the last sync read. When +// the event changed elsewhere since, the source refuses (412), Docwell keeps +// what is there, reads the account again and tells the person. Only single +// events are changed; occurrences of repeating events are left to the +// calendar's own app. The stored copy is updated straight after a write, so +// the journal shows the change without waiting for the next sync. + +var ( + // errStale: the event changed at the source since it was read. + errStale = errors.New("calendar: event changed at the source") + // errGone: the event is no longer at the source. + errGone = errors.New("calendar: event no longer at the source") +) + +const ( + maxTitle = 500 + maxLocation = 500 + // maxSpan caps how long one event may last. + maxSpan = 366 * 24 * time.Hour +) + +// EventInput adds an event (Calendar, Title and Start required) or changes +// the fields that are set. Start and End are RFC 3339 times, or dates +// (YYYY-MM-DD, End exclusive) when AllDay is set. A missing End is an hour +// after Start, or the next day for all-day events. +type EventInput struct { + Calendar *string `json:"calendar"` + Title *string `json:"title"` + Location *string `json:"location"` + Start *string `json:"start"` + End *string `json:"end"` + AllDay *bool `json:"allDay"` +} + +var ( + errStaleMsg = apperr.Conflict("This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.") + errGoneMsg = apperr.NotFound("This event is no longer in its calendar.") +) + +// apply checks in and writes it over it (the event as it is, zero for a new one). +func (in EventInput) apply(it *item) error { + if in.Title != nil { + t := strings.TrimSpace(*in.Title) + if t == "" || utf8.RuneCountInString(t) > maxTitle { + return apperr.InvalidFields(map[string]string{"title": fmt.Sprintf("Give the event a title of at most %d characters.", maxTitle)}) + } + it.title = t + } + if in.Location != nil { + l := strings.TrimSpace(*in.Location) + if utf8.RuneCountInString(l) > maxLocation { + return apperr.InvalidFields(map[string]string{"location": fmt.Sprintf("The place can have at most %d characters.", maxLocation)}) + } + it.location = l + } + if in.AllDay == nil && in.Start == nil && in.End == nil { + return nil + } + allDay := it.allDay + if in.AllDay != nil { + allDay = *in.AllDay + } + if in.Start == nil && allDay != it.allDay { + return apperr.InvalidFields(map[string]string{"start": "Give the start when switching between all-day and timed."}) + } + start, end := it.start, it.end + parse := func(v string) (time.Time, error) { + if allDay { + return time.Parse(time.DateOnly, v) + } + t, err := time.Parse(time.RFC3339, v) + return t.UTC(), err + } + if in.Start != nil { + t, err := parse(*in.Start) + if err != nil { + if allDay { + return apperr.InvalidFields(map[string]string{"start": "All-day events start on a date like 2026-11-17."}) + } + return apperr.InvalidFields(map[string]string{"start": "Give the start as a time like 2026-11-17T09:00:00+01:00."}) + } + // A moved start keeps the event's length unless End is given too. + length := end.Sub(start) + start = t + if in.End == nil { + if length <= 0 || in.AllDay != nil && *in.AllDay != it.allDay { + length = time.Hour + if allDay { + length = 24 * time.Hour + } + } + end = start.Add(length) + } + } + if in.End != nil { + t, err := parse(*in.End) + if err != nil { + return apperr.InvalidFields(map[string]string{"end": "The end is written like the start."}) + } + end = t + } + if !end.After(start) { + return apperr.InvalidFields(map[string]string{"end": "The event has to end after it starts."}) + } + if end.Sub(start) > maxSpan { + return apperr.InvalidFields(map[string]string{"end": "An event can last at most a year."}) + } + it.start, it.end, it.allDay = start, end, allDay + return nil +} + +// findEvent is the caller's stored event id with its account. +func (s *Service) findEvent(ctx context.Context, c access.Caller, id string) (eventRecord, record, error) { + if err := signedIn(c); err != nil { + return eventRecord{}, record{}, err + } + if _, err := hex.DecodeString(id); err != nil || len(id) != 16 { + return eventRecord{}, record{}, apperr.NotFound("event not found") + } + res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("user = '%s' && key = '%s'", c.ID, id), + }) + if err != nil { + return eventRecord{}, record{}, err + } + if len(res.Items) == 0 { + return eventRecord{}, record{}, apperr.NotFound("event not found") + } + e := res.Items[0] + acc, err := s.get(ctx, c, e.Account) + if err != nil { + return eventRecord{}, record{}, err + } + return e, acc, nil +} + +// cannotWrite says why events of acc cannot be added or changed. +func cannotWrite(acc record) error { + switch { + case acc.Kind == KindICS: + return apperr.Invalid("Events of a subscribed feed are changed where the feed comes from.") + case acc.Kind == KindGoogle && !acc.CanWrite: + return apperr.Invalid("Connect the Google account again and allow Docwell to manage events, then try again.") + case !acc.Enabled: + return apperr.Invalid("Turn the calendar on first.") + default: + return apperr.Invalid("This calendar cannot be written to.") + } +} + +// stored reads back an event record as an item. +func (e eventRecord) item() item { + st, _ := parsePB(e.StartAt) + en, _ := parsePB(e.EndAt) + return item{ + key: e.Key, title: e.Title, location: e.Location, url: e.URL, allDay: e.AllDay, start: st, end: en, + cal: e.Cal, ref: e.Ref, etag: e.ETag, recurring: e.Recurring, + } +} + +func (it item) event(acc record) Event { + e := eventRecord{ + Key: it.key, Account: acc.ID, Title: it.title, Location: it.location, URL: it.url, AllDay: it.allDay, + Ref: it.ref, Recurring: it.recurring, + } + return e.view(acc.Color, acc.writable(), it.start, it.end) +} + +// resync reads acc again in the background, after the source surprised us. +func (s *Service) resync(acc record) { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + if err := s.Sync(ctx, acc); err != nil { + slog.Debug("calendar resync failed", "calendar", acc.ID, "err", err) + } + }() +} + +// writeError turns a source's refusal into what the person is told. +func (s *Service) writeError(acc record, e *eventRecord, err error) error { + switch { + case errors.Is(err, errStale): + s.resync(acc) + return errStaleMsg + case errors.Is(err, errGone): + if e != nil { + _ = s.pb.Delete(context.Background(), "calendar_events", e.ID) + } + s.resync(acc) + return errGoneMsg + } + return apperr.Invalid(err.Error()) +} + +// CreateEvent adds an event to one of the caller's calendars (the +// account's chosen calendar within it). +func (s *Service) CreateEvent(ctx context.Context, c access.Caller, in EventInput) (Event, error) { + if err := signedIn(c); err != nil { + return Event{}, err + } + if in.Calendar == nil || in.Title == nil || in.Start == nil { + return Event{}, apperr.InvalidFields(map[string]string{"title": "Calendar, title and start are required."}) + } + acc, err := s.get(ctx, c, *in.Calendar) + if err != nil { + return Event{}, err + } + if !acc.writable() { + return Event{}, cannotWrite(acc) + } + var it item + if err := in.apply(&it); err != nil { + return Event{}, err + } + it.cal = acc.target() + if acc.Kind == KindGoogle { + err = s.googleCreate(ctx, acc, &it) + } else { + err = s.davCreate(ctx, acc, &it) + } + if err != nil { + return Event{}, s.writeError(acc, nil, err) + } + body := it.body() + body["account"], body["user"], body["key"] = acc.ID, acc.User, it.key + if _, err := pocketbase.Create[eventRecord](ctx, s.pb, "calendar_events", body); err != nil { + // It is in the calendar; the next sync stores it. + slog.Warn("new calendar event not stored", "calendar", acc.ID, "err", err) + } + return it.event(acc), nil +} + +// UpdateEvent changes a single event at its source. +func (s *Service) UpdateEvent(ctx context.Context, c access.Caller, id string, in EventInput) (Event, error) { + e, acc, err := s.findEvent(ctx, c, id) + if err != nil { + return Event{}, err + } + if in.Calendar != nil && *in.Calendar != acc.ID { + return Event{}, apperr.InvalidFields(map[string]string{"calendar": "An event cannot move to another calendar account."}) + } + if !acc.writable() || e.Ref == "" { + return Event{}, cannotWrite(acc) + } + if e.Recurring { + return Event{}, apperr.Invalid("Repeating events are changed in their own calendar app.") + } + it := e.item() + if err := in.apply(&it); err != nil { + return Event{}, err + } + if acc.Kind == KindGoogle { + err = s.googleUpdate(ctx, acc, &it) + } else { + err = s.davUpdate(ctx, acc, &it) + } + if err != nil { + return Event{}, s.writeError(acc, &e, err) + } + body := it.body() + body["key"] = it.key + if _, err := pocketbase.Update[eventRecord](ctx, s.pb, "calendar_events", e.ID, body); err != nil { + slog.Warn("changed calendar event not stored", "calendar", acc.ID, "err", err) + s.resync(acc) + } + return it.event(acc), nil +} + +// DeleteEvent removes a single event from its source. +func (s *Service) DeleteEvent(ctx context.Context, c access.Caller, id string) error { + e, acc, err := s.findEvent(ctx, c, id) + if err != nil { + return err + } + if !acc.writable() || e.Ref == "" { + return cannotWrite(acc) + } + if e.Recurring { + return apperr.Invalid("Repeating events are changed in their own calendar app.") + } + it := e.item() + if acc.Kind == KindGoogle { + err = s.googleDelete(ctx, acc, it) + } else { + err = s.davDelete(ctx, acc, it) + } + if err != nil && !errors.Is(err, errGone) { + return s.writeError(acc, &e, err) + } + if err := s.pb.Delete(ctx, "calendar_events", e.ID); err != nil && !pocketbase.IsNotFound(err) { + return err + } + return nil +} + +// ---- CalDAV ----------------------------------------------------------------------- + +func (s *Service) davBase(acc record) (webdav.HTTPClient, *url.URL, error) { + password, err := s.open(acc.Secret) + if err != nil { + return nil, nil, err + } + u, err := feedURL(acc.URL) + if err != nil { + return nil, nil, err + } + return davClient(s.client, source{kind: acc.Kind, url: acc.URL, username: acc.Username, password: password}), u, nil +} + +// davURL resolves a path on the account's server. +func davURL(base *url.URL, path string) string { + return base.ResolveReference(&url.URL{Path: path}).String() +} + +// quoteETag writes an ETag as a header wants it; unquoteETag reads one back. +func quoteETag(etag string) string { return strconv.Quote(etag) } + +func unquoteETag(h string) string { + h = strings.TrimPrefix(strings.TrimSpace(h), "W/") + if v, err := strconv.Unquote(h); err == nil { + return v + } + return h +} + +// davSend sends one request; status 412 is errStale, 404 and 410 errGone. +func davSend(ctx context.Context, hc webdav.HTTPClient, method, u string, body []byte, headers map[string]string) (*http.Response, error) { + var r io.Reader + if body != nil { + r = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, u, r) + if err != nil { + return nil, err + } + for k, v := range headers { + req.Header.Set(k, v) + } + res, err := hc.Do(req) + if err != nil { + return nil, friendly(err) + } + switch { + case res.StatusCode == http.StatusPreconditionFailed: + _ = res.Body.Close() + return nil, errStale + case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusGone: + _ = res.Body.Close() + return nil, errGone + case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden: + _ = res.Body.Close() + return nil, errors.New("the calendar did not let Docwell change it") + case res.StatusCode >= 300: + _ = res.Body.Close() + return nil, fmt.Errorf("the calendar answered %s", res.Status) + } + return res, nil +} + +// davPut stores cal at u under the given condition and returns the new ETag +// (read back with a GET when the server does not send it). +func davPut(ctx context.Context, hc webdav.HTTPClient, u string, cal *ical.Calendar, condition map[string]string) (string, error) { + var buf bytes.Buffer + if err := ical.NewEncoder(&buf).Encode(cal); err != nil { + return "", err + } + headers := map[string]string{"Content-Type": ical.MIMEType + "; charset=utf-8"} + for k, v := range condition { + headers[k] = v + } + res, err := davSend(ctx, hc, http.MethodPut, u, buf.Bytes(), headers) + if err != nil { + return "", err + } + _ = res.Body.Close() + if etag := res.Header.Get("ETag"); etag != "" { + return unquoteETag(etag), nil + } + _, etag, err := davGet(ctx, hc, u) + return etag, err +} + +// davGet reads one calendar object and its ETag. +func davGet(ctx context.Context, hc webdav.HTTPClient, u string) (*ical.Calendar, string, error) { + res, err := davSend(ctx, hc, http.MethodGet, u, nil, map[string]string{"Accept": ical.MIMEType}) + if err != nil { + return nil, "", err + } + defer func() { _ = res.Body.Close() }() + cal, err := ical.NewDecoder(res.Body).Decode() + if err != nil { + return nil, "", fmt.Errorf("the calendar sent an event Docwell cannot read: %w", err) + } + return cal, unquoteETag(res.Header.Get("ETag")), nil +} + +// setTimes writes it's times and texts onto a VEVENT. +func setTimes(ev *ical.Component, it item) { + ev.Props.SetText(ical.PropSummary, it.title) + if it.location != "" { + ev.Props.SetText(ical.PropLocation, it.location) + } else { + ev.Props.Del(ical.PropLocation) + } + ev.Props.Del(ical.PropDuration) + if it.allDay { + ev.Props.SetDate(ical.PropDateTimeStart, it.start) + ev.Props.SetDate(ical.PropDateTimeEnd, it.end) + } else { + ev.Props.SetDateTime(ical.PropDateTimeStart, it.start.UTC()) + ev.Props.SetDateTime(ical.PropDateTimeEnd, it.end.UTC()) + } + now := time.Now().UTC() + ev.Props.SetDateTime(ical.PropDateTimeStamp, now) + ev.Props.SetDateTime(ical.PropLastModified, now) +} + +func newUID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) + "@docwell" +} + +func (s *Service) davCreate(ctx context.Context, acc record, it *item) error { + hc, base, err := s.davBase(acc) + if err != nil { + return err + } + uid := newUID() + ev := ical.NewEvent() + ev.Props.SetText(ical.PropUID, uid) + setTimes(ev.Component, *it) + cal := ical.NewCalendar() + cal.Props.SetText(ical.PropVersion, "2.0") + cal.Props.SetText(ical.PropProductID, "-//Docwell//Calendar//EN") + cal.Children = append(cal.Children, ev.Component) + path := strings.TrimSuffix(it.cal, "/") + "/" + uid + ".ics" + etag, err := davPut(ctx, hc, davURL(base, path), cal, map[string]string{"If-None-Match": "*"}) + if err != nil { + if errors.Is(err, errGone) { + return errors.New("the calendar Docwell writes to is gone; pick another in account settings") + } + return err + } + it.ref, it.etag, it.key = path, etag, eventID(uid, it.start) + return nil +} + +// davEvent is the one VEVENT of a single event's object. +func davEvent(cal *ical.Calendar) (*ical.Component, error) { + var found *ical.Component + for _, c := range cal.Children { + if c.Name != ical.CompEvent { + continue + } + if found != nil || c.Props.Get(ical.PropRecurrenceID) != nil || c.Props.Get(ical.PropRecurrenceRule) != nil || + c.Props.Get(ical.PropRecurrenceDates) != nil { + return nil, errors.New("this is a repeating event; change it in its own calendar app") + } + found = c + } + if found == nil { + return nil, errGone + } + return found, nil +} + +func (s *Service) davUpdate(ctx context.Context, acc record, it *item) error { + hc, base, err := s.davBase(acc) + if err != nil { + return err + } + u := davURL(base, it.ref) + cal, _, err := davGet(ctx, hc, u) + if err != nil { + return err + } + ev, err := davEvent(cal) + if err != nil { + return err + } + setTimes(ev, *it) + seq := 0 + if p := ev.Props.Get(ical.PropSequence); p != nil { + seq, _ = p.Int() + } + sp := ical.NewProp(ical.PropSequence) + sp.Value = strconv.Itoa(seq + 1) + ev.Props.Set(sp) + // The ETag of the last sync, not of the GET: a change made since then + // is refused even if it came in between. + etag, err := davPut(ctx, hc, u, cal, map[string]string{"If-Match": quoteETag(it.etag)}) + if err != nil { + return err + } + it.etag = etag + it.key = eventID(propText(ev, ical.PropUID), it.start) + return nil +} + +func (s *Service) davDelete(ctx context.Context, acc record, it item) error { + hc, base, err := s.davBase(acc) + if err != nil { + return err + } + res, err := davSend(ctx, hc, http.MethodDelete, davURL(base, it.ref), nil, map[string]string{"If-Match": quoteETag(it.etag)}) + if err != nil { + return err + } + return res.Body.Close() +} + +// ---- Google ----------------------------------------------------------------------- + +// googleBody is it as the Calendar API takes it. +func googleBody(it item) map[string]any { + when := func(t time.Time) googleTime { + if it.allDay { + return googleTime{Date: t.Format(time.DateOnly)} + } + return googleTime{DateTime: t.UTC().Format(time.RFC3339)} + } + return map[string]any{ + "summary": it.title, "location": it.location, "start": when(it.start), "end": when(it.end), + } +} + +func googleEventPath(cal, id string) string { + p := "/calendar/v3/calendars/" + url.PathEscape(cal) + "/events" + if id != "" { + p += "/" + url.PathEscape(id) + } + return p +} + +// fromGoogle copies what Google stored back into it. +func fromGoogle(it *item, cal string, e googleEvent) { + if got, ok := e.item(cal); ok { + *it = got + } +} + +func (s *Service) googleCreate(ctx context.Context, acc record, it *item) error { + access, err := s.googleAccess(ctx, acc) + if err != nil { + return err + } + var e googleEvent + if err := s.googleDo(ctx, http.MethodPost, access, googleEventPath(it.cal, ""), nil, googleBody(*it), "", &e); err != nil { + if errors.Is(err, errGone) { + return errors.New("the calendar Docwell writes to is gone; pick another in account settings") + } + return err + } + fromGoogle(it, it.cal, e) + return nil +} + +func (s *Service) googleUpdate(ctx context.Context, acc record, it *item) error { + access, err := s.googleAccess(ctx, acc) + if err != nil { + return err + } + var e googleEvent + if err := s.googleDo(ctx, http.MethodPatch, access, googleEventPath(it.cal, it.ref), nil, googleBody(*it), it.etag, &e); err != nil { + return err + } + fromGoogle(it, it.cal, e) + return nil +} + +func (s *Service) googleDelete(ctx context.Context, acc record, it item) error { + access, err := s.googleAccess(ctx, acc) + if err != nil { + return err + } + return s.googleDo(ctx, http.MethodDelete, access, googleEventPath(it.cal, it.ref), nil, nil, it.etag, nil) +} diff --git a/Server/internal/calendar/write_test.go b/Server/internal/calendar/write_test.go new file mode 100644 index 0000000..5849106 --- /dev/null +++ b/Server/internal/calendar/write_test.go @@ -0,0 +1,514 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package calendar + +import ( + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strconv" + "strings" + "sync" + "testing" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/oauth" + "docwell/server/internal/store/pocketbase" +) + +// fakeStore is an in-memory PocketBase for the two calendar collections. +// Filters are read as "field = 'value'" pairs joined by &&; anything else +// in a filter is ignored. +type fakeStore struct { + mu sync.Mutex + next int + rows map[string]map[string]map[string]any // collection -> id -> record +} + +var filterPair = regexp.MustCompile(`(\w+) = '([^']*)'`) + +func newFakeStore(t *testing.T) (*fakeStore, *pocketbase.Client) { + t.Helper() + f := &fakeStore{rows: map[string]map[string]map[string]any{}} + mux := http.NewServeMux() + reply := func(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) + } + mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) { + reply(w, 200, map[string]string{"token": "su"}) + }) + mux.HandleFunc("GET /api/collections/{c}/records", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + want := map[string]string{} + filter := r.URL.Query().Get("filter") + if !strings.Contains(filter, "||") { + for _, m := range filterPair.FindAllStringSubmatch(filter, -1) { + want[m[1]] = m[2] + } + } else if m := filterPair.FindStringSubmatch(filter); m != nil && m[1] == "user" { + want["user"] = m[2] + } + items := []map[string]any{} + for _, rec := range f.rows[r.PathValue("c")] { + ok := true + for k, v := range want { + ok = ok && fmt.Sprint(rec[k]) == v + } + if ok { + items = append(items, rec) + } + } + reply(w, 200, map[string]any{"page": 1, "perPage": len(items), "totalPages": 1, "totalItems": len(items), "items": items}) + }) + mux.HandleFunc("POST /api/collections/{c}/records", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + reply(w, 200, f.put(r.PathValue("c"), "", body)) + }) + mux.HandleFunc("GET /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { + if rec := f.get(r.PathValue("c"), r.PathValue("id")); rec != nil { + reply(w, 200, rec) + return + } + reply(w, 404, map[string]any{"status": 404, "message": "not found"}) + }) + mux.HandleFunc("PATCH /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + reply(w, 200, f.put(r.PathValue("c"), r.PathValue("id"), body)) + }) + mux.HandleFunc("DELETE /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + delete(f.rows[r.PathValue("c")], r.PathValue("id")) + f.mu.Unlock() + w.WriteHeader(204) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return f, pocketbase.New(srv.URL, "su@test", "pw") +} + +func (f *fakeStore) put(c, id string, body map[string]any) map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + if f.rows[c] == nil { + f.rows[c] = map[string]map[string]any{} + } + rec := f.rows[c][id] + if rec == nil { + f.next++ + id = fmt.Sprintf("r%014d", f.next) + rec = map[string]any{"id": id} + f.rows[c][id] = rec + } + for k, v := range body { + rec[k] = v + } + return rec +} + +func (f *fakeStore) get(c, id string) map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + return f.rows[c][id] +} + +func (f *fakeStore) count(c string) int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.rows[c]) +} + +// fakeDAV is a CalDAV calendar at /cal/ that keeps objects with ETags and +// honours If-Match and If-None-Match. +type fakeDAV struct { + mu sync.Mutex + objects map[string]string // path -> iCalendar + etags map[string]int + puts []string // "path If-Match If-None-Match" +} + +func newFakeDAV(t *testing.T) (*fakeDAV, *httptest.Server) { + d := &fakeDAV{objects: map[string]string{}, etags: map[string]int{}} + srv := httptest.NewServer(http.HandlerFunc(d.serve)) + t.Cleanup(srv.Close) + return d, srv +} + +func (d *fakeDAV) set(path, data string) { + d.mu.Lock() + defer d.mu.Unlock() + data = strings.ReplaceAll(strings.TrimSpace(data), "\r\n", "\n") + d.objects[path] = strings.ReplaceAll(data, "\n", "\r\n") + "\r\n" + d.etags[path]++ +} + +func (d *fakeDAV) etag(path string) string { return `"` + strconv.Itoa(d.etags[path]) + `"` } + +func (d *fakeDAV) serve(w http.ResponseWriter, r *http.Request) { + d.mu.Lock() + defer d.mu.Unlock() + if u, p, ok := r.BasicAuth(); !ok || u != "ann" || p != "pw" { + w.WriteHeader(http.StatusUnauthorized) + return + } + path := r.URL.Path + _, exists := d.objects[path] + switch r.Method { + case "REPORT": + var b strings.Builder + b.WriteString(``) + for p, data := range d.objects { + var esc strings.Builder + _ = xml.EscapeText(&esc, []byte(data)) + fmt.Fprintf(&b, `%s%s%sHTTP/1.1 200 OK`, + p, strings.ReplaceAll(d.etag(p), `"`, """), esc.String()) + } + b.WriteString(``) + w.Header().Set("Content-Type", "application/xml; charset=utf-8") + w.WriteHeader(http.StatusMultiStatus) + _, _ = io.WriteString(w, b.String()) + case http.MethodGet: + if !exists { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/calendar") + w.Header().Set("ETag", d.etag(path)) + _, _ = io.WriteString(w, d.objects[path]) + case http.MethodPut: + d.puts = append(d.puts, path+" "+r.Header.Get("If-Match")+" "+r.Header.Get("If-None-Match")) + if m := r.Header.Get("If-Match"); m != "" && (!exists || m != d.etag(path)) { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + if r.Header.Get("If-None-Match") == "*" && exists { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + data, _ := io.ReadAll(r.Body) + d.objects[path] = string(data) + d.etags[path]++ + w.Header().Set("ETag", d.etag(path)) + w.WriteHeader(http.StatusCreated) + case http.MethodDelete: + if !exists { + http.NotFound(w, r) + return + } + if m := r.Header.Get("If-Match"); m != "" && m != d.etag(path) { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + delete(d.objects, path) + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func eventByTitle(t *testing.T, events []Event, title string) Event { + t.Helper() + for _, e := range events { + if e.Title == title { + return e + } + } + t.Fatalf("no event %q in %+v", title, events) + return Event{} +} + +func isKind(err error, kind apperr.Kind) bool { + e, ok := apperr.As(err) + return ok && e.Kind == kind +} + +func ptr[T any](v T) *T { return &v } + +func TestCalDAVWrites(t *testing.T) { + store, pb := newFakeStore(t) + dav, srv := newFakeDAV(t) + day := time.Now().UTC().AddDate(0, 0, 3).Format("20060102") + dav.set("/cal/single.ics", `BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//test//EN +BEGIN:VEVENT +UID:single-1 +DTSTAMP:20260101T000000Z +DTSTART;TZID=Europe/Warsaw:`+day+`T090000 +DTEND;TZID=Europe/Warsaw:`+day+`T100000 +SUMMARY:Planning +X-KEEP:yes +END:VEVENT +END:VCALENDAR`) + dav.set("/cal/weekly.ics", `BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//test//EN +BEGIN:VEVENT +UID:weekly-1 +DTSTAMP:20260101T000000Z +DTSTART:`+day+`T120000Z +DTEND:`+day+`T123000Z +RRULE:FREQ=WEEKLY;COUNT=3 +SUMMARY:Standup +END:VEVENT +END:VCALENDAR`) + + s := New(pb, Options{Secret: "x", Client: srv.Client()}) + ctx := context.Background() + c := access.Caller{ID: "u1"} + acc := store.put("calendar_accounts", "", map[string]any{ + "user": "u1", "name": "Work", "kind": KindCalDAV, "url": srv.URL + "/cal/", "username": "ann", + "secret": s.seal("pw"), "color": "blue", "enabled": true, + }) + rec, err := s.get(ctx, c, acc["id"].(string)) + if err != nil { + t.Fatal(err) + } + if err := s.Sync(ctx, rec); err != nil { + t.Fatal(err) + } + if rec, _ = s.get(ctx, c, rec.ID); !rec.CanWrite || rec.target() != "/cal/" { + t.Fatalf("after sync: canWrite %v, targets %+v", rec.CanWrite, rec.Targets) + } + + date := time.Now().UTC().AddDate(0, 0, 3).Format(time.DateOnly) + events, err := s.Events(ctx, c, date, date, "Europe/Warsaw") + if err != nil { + t.Fatal(err) + } + planning, standup := eventByTitle(t, events, "Planning"), eventByTitle(t, events, "Standup") + if !planning.Editable || standup.Editable { + t.Fatalf("editable: planning %v, standup %v", planning.Editable, standup.Editable) + } + + // A change goes to the server with the ETag the sync read, and keeps + // what Docwell does not know about (X-KEEP). + got, err := s.UpdateEvent(ctx, c, planning.ID, EventInput{Title: ptr("Planning (moved)"), Location: ptr("Room 2")}) + if err != nil { + t.Fatal(err) + } + if got.Title != "Planning (moved)" || got.Location != "Room 2" || got.Start != planning.Start { + t.Fatalf("updated = %+v", got) + } + if last := dav.puts[len(dav.puts)-1]; last != `/cal/single.ics "1" ` { + t.Fatalf("put = %q", last) + } + body := dav.objects["/cal/single.ics"] + if !strings.Contains(body, "SUMMARY:Planning (moved)") || !strings.Contains(body, "X-KEEP:yes") || !strings.Contains(body, "SEQUENCE:1") { + t.Fatalf("stored object:\n%s", body) + } + + // Moving it changes its id; the old one is gone. + newStart := time.Now().UTC().AddDate(0, 0, 3).Truncate(time.Hour).Add(2 * time.Hour) + moved, err := s.UpdateEvent(ctx, c, got.ID, EventInput{Start: ptr(newStart.Format(time.RFC3339))}) + if err != nil { + t.Fatal(err) + } + if moved.ID == got.ID || moved.Start != newStart.Format(time.RFC3339) || moved.End != newStart.Add(time.Hour).Format(time.RFC3339) { + t.Fatalf("moved = %+v (was %+v)", moved, got) + } + + // Changed elsewhere since: refused, nothing overwritten. + dav.set("/cal/single.ics", strings.ReplaceAll(dav.objects["/cal/single.ics"], "Planning (moved)", "Changed on the phone")) + if _, err := s.UpdateEvent(ctx, c, moved.ID, EventInput{Title: ptr("Mine")}); !isKind(err, apperr.KindConflict) { + t.Fatalf("stale update: %v", err) + } + if !strings.Contains(dav.objects["/cal/single.ics"], "Changed on the phone") { + t.Fatal("a stale change overwrote the calendar") + } + if err := s.DeleteEvent(ctx, c, moved.ID); !isKind(err, apperr.KindConflict) { + t.Fatalf("stale delete: %v", err) + } + + // Repeating events are left alone. + if _, err := s.UpdateEvent(ctx, c, standup.ID, EventInput{Title: ptr("x")}); !isKind(err, apperr.KindInvalid) { + t.Fatalf("repeating update: %v", err) + } + + // New events: all-day, into the account's calendar, never over an existing object. + before := store.count("calendar_events") + added, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(rec.ID), Title: ptr("Holiday"), Start: ptr(date), AllDay: ptr(true)}) + if err != nil { + t.Fatal(err) + } + if !added.AllDay || added.Start != date || !added.Editable || store.count("calendar_events") != before+1 { + t.Fatalf("added = %+v", added) + } + var path string + for p, data := range dav.objects { + if strings.Contains(data, "SUMMARY:Holiday") { + path = p + if !strings.Contains(data, "DTSTART;VALUE=DATE:") { + t.Errorf("all-day start not a date:\n%s", data) + } + } + } + if !strings.HasPrefix(path, "/cal/") || !strings.HasSuffix(path, "@docwell.ics") { + t.Fatalf("new object at %q", path) + } + if last := dav.puts[len(dav.puts)-1]; !strings.HasSuffix(last, " *") { + t.Fatalf("create put = %q", last) + } + if err := s.DeleteEvent(ctx, c, added.ID); err != nil { + t.Fatal(err) + } + if _, ok := dav.objects[path]; ok || store.count("calendar_events") != before { + t.Fatal("deleted event still there") + } + + // Input checks. + for name, in := range map[string]EventInput{ + "no title": {Calendar: ptr(rec.ID), Title: ptr(" "), Start: ptr(date), AllDay: ptr(true)}, + "bad start": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("tomorrow")}, + "end first": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("2026-11-17T10:00:00Z"), End: ptr("2026-11-17T09:00:00Z")}, + "too long": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("2026-11-17"), End: ptr("2028-11-17"), AllDay: ptr(true)}, + "not a target": {Calendar: ptr("nope"), Title: ptr("x"), Start: ptr("2026-11-17"), AllDay: ptr(true)}, + } { + if _, err := s.CreateEvent(ctx, c, in); err == nil { + t.Errorf("%s: accepted", name) + } + } + // Someone else's event. + if err := s.DeleteEvent(ctx, access.Caller{ID: "u2"}, standup.ID); !isKind(err, apperr.KindNotFound) { + t.Errorf("other user: %v", err) + } +} + +func TestGoogleWrites(t *testing.T) { + store, pb := newFakeStore(t) + var mu sync.Mutex + etag := `"g1"` + var calls []string + mux := http.NewServeMux() + mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"access_token":"access-1","expires_in":3600}`)) + }) + mux.HandleFunc("POST /calendar/v3/calendars/{cal}/events", func(w http.ResponseWriter, r *http.Request) { + var in map[string]any + _ = json.NewDecoder(r.Body).Decode(&in) + mu.Lock() + calls = append(calls, "POST "+r.PathValue("cal")) + mu.Unlock() + out := map[string]any{"id": "new1", "etag": `"n1"`, "summary": in["summary"], "location": in["location"], "start": in["start"], "end": in["end"], "htmlLink": "https://calendar.google.com/new1"} + _ = json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("PATCH /calendar/v3/calendars/{cal}/events/{id}", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + calls = append(calls, "PATCH "+r.PathValue("id")+" "+r.Header.Get("If-Match")) + if r.Header.Get("If-Match") != etag { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + var in map[string]any + _ = json.NewDecoder(r.Body).Decode(&in) + etag = `"g2"` + _ = json.NewEncoder(w).Encode(map[string]any{"id": r.PathValue("id"), "etag": etag, "summary": in["summary"], "start": in["start"], "end": in["end"]}) + }) + mux.HandleFunc("DELETE /calendar/v3/calendars/{cal}/events/{id}", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + calls = append(calls, "DELETE "+r.PathValue("id")+" "+r.Header.Get("If-Match")) + w.WriteHeader(http.StatusNoContent) + }) + g := httptest.NewServer(mux) + defer g.Close() + + s := New(pb, Options{ + Secret: "x", Client: g.Client(), GoogleAPI: g.URL, + Google: oauth.Provider{Name: "google", ClientID: "c", ClientSecret: "s", TokenURL: g.URL + "/token"}, + }) + ctx := context.Background() + c := access.Caller{ID: "u1"} + acc := store.put("calendar_accounts", "", map[string]any{ + "user": "u1", "name": "Google", "kind": KindGoogle, "url": "https://calendar.google.com", "username": "me@example.com", + "secret": s.seal("refresh-1"), "color": "green", "enabled": true, "can_write": false, + "targets": []Target{{ID: "me@example.com", Name: "Me"}}, + }) + id := acc["id"].(string) + + // Connected before writing existed: the person is asked to reconnect. + _, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(id), Title: ptr("Lunch"), Start: ptr("2026-11-20T12:00:00Z")}) + if err == nil || !strings.Contains(err.Error(), "Connect the Google account again") { + t.Fatalf("read-only account: %v", err) + } + if v, _ := s.List(ctx, c); !v[0].NeedsReconnect || v[0].CanWrite { + t.Fatalf("account view = %+v", v[0]) + } + store.put("calendar_accounts", id, map[string]any{"can_write": true}) + + added, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(id), Title: ptr("Lunch"), Start: ptr("2026-11-20T12:00:00Z")}) + if err != nil { + t.Fatal(err) + } + if added.End != "2026-11-20T13:00:00Z" || added.URL == "" || !added.Editable { + t.Fatalf("added = %+v", added) + } + + // Pretend the sync read the event with ETag g1. + for _, rec := range store.rows["calendar_events"] { + rec["etag"] = `"g1"` + } + changed, err := s.UpdateEvent(ctx, c, added.ID, EventInput{Title: ptr("Long lunch")}) + if err != nil { + t.Fatal(err) + } + if changed.Title != "Long lunch" { + t.Fatalf("changed = %+v", changed) + } + // The stored ETag is now g2; Google moving on to g3 makes the next change stale. + mu.Lock() + etag = `"g3"` + mu.Unlock() + if _, err := s.UpdateEvent(ctx, c, changed.ID, EventInput{Title: ptr("x")}); !isKind(err, apperr.KindConflict) { + t.Fatalf("stale: %v", err) + } + if err := s.DeleteEvent(ctx, c, changed.ID); err != nil { + t.Fatal(err) + } + want := []string{"POST me@example.com", `PATCH new1 "g1"`, `PATCH new1 "g2"`, `DELETE new1 "g2"`} + if strings.Join(calls, "|") != strings.Join(want, "|") { + t.Fatalf("calls = %q\nwant %q", calls, want) + } +} + +func TestGrantsEvents(t *testing.T) { + if !grantsEvents("openid email https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events") { + t.Error("events scope not seen") + } + if grantsEvents("openid https://www.googleapis.com/auth/calendar.readonly") { + t.Error("read-only seen as writable") + } +} + +func TestApplyKeepsLength(t *testing.T) { + start := time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC) + it := item{title: "x", start: start, end: start.Add(90 * time.Minute)} + if err := (EventInput{Start: ptr("2026-11-18T09:00:00Z")}).apply(&it); err != nil { + t.Fatal(err) + } + if it.end.Sub(it.start) != 90*time.Minute { + t.Errorf("length = %v", it.end.Sub(it.start)) + } + if err := (EventInput{AllDay: ptr(true)}).apply(&it); err == nil { + t.Error("switched to all-day without a date") + } + if err := (EventInput{AllDay: ptr(true), Start: ptr("2026-11-18")}).apply(&it); err != nil || it.end.Sub(it.start) != 24*time.Hour { + t.Errorf("all-day = %+v, %v", it, err) + } + if !errors.Is(errStale, errStale) { + t.Fatal() + } +} diff --git a/Server/internal/httpapi/calendars.go b/Server/internal/httpapi/calendars.go index ef409b1..98f1798 100644 --- a/Server/internal/httpapi/calendars.go +++ b/Server/internal/httpapi/calendars.go @@ -11,7 +11,7 @@ import ( "docwell/server/internal/calendar" ) -// CalendarService reads people's calendars for their journals (ADR-16). +// CalendarService reads and writes people's calendars for their journals (ADR-16, ADR-19). 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) @@ -19,6 +19,9 @@ type CalendarService interface { 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) + CreateEvent(ctx context.Context, c access.Caller, in calendar.EventInput) (calendar.Event, error) + UpdateEvent(ctx context.Context, c access.Caller, id string, in calendar.EventInput) (calendar.Event, error) + DeleteEvent(ctx context.Context, c access.Caller, id string) error GoogleEnabled() bool GoogleConnectURL(ctx context.Context, c access.Caller) (string, error) } @@ -68,4 +71,23 @@ func (a *api) calendarRoutes(mux *routeMux) { v, err := a.calendars.Events(r.Context(), caller(r), q.Get("from"), q.Get("to"), q.Get("tz")) a.respond(w, v, err) })) + mux.HandleFunc("POST /api/v1/calendar/events", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + var in calendar.EventInput + if !a.decode(w, r, &in) { + return + } + v, err := a.calendars.CreateEvent(r.Context(), caller(r), in) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("PATCH /api/v1/calendar/events/{id}", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + var in calendar.EventInput + if !a.decode(w, r, &in) { + return + } + v, err := a.calendars.UpdateEvent(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, v, err) + })) + mux.HandleFunc("DELETE /api/v1/calendar/events/{id}", a.withCalendars(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.calendars.DeleteEvent(r.Context(), caller(r), r.PathValue("id"))) + })) } diff --git a/Server/internal/i18n/catalog/de.json b/Server/internal/i18n/catalog/de.json index fe53e0b..0b1c59a 100644 --- a/Server/internal/i18n/catalog/de.json +++ b/Server/internal/i18n/catalog/de.json @@ -18,12 +18,16 @@ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "KI ist für diesen Arbeitsbereich nicht eingerichtet: Ein Admin muss in den Einstellungen des Arbeitsbereichs einen Anbieter hinzufügen.", "AI is turned off in this workspace": "KI ist in diesem Arbeitsbereich ausgeschaltet", "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Füge Text-, Markdown-, HTML-, Word- (.docx) oder PDF-Dateien hinzu.", + "All-day events start on a date like 2026-11-17.": "Ganztägige Termine beginnen an einem Datum wie 2026-11-17.", + "An event can last at most a year.": "Ein Termin kann höchstens ein Jahr dauern.", + "An event cannot move to another calendar account.": "Ein Termin kann nicht in ein anderes Kalenderkonto verschoben werden.", "Ask a question of up to 8 000 characters.": "Stelle eine Frage mit bis zu 8 000 Zeichen.", "Ask for at most %d days, ending after they start.": "Wähle höchstens %d Tage, mit dem Ende nach dem Anfang.", "At most 200 options.": "Höchstens 200 Optionen.", "At most 2000 pages.": "Höchstens 2000 Seiten.", "At most 50 rules.": "Höchstens 50 Regeln.", "Bucket and endpoint are required for S3.": "Für S3 sind Bucket und Endpunkt erforderlich.", + "Calendar, title and start are required.": "Kalender, Titel und Beginn sind erforderlich.", "Choose a file.": "Wähle eine Datei.", "Choose a language.": "Wähle eine Sprache.", "Choose a notebook.": "Wähle ein Notizbuch.", @@ -33,6 +37,7 @@ "Choose the space highlights go to.": "Wähle den Bereich für die Markierungen.", "Choose the space to import into.": "Wähle den Bereich, in den importiert wird.", "Collection name is required.": "Ein Name für die Sammlung ist erforderlich.", + "Connect the Google account again and allow Docwell to manage events, then try again.": "Verbinde das Google-Konto erneut und erlaube Docwell, Termine zu verwalten, dann versuche es noch einmal.", "Connect the bot token and choose a channel first.": "Verbinde zuerst das Bot-Token und wähle einen Kanal.", "Connect the bot token first.": "Verbinde zuerst das Bot-Token.", "Content must be a Tiptap document.": "Der Inhalt muss ein Tiptap-Dokument sein.", @@ -44,10 +49,14 @@ "Each option needs a name of at most 60 characters.": "Jede Option braucht einen Namen mit höchstens 60 Zeichen.", "Endpoint must be an http(s) address.": "Der Endpunkt muss eine http(s)-Adresse sein.", "Enter a web address (http or https).": "Gib eine Webadresse ein (http oder https).", + "Events of a subscribed feed are changed where the feed comes from.": "Termine eines abonnierten Feeds werden dort geändert, wo der Feed herkommt.", "Files can be up to 10 MB.": "Dateien dürfen bis zu 10 MB groß sein.", "Font must be empty, serif or mono.": "Die Schrift muss leer, serif oder mono sein.", "Format must be markdown or html.": "Das Format muss markdown oder html sein.", "Format must be markdown, html, pdf or docx.": "Das Format muss markdown, html, pdf oder docx sein.", + "Give the event a title of at most %d characters.": "Gib dem Termin einen Titel mit höchstens %d Zeichen.", + "Give the start as a time like 2026-11-17T09:00:00+01:00.": "Gib den Beginn als Zeit wie 2026-11-17T09:00:00+01:00 an.", + "Give the start when switching between all-day and timed.": "Gib den Beginn an, wenn du zwischen ganztägig und mit Uhrzeit wechselst.", "Google sign-in is not set up on this server": "Die Anmeldung mit Google ist auf diesem Server nicht eingerichtet", "Icon is too long.": "Das Symbol ist zu lang.", "Import at most %d pages at once.": "Importiere höchstens %d Seiten auf einmal.", @@ -74,12 +83,14 @@ "Pick a range of at most a year.": "Wähle einen Zeitraum von höchstens einem Jahr.", "Pick an emoji.": "Wähle ein Emoji.", "Pick another tag of this workspace.": "Wähle ein anderes Tag dieses Arbeitsbereichs.", + "Pick one of the account's calendars.": "Wähle einen der Kalender des Kontos.", "Position must be a number.": "Die Position muss eine Zahl sein.", "Readwise is not connected": "Readwise ist nicht verbunden", "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Aufnahmen über 25 MB müssen mit ffmpeg zerteilt werden: Starte den Dienst docwell-media (DOCWELL_MEDIA_URL) oder installiere ffmpeg auf dem Server. MP3- und WAV-Dateien gehen auch ohne.", "Recordings up to 1 GB can be transcribed.": "Aufnahmen bis 1 GB können verschriftlicht werden.", "Reminder": "Erinnerung", "Reminder in “%s”": "Erinnerung in „%s“", + "Repeating events are changed in their own calendar app.": "Wiederkehrende Termine werden in ihrer eigenen Kalender-App geändert.", "Role must be member or guest.": "Die Rolle muss Mitglied oder Gast sein.", "Role must be user, admin or superadmin.": "Die Rolle muss Benutzer, Admin oder Superadmin sein.", "Say what to do, in up to 2 000 characters.": "Sag, was zu tun ist, in bis zu 2 000 Zeichen.", @@ -104,6 +115,8 @@ "The Word document could not be read.": "Das Word-Dokument konnte nicht gelesen werden.", "The anchor is too large.": "Der Anker ist zu groß.", "The comment is too long (max 5000).": "Der Kommentar ist zu lang (max. 5000).", + "The end is written like the start.": "Das Ende wird wie der Beginn geschrieben.", + "The event has to end after it starts.": "Der Termin muss nach seinem Beginn enden.", "The file has no text.": "Die Datei enthält keinen Text.", "The file is larger than %d MB.": "Die Datei ist größer als %d MB.", "The file is not UTF-8 text.": "Die Datei ist kein UTF-8-Text.", @@ -111,14 +124,19 @@ "The filter is not valid JSON.": "Der Filter ist kein gültiges JSON.", "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Der Mediendienst, der lange Aufnahmen zerteilt, ist nicht erreichbar. Versuche es später erneut oder frage einen Administrator.", "The page is too large to save.": "Die Seite ist zu groß zum Speichern.", + "The place can have at most %d characters.": "Der Ort kann höchstens %d Zeichen haben.", "The recording has no sound to transcribe.": "Die Aufnahme hat keinen Ton zum Verschriftlichen.", "The recording is larger than the media service accepts.": "Die Aufnahme ist größer, als der Mediendienst annimmt.", "The token is too long.": "Das Token ist zu lang.", + "This calendar cannot be written to.": "In diesen Kalender kann nicht geschrieben werden.", "This chat is full; start a new one or fork it.": "Dieser Chat ist voll; starte einen neuen oder verzweige ihn.", + "This event is no longer in its calendar.": "Dieser Termin ist nicht mehr in seinem Kalender.", + "This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.": "Dieser Termin wurde in seinem Kalender geändert, nachdem Docwell ihn zuletzt gelesen hat. Das Journal zeigt ihn jetzt so, wie er ist; nimm deine Änderung noch einmal vor.", "This list has as many profiles as allowed.": "Diese Liste hat schon so viele Profile wie erlaubt.", "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Dieser Arbeitsbereich hat seine KI-Tokens für diesen Monat aufgebraucht; ein Admin kann das Limit erhöhen.", "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Dieser Arbeitsbereich hat seinen Anteil an der KI des Servers für diesen Monat aufgebraucht; füge einen eigenen Anbieter hinzu oder frage den Admin des Servers.", "Title is too long (max 500).": "Der Titel ist zu lang (max. 500).", + "Turn the calendar on first.": "Schalte den Kalender zuerst ein.", "Unarchive the parent page first.": "Hole zuerst die übergeordnete Seite aus dem Archiv.", "Unknown colour.": "Unbekannte Farbe.", "Unknown option colour.": "Unbekannte Optionsfarbe.", @@ -159,6 +177,7 @@ "days must be between 0 and %d": "die Tage müssen zwischen 0 und %d liegen", "device not found": "Gerät nicht gefunden", "editor role required": "Bearbeiter-Rolle erforderlich", + "event not found": "Termin nicht gefunden", "file not found": "Datei nicht gefunden", "give a space, or a workspace for its recent pages": "gib einen Bereich an, oder einen Arbeitsbereich für dessen letzte Seiten", "grant not found": "Freigabe nicht gefunden", diff --git a/Server/internal/i18n/catalog/es.json b/Server/internal/i18n/catalog/es.json index f409a44..ea839e0 100644 --- a/Server/internal/i18n/catalog/es.json +++ b/Server/internal/i18n/catalog/es.json @@ -18,12 +18,16 @@ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "La IA no está configurada en este espacio de trabajo: un administrador debe añadir un proveedor en su configuración.", "AI is turned off in this workspace": "La IA está desactivada en este espacio de trabajo", "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Añade archivos de texto, Markdown, HTML, Word (.docx) o PDF.", + "All-day events start on a date like 2026-11-17.": "Los eventos de todo el día empiezan en una fecha como 2026-11-17.", + "An event can last at most a year.": "Un evento puede durar como máximo un año.", + "An event cannot move to another calendar account.": "Un evento no puede pasar a otra cuenta de calendario.", "Ask a question of up to 8 000 characters.": "Haz una pregunta de hasta 8000 caracteres.", "Ask for at most %d days, ending after they start.": "Pide como máximo %d días, con el final después del inicio.", "At most 200 options.": "Como máximo 200 opciones.", "At most 2000 pages.": "Como máximo 2000 páginas.", "At most 50 rules.": "Como máximo 50 reglas.", "Bucket and endpoint are required for S3.": "Para S3 se necesitan el bucket y el endpoint.", + "Calendar, title and start are required.": "El calendario, el título y el inicio son obligatorios.", "Choose a file.": "Elige un archivo.", "Choose a language.": "Elige un idioma.", "Choose a notebook.": "Elige un bloc de notas.", @@ -33,6 +37,7 @@ "Choose the space highlights go to.": "Elige el espacio al que van los subrayados.", "Choose the space to import into.": "Elige el espacio al que importar.", "Collection name is required.": "La colección necesita un nombre.", + "Connect the Google account again and allow Docwell to manage events, then try again.": "Vuelve a conectar la cuenta de Google y permite que Docwell gestione eventos; luego inténtalo de nuevo.", "Connect the bot token and choose a channel first.": "Primero conecta el token del bot y elige un canal.", "Connect the bot token first.": "Primero conecta el token del bot.", "Content must be a Tiptap document.": "El contenido debe ser un documento Tiptap.", @@ -44,10 +49,14 @@ "Each option needs a name of at most 60 characters.": "Cada opción necesita un nombre de como máximo 60 caracteres.", "Endpoint must be an http(s) address.": "El endpoint debe ser una dirección http(s).", "Enter a web address (http or https).": "Escribe una dirección web (http o https).", + "Events of a subscribed feed are changed where the feed comes from.": "Los eventos de un feed suscrito se cambian donde se origina el feed.", "Files can be up to 10 MB.": "Los archivos pueden ocupar hasta 10 MB.", "Font must be empty, serif or mono.": "La fuente debe estar vacía o ser serif o mono.", "Format must be markdown or html.": "El formato debe ser markdown o html.", "Format must be markdown, html, pdf or docx.": "El formato debe ser markdown, html, pdf o docx.", + "Give the event a title of at most %d characters.": "Dale al evento un título de como máximo %d caracteres.", + "Give the start as a time like 2026-11-17T09:00:00+01:00.": "Indica el inicio como una hora como 2026-11-17T09:00:00+01:00.", + "Give the start when switching between all-day and timed.": "Indica el inicio al cambiar entre todo el día y con hora.", "Google sign-in is not set up on this server": "El inicio de sesión con Google no está configurado en este servidor", "Icon is too long.": "El icono es demasiado largo.", "Import at most %d pages at once.": "Importa como máximo %d páginas a la vez.", @@ -74,12 +83,14 @@ "Pick a range of at most a year.": "Elige un periodo de como máximo un año.", "Pick an emoji.": "Elige un emoji.", "Pick another tag of this workspace.": "Elige otra etiqueta de este espacio de trabajo.", + "Pick one of the account's calendars.": "Elige uno de los calendarios de la cuenta.", "Position must be a number.": "La posición debe ser un número.", "Readwise is not connected": "Readwise no está conectado", "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Las grabaciones de más de 25 MB necesitan ffmpeg para cortarse: ejecuta el servicio docwell-media (DOCWELL_MEDIA_URL) o instala ffmpeg en el servidor. Los archivos MP3 y WAV funcionan sin él.", "Recordings up to 1 GB can be transcribed.": "Se pueden transcribir grabaciones de hasta 1 GB.", "Reminder": "Recordatorio", "Reminder in “%s”": "Recordatorio en «%s»", + "Repeating events are changed in their own calendar app.": "Los eventos periódicos se cambian en su propia aplicación de calendario.", "Role must be member or guest.": "El rol debe ser miembro o invitado.", "Role must be user, admin or superadmin.": "El rol debe ser usuario, administrador o superadministrador.", "Say what to do, in up to 2 000 characters.": "Di qué hacer, en hasta 2000 caracteres.", @@ -104,6 +115,8 @@ "The Word document could not be read.": "No se pudo leer el documento de Word.", "The anchor is too large.": "El ancla es demasiado grande.", "The comment is too long (max 5000).": "El comentario es demasiado largo (máx. 5000).", + "The end is written like the start.": "El final se escribe como el inicio.", + "The event has to end after it starts.": "El evento tiene que terminar después de empezar.", "The file has no text.": "El archivo no tiene texto.", "The file is larger than %d MB.": "El archivo ocupa más de %d MB.", "The file is not UTF-8 text.": "El archivo no es texto UTF-8.", @@ -111,14 +124,19 @@ "The filter is not valid JSON.": "El filtro no es un JSON válido.", "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "No se puede acceder al servicio que corta las grabaciones largas. Inténtalo más tarde o pregunta a un administrador.", "The page is too large to save.": "La página es demasiado grande para guardarla.", + "The place can have at most %d characters.": "El lugar puede tener como máximo %d caracteres.", "The recording has no sound to transcribe.": "La grabación no tiene sonido que transcribir.", "The recording is larger than the media service accepts.": "La grabación es más grande de lo que acepta el servicio multimedia.", "The token is too long.": "El token es demasiado largo.", + "This calendar cannot be written to.": "No se puede escribir en este calendario.", "This chat is full; start a new one or fork it.": "Este chat está lleno; empieza uno nuevo o bifúrcalo.", + "This event is no longer in its calendar.": "Este evento ya no está en su calendario.", + "This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.": "Este evento se cambió en su calendario después de que Docwell lo leyera por última vez. El diario lo muestra ahora tal como está; vuelve a hacer tu cambio.", "This list has as many profiles as allowed.": "Esta lista ya tiene tantos perfiles como se permite.", "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Este espacio de trabajo ha gastado sus tokens de IA de este mes; un administrador puede subir el límite.", "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Este espacio de trabajo ha gastado su parte de la IA del servidor de este mes; añade un proveedor propio o pregunta al administrador del servidor.", "Title is too long (max 500).": "El título es demasiado largo (máx. 500).", + "Turn the calendar on first.": "Activa primero el calendario.", "Unarchive the parent page first.": "Primero desarchiva la página superior.", "Unknown colour.": "Color desconocido.", "Unknown option colour.": "Color de opción desconocido.", @@ -159,6 +177,7 @@ "days must be between 0 and %d": "los días deben estar entre 0 y %d", "device not found": "no se encontró el dispositivo", "editor role required": "se necesita el rol de editor", + "event not found": "no se encontró el evento", "file not found": "no se encontró el archivo", "give a space, or a workspace for its recent pages": "indica un espacio, o un espacio de trabajo para sus páginas recientes", "grant not found": "no se encontró el permiso", diff --git a/Server/internal/i18n/catalog/fr.json b/Server/internal/i18n/catalog/fr.json index dbe49a7..62c0a0d 100644 --- a/Server/internal/i18n/catalog/fr.json +++ b/Server/internal/i18n/catalog/fr.json @@ -18,12 +18,16 @@ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "L’IA n’est pas configurée pour cet espace de travail : un administrateur doit ajouter un fournisseur dans ses paramètres.", "AI is turned off in this workspace": "L’IA est désactivée dans cet espace de travail", "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Ajoutez des fichiers texte, Markdown, HTML, Word (.docx) ou PDF.", + "All-day events start on a date like 2026-11-17.": "Les événements sur la journée commencent à une date comme 2026-11-17.", + "An event can last at most a year.": "Un événement peut durer au plus un an.", + "An event cannot move to another calendar account.": "Un événement ne peut pas passer à un autre compte d’agenda.", "Ask a question of up to 8 000 characters.": "Posez une question de 8 000 caractères au plus.", "Ask for at most %d days, ending after they start.": "Demandez au plus %d jours, la fin après le début.", "At most 200 options.": "200 options au plus.", "At most 2000 pages.": "2000 pages au plus.", "At most 50 rules.": "50 règles au plus.", "Bucket and endpoint are required for S3.": "Le bucket et le point de terminaison sont requis pour S3.", + "Calendar, title and start are required.": "L’agenda, le titre et le début sont obligatoires.", "Choose a file.": "Choisissez un fichier.", "Choose a language.": "Choisissez une langue.", "Choose a notebook.": "Choisissez un bloc-notes.", @@ -33,6 +37,7 @@ "Choose the space highlights go to.": "Choisissez l’espace où vont les surlignages.", "Choose the space to import into.": "Choisissez l’espace où importer.", "Collection name is required.": "Le nom de la collection est requis.", + "Connect the Google account again and allow Docwell to manage events, then try again.": "Connectez à nouveau le compte Google en autorisant Docwell à gérer les événements, puis réessayez.", "Connect the bot token and choose a channel first.": "Connectez d’abord le jeton du bot et choisissez un canal.", "Connect the bot token first.": "Connectez d’abord le jeton du bot.", "Content must be a Tiptap document.": "Le contenu doit être un document Tiptap.", @@ -44,10 +49,14 @@ "Each option needs a name of at most 60 characters.": "Chaque option doit avoir un nom de 60 caractères au plus.", "Endpoint must be an http(s) address.": "Le point de terminaison doit être une adresse http(s).", "Enter a web address (http or https).": "Saisissez une adresse web (http ou https).", + "Events of a subscribed feed are changed where the feed comes from.": "Les événements d’un flux abonné se modifient là d’où vient le flux.", "Files can be up to 10 MB.": "Les fichiers peuvent faire jusqu’à 10 Mo.", "Font must be empty, serif or mono.": "La police doit être vide, serif ou mono.", "Format must be markdown or html.": "Le format doit être markdown ou html.", "Format must be markdown, html, pdf or docx.": "Le format doit être markdown, html, pdf ou docx.", + "Give the event a title of at most %d characters.": "Donnez à l’événement un titre d’au plus %d caractères.", + "Give the start as a time like 2026-11-17T09:00:00+01:00.": "Indiquez le début sous la forme d’une heure comme 2026-11-17T09:00:00+01:00.", + "Give the start when switching between all-day and timed.": "Indiquez le début quand vous passez d’un événement sur la journée à un événement horaire, ou l’inverse.", "Google sign-in is not set up on this server": "La connexion avec Google n’est pas configurée sur ce serveur", "Icon is too long.": "L’icône est trop longue.", "Import at most %d pages at once.": "Importez au plus %d pages à la fois.", @@ -74,12 +83,14 @@ "Pick a range of at most a year.": "Choisissez une période d’un an au plus.", "Pick an emoji.": "Choisissez un emoji.", "Pick another tag of this workspace.": "Choisissez une autre étiquette de cet espace de travail.", + "Pick one of the account's calendars.": "Choisissez l’un des agendas du compte.", "Position must be a number.": "La position doit être un nombre.", "Readwise is not connected": "Readwise n’est pas connecté", "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Les enregistrements de plus de 25 Mo doivent être découpés avec ffmpeg : lancez le service docwell-media (DOCWELL_MEDIA_URL) ou installez ffmpeg sur le serveur. Les fichiers MP3 et WAV fonctionnent sans.", "Recordings up to 1 GB can be transcribed.": "Les enregistrements jusqu’à 1 Go peuvent être transcrits.", "Reminder": "Rappel", "Reminder in “%s”": "Rappel dans « %s »", + "Repeating events are changed in their own calendar app.": "Les événements récurrents se modifient dans leur propre application d’agenda.", "Role must be member or guest.": "Le rôle doit être membre ou invité.", "Role must be user, admin or superadmin.": "Le rôle doit être utilisateur, administrateur ou superadministrateur.", "Say what to do, in up to 2 000 characters.": "Dites quoi faire, en 2 000 caractères au plus.", @@ -104,6 +115,8 @@ "The Word document could not be read.": "Le document Word n’a pas pu être lu.", "The anchor is too large.": "L’ancre est trop grande.", "The comment is too long (max 5000).": "Le commentaire est trop long (5000 max.).", + "The end is written like the start.": "La fin s’écrit comme le début.", + "The event has to end after it starts.": "L’événement doit se terminer après son début.", "The file has no text.": "Le fichier ne contient pas de texte.", "The file is larger than %d MB.": "Le fichier dépasse %d Mo.", "The file is not UTF-8 text.": "Le fichier n’est pas du texte UTF-8.", @@ -111,14 +124,19 @@ "The filter is not valid JSON.": "Le filtre n’est pas un JSON valide.", "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Le service qui découpe les longs enregistrements est injoignable. Réessayez plus tard ou contactez un administrateur.", "The page is too large to save.": "La page est trop volumineuse pour être enregistrée.", + "The place can have at most %d characters.": "Le lieu peut compter au plus %d caractères.", "The recording has no sound to transcribe.": "L’enregistrement n’a pas de son à transcrire.", "The recording is larger than the media service accepts.": "L’enregistrement dépasse la taille acceptée par le service multimédia.", "The token is too long.": "Le jeton est trop long.", + "This calendar cannot be written to.": "Impossible d’écrire dans cet agenda.", "This chat is full; start a new one or fork it.": "Cette discussion est pleine ; commencez-en une nouvelle ou dupliquez-la.", + "This event is no longer in its calendar.": "Cet événement n’est plus dans son agenda.", + "This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.": "Cet événement a été modifié dans son agenda depuis la dernière lecture de Docwell. Le journal l’affiche maintenant tel qu’il est ; refaites votre modification.", "This list has as many profiles as allowed.": "Cette liste a déjà autant de profils que permis.", "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Cet espace de travail a épuisé ses jetons d’IA pour ce mois ; un administrateur peut relever la limite.", "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Cet espace de travail a épuisé sa part de l’IA du serveur pour ce mois ; ajoutez son propre fournisseur ou contactez l’administrateur du serveur.", "Title is too long (max 500).": "Le titre est trop long (500 max.).", + "Turn the calendar on first.": "Activez d’abord l’agenda.", "Unarchive the parent page first.": "Désarchivez d’abord la page parente.", "Unknown colour.": "Couleur inconnue.", "Unknown option colour.": "Couleur d’option inconnue.", @@ -159,6 +177,7 @@ "days must be between 0 and %d": "le nombre de jours doit être compris entre 0 et %d", "device not found": "appareil introuvable", "editor role required": "rôle d’éditeur requis", + "event not found": "événement introuvable", "file not found": "fichier introuvable", "give a space, or a workspace for its recent pages": "indiquez un espace, ou un espace de travail pour ses pages récentes", "grant not found": "autorisation introuvable", diff --git a/Server/internal/i18n/catalog/pl.json b/Server/internal/i18n/catalog/pl.json index a680890..2000052 100644 --- a/Server/internal/i18n/catalog/pl.json +++ b/Server/internal/i18n/catalog/pl.json @@ -18,12 +18,16 @@ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "AI nie jest skonfigurowane w tym obszarze roboczym: administrator musi dodać dostawcę w ustawieniach obszaru.", "AI is turned off in this workspace": "AI jest wyłączone w tym obszarze roboczym", "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Dodaj pliki tekstowe, Markdown, HTML, Word (.docx) lub PDF.", + "All-day events start on a date like 2026-11-17.": "Wydarzenia całodniowe zaczynają się w dniu zapisanym jak 2026-11-17.", + "An event can last at most a year.": "Wydarzenie może trwać najwyżej rok.", + "An event cannot move to another calendar account.": "Wydarzenia nie można przenieść na inne konto kalendarza.", "Ask a question of up to 8 000 characters.": "Zadaj pytanie o długości do 8000 znaków.", "Ask for at most %d days, ending after they start.": "Wybierz najwyżej %d dni, z końcem po początku.", "At most 200 options.": "Najwyżej 200 opcji.", "At most 2000 pages.": "Najwyżej 2000 stron.", "At most 50 rules.": "Najwyżej 50 reguł.", "Bucket and endpoint are required for S3.": "Dla S3 wymagane są bucket i endpoint.", + "Calendar, title and start are required.": "Kalendarz, tytuł i początek są wymagane.", "Choose a file.": "Wybierz plik.", "Choose a language.": "Wybierz język.", "Choose a notebook.": "Wybierz notes.", @@ -33,6 +37,7 @@ "Choose the space highlights go to.": "Wybierz przestrzeń, do której trafią zakreślenia.", "Choose the space to import into.": "Wybierz przestrzeń, do której chcesz importować.", "Collection name is required.": "Podaj nazwę kolekcji.", + "Connect the Google account again and allow Docwell to manage events, then try again.": "Połącz konto Google ponownie i pozwól Docwell zarządzać wydarzeniami, a potem spróbuj jeszcze raz.", "Connect the bot token and choose a channel first.": "Najpierw podłącz token bota i wybierz kanał.", "Connect the bot token first.": "Najpierw podłącz token bota.", "Content must be a Tiptap document.": "Treść musi być dokumentem Tiptap.", @@ -44,10 +49,14 @@ "Each option needs a name of at most 60 characters.": "Każda opcja potrzebuje nazwy o długości do 60 znaków.", "Endpoint must be an http(s) address.": "Endpoint musi być adresem http(s).", "Enter a web address (http or https).": "Wpisz adres internetowy (http lub https).", + "Events of a subscribed feed are changed where the feed comes from.": "Wydarzenia z subskrybowanego kanału zmienia się tam, skąd pochodzi kanał.", "Files can be up to 10 MB.": "Pliki mogą mieć do 10 MB.", "Font must be empty, serif or mono.": "Czcionka musi być pusta, serif lub mono.", "Format must be markdown or html.": "Format musi być markdown lub html.", "Format must be markdown, html, pdf or docx.": "Format musi być markdown, html, pdf lub docx.", + "Give the event a title of at most %d characters.": "Nadaj wydarzeniu tytuł o długości najwyżej %d znaków.", + "Give the start as a time like 2026-11-17T09:00:00+01:00.": "Podaj początek jako czas zapisany jak 2026-11-17T09:00:00+01:00.", + "Give the start when switching between all-day and timed.": "Podaj początek, gdy zmieniasz wydarzenie całodniowe na godzinowe lub odwrotnie.", "Google sign-in is not set up on this server": "Logowanie przez Google nie jest skonfigurowane na tym serwerze", "Icon is too long.": "Ikona jest za długa.", "Import at most %d pages at once.": "Importuj najwyżej %d stron naraz.", @@ -74,12 +83,14 @@ "Pick a range of at most a year.": "Wybierz zakres najwyżej jednego roku.", "Pick an emoji.": "Wybierz emoji.", "Pick another tag of this workspace.": "Wybierz inny tag z tego obszaru roboczego.", + "Pick one of the account's calendars.": "Wybierz jeden z kalendarzy konta.", "Position must be a number.": "Pozycja musi być liczbą.", "Readwise is not connected": "Readwise nie jest połączony", "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Nagrania ponad 25 MB trzeba pociąć programem ffmpeg: uruchom usługę docwell-media (DOCWELL_MEDIA_URL) albo zainstaluj ffmpeg na serwerze. Pliki MP3 i WAV działają bez niego.", "Recordings up to 1 GB can be transcribed.": "Przepisać można nagrania do 1 GB.", "Reminder": "Przypomnienie", "Reminder in “%s”": "Przypomnienie w „%s”", + "Repeating events are changed in their own calendar app.": "Wydarzenia cykliczne zmienia się w ich własnej aplikacji kalendarza.", "Role must be member or guest.": "Rola musi być: członek lub gość.", "Role must be user, admin or superadmin.": "Rola musi być: użytkownik, administrator lub superadministrator.", "Say what to do, in up to 2 000 characters.": "Napisz, co zrobić, w maksymalnie 2000 znaków.", @@ -104,6 +115,8 @@ "The Word document could not be read.": "Nie udało się odczytać dokumentu Word.", "The anchor is too large.": "Kotwica jest za duża.", "The comment is too long (max 5000).": "Komentarz jest za długi (maks. 5000).", + "The end is written like the start.": "Koniec zapisuje się tak samo jak początek.", + "The event has to end after it starts.": "Wydarzenie musi się kończyć po swoim początku.", "The file has no text.": "Plik nie zawiera tekstu.", "The file is larger than %d MB.": "Plik jest większy niż %d MB.", "The file is not UTF-8 text.": "Plik nie jest tekstem UTF-8.", @@ -111,14 +124,19 @@ "The filter is not valid JSON.": "Filtr nie jest prawidłowym JSON-em.", "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Usługa dzieląca długie nagrania jest nieosiągalna. Spróbuj później lub zapytaj administratora.", "The page is too large to save.": "Strona jest za duża, by ją zapisać.", + "The place can have at most %d characters.": "Miejsce może mieć najwyżej %d znaków.", "The recording has no sound to transcribe.": "Nagranie nie ma dźwięku do przepisania.", "The recording is larger than the media service accepts.": "Nagranie jest większe, niż przyjmuje usługa multimediów.", "The token is too long.": "Token jest za długi.", + "This calendar cannot be written to.": "Do tego kalendarza nie można zapisywać.", "This chat is full; start a new one or fork it.": "Ten czat jest pełny; zacznij nowy albo go rozgałęź.", + "This event is no longer in its calendar.": "Tego wydarzenia nie ma już w jego kalendarzu.", + "This event was changed in its calendar after Docwell last read it. The journal now shows it as it is; make your change again.": "To wydarzenie zmieniono w jego kalendarzu po tym, jak Docwell ostatnio je odczytał. Dziennik pokazuje je teraz w obecnej postaci; wprowadź zmianę jeszcze raz.", "This list has as many profiles as allowed.": "Ta lista ma już maksymalną liczbę profili.", "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Ten obszar roboczy wykorzystał tokeny AI na ten miesiąc; administrator obszaru może podnieść limit.", "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Ten obszar roboczy wykorzystał swój udział w AI serwera na ten miesiąc; dodaj własnego dostawcę albo zapytaj administratora serwera.", "Title is too long (max 500).": "Tytuł jest za długi (maks. 500).", + "Turn the calendar on first.": "Najpierw włącz kalendarz.", "Unarchive the parent page first.": "Najpierw przywróć z archiwum stronę nadrzędną.", "Unknown colour.": "Nieznany kolor.", "Unknown option colour.": "Nieznany kolor opcji.", @@ -159,6 +177,7 @@ "days must be between 0 and %d": "liczba dni musi wynosić od 0 do %d", "device not found": "nie znaleziono urządzenia", "editor role required": "wymagana rola edytora", + "event not found": "nie znaleziono wydarzenia", "file not found": "nie znaleziono pliku", "give a space, or a workspace for its recent pages": "podaj przestrzeń albo obszar roboczy, by zobaczyć jego ostatnie strony", "grant not found": "nie znaleziono uprawnienia", diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json index 3b0372f..4718c68 100644 --- a/Server/internal/pbschema/schema.json +++ b/Server/internal/pbschema/schema.json @@ -5454,6 +5454,42 @@ "presentable": false, "system": false, "type": "autodate" + }, + { + "help": "", + "hidden": false, + "id": "bool46008626", + "name": "can_write", + "presentable": false, + "required": false, + "system": false, + "type": "bool" + }, + { + "help": "", + "hidden": false, + "id": "json2940411411", + "maxSize": 200000, + "name": "targets", + "presentable": false, + "required": false, + "system": false, + "type": "json" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1722757368", + "max": 2000, + "min": 0, + "name": "write_to", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" } ], "id": "pbc_1382459093", @@ -5642,12 +5678,68 @@ "presentable": false, "system": false, "type": "autodate" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text2368920574", + "max": 2000, + "min": 0, + "name": "cal", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text342834851", + "max": 2000, + "min": 0, + "name": "ref", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text3514087100", + "max": 500, + "min": 0, + "name": "etag", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "bool1819017965", + "name": "recurring", + "presentable": false, + "required": false, + "system": false, + "type": "bool" } ], "id": "pbc_2544738948", "indexes": [ "CREATE UNIQUE INDEX idx_calendar_events_key ON calendar_events (account, key)", - "CREATE INDEX idx_calendar_events_user ON calendar_events (user, start_at)" + "CREATE INDEX idx_calendar_events_user ON calendar_events (user, start_at)", + "CREATE INDEX idx_calendar_events_user_key ON calendar_events (user, key)" ], "listRule": null, "name": "calendar_events", diff --git a/Web-App/frontend/src/components/CalendarAccounts.vue b/Web-App/frontend/src/components/CalendarAccounts.vue index 2d7abee..68d409a 100644 --- a/Web-App/frontend/src/components/CalendarAccounts.vue +++ b/Web-App/frontend/src/components/CalendarAccounts.vue @@ -12,6 +12,9 @@ import FormField from "./FormField.vue"; // The signed-in person's calendars (ADR-16): iCalendar feeds, CalDAV and // Google accounts whose events show on their journal pages. Only they see them. +// Events can be added to CalDAV and Google calendars from journal pages +// (ADR-19); each account picks the calendar new events go to. A Google +// account connected read-only is offered a new sign-in. const api = useApi(); const route = useRoute(); const router = useRouter(); @@ -97,6 +100,7 @@ const add = () => const toggle = (a: CalendarAccount) => run(() => api.calendars.update(a.id, { enabled: !a.enabled })); const recolor = (a: CalendarAccount, color: LabelColor) => run(() => api.calendars.update(a.id, { color })); const refresh = (a: CalendarAccount) => run(() => api.calendars.refresh(a.id)); +const writeTo = (a: CalendarAccount, id: string) => run(() => api.calendars.update(a.id, { writeTo: id })); const remove = (a: CalendarAccount) => { if (confirm(t("calendars.confirmRemove", { name: a.name }))) void run(() => api.calendars.remove(a.id)); }; @@ -153,6 +157,31 @@ const when = (iso: string) => {{ $t("calendars.synced", { date: when(a.lastSync), n: a.events }) }} + + {{ $t("calendars.readOnlyGoogle") }} + + {{ $t("calendars.reconnect") }} + + +