Connect Google Calendar, import OneNote notebooks, sync Readwise, and package the clipper
Phase F follow-ups (ADR-16): - Calendars: events are now stored in calendar_events by a calendars.sync job (every 15 minutes per account, 90 days back and 400 ahead), so journals open at once and keep showing events while a source is down. Google accounts connect with OAuth (calendar.readonly) through DOCWELL_GOOGLE_CLIENT_ID/SECRET; reconnecting renews access. - OneNote: whole notebooks import through Microsoft Graph (Notes.Read, DOCWELL_MICROSOFT_CLIENT_ID/SECRET/TENANT) in the background, with section groups, sections, subpages, pictures and attached files. The Microsoft sign-in lives in memory for an hour and is never stored. - Readwise: an hourly sync with the person's sealed access token; new books get a page under "Readwise", new highlights are appended once. New readwise_syncs collection. - internal/oauth: signed states and one callback route per provider, routed by purpose. directory gains ImportConverted and CallerOf. - Phone app: "Today's journal" on the home screen and calendar events on journal pages. - Web clipper: `npm run package` builds Chrome/Edge, Firefox and source zips; store/ holds listing texts, permission notes and a privacy policy. - OpenAPI, generated clients, translations, compose and .env examples, and user docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3d1cf362d7
commit
6984c7d162
59 files changed
+5697
-255
No files matched your search
@@ -16,6 +16,7 @@ build/bin/
|
||||
/Desktop-App/frontend/dist/*
|
||||
!/Desktop-App/frontend/dist/.gitkeep
|
||||
/Web-Clipper/dist/
|
||||
/Web-Clipper/release/
|
||||
|
||||
# PocketBase local data
|
||||
pb_data/
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Phase F follow-ups (ADR-16):
|
||||
//
|
||||
// - calendar_events: the occurrences of each calendar account's events, a
|
||||
// few months back and a year ahead, written by the calendars.sync job, so
|
||||
// journals (web and phones) read them without waiting on the source and
|
||||
// still show them when it is down. Timed events keep UTC instants; all-day
|
||||
// events keep their dates (start_at/end_at at 00:00 UTC, all_day set).
|
||||
// - calendar_accounts.kind "google": a Google account signed in with OAuth;
|
||||
// secret holds its sealed refresh token.
|
||||
// - readwise_syncs: a person's Readwise connection (sealed token) and where
|
||||
// their highlights go; books maps Readwise book ids to pages and the
|
||||
// highlight ids already written.
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
const accounts = app.findCollectionByNameOrId("calendar_accounts");
|
||||
const kind = accounts.fields.getByName("kind");
|
||||
kind.values = ["ics", "caldav", "google"];
|
||||
app.save(accounts);
|
||||
|
||||
app.save(
|
||||
new Collection({
|
||||
type: "base",
|
||||
name: "calendar_events",
|
||||
fields: [
|
||||
{ name: "account", type: "relation", collectionId: accounts.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "key", type: "text", required: true, max: 64 },
|
||||
{ name: "hash", type: "text", max: 64 },
|
||||
{ name: "title", type: "text", max: 1000 },
|
||||
{ name: "location", type: "text", max: 1000 },
|
||||
{ name: "url", type: "text", max: 2000 },
|
||||
{ name: "all_day", type: "bool" },
|
||||
{ name: "start_at", type: "date", required: true },
|
||||
{ name: "end_at", type: "date", required: true },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
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)",
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const workspaces = app.findCollectionByNameOrId("workspaces");
|
||||
const spaces = app.findCollectionByNameOrId("spaces");
|
||||
app.save(
|
||||
new Collection({
|
||||
type: "base",
|
||||
name: "readwise_syncs",
|
||||
fields: [
|
||||
{ name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "space", type: "relation", collectionId: spaces.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "parent", type: "text", max: 64 },
|
||||
{ name: "secret", type: "text", max: 2000 },
|
||||
{ name: "enabled", type: "bool" },
|
||||
{ name: "cursor", type: "text", max: 64 },
|
||||
{ name: "books", type: "json", maxSize: 5000000 },
|
||||
{ name: "last_sync", type: "date" },
|
||||
{ name: "last_error", type: "text", max: 500 },
|
||||
{ name: "highlights", type: "number" },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
indexes: ["CREATE UNIQUE INDEX idx_readwise_syncs_user ON readwise_syncs (user)"],
|
||||
}),
|
||||
);
|
||||
},
|
||||
(app) => {
|
||||
app.delete(app.findCollectionByNameOrId("readwise_syncs"));
|
||||
app.delete(app.findCollectionByNameOrId("calendar_events"));
|
||||
const accounts = app.findCollectionByNameOrId("calendar_accounts");
|
||||
accounts.fields.getByName("kind").values = ["ics", "caldav"];
|
||||
app.save(accounts);
|
||||
},
|
||||
);
|
||||
@@ -26,6 +26,17 @@ DOCWELL_MAX_UPLOAD_MB=50
|
||||
# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
|
||||
DOCWELL_MEDIA_TOKEN=
|
||||
|
||||
# Optional OAuth apps people sign in to. Google: Google Calendar on journal
|
||||
# pages (calendar.readonly). Microsoft: importing whole OneNote notebooks
|
||||
# (Notes.Read). Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback
|
||||
# and .../oauth/microsoft/callback as redirect URIs. Blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID=
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET=
|
||||
DOCWELL_MICROSOFT_CLIENT_ID=
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET=
|
||||
# "common" (any account), "organizations", "consumers" or a tenant id.
|
||||
DOCWELL_MICROSOFT_TENANT=common
|
||||
|
||||
# Sign-up defaults; the admin panel can change them later.
|
||||
# The first account always can sign up and becomes the instance admin.
|
||||
DOCWELL_SIGNUP_ENABLED=true
|
||||
|
||||
@@ -67,6 +67,17 @@ DOCWELL_MAX_UPLOAD_MB=50
|
||||
# between it and docwell-server. To run without it, remove the media service
|
||||
# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
|
||||
DOCWELL_MEDIA_TOKEN=
|
||||
|
||||
# Optional OAuth apps people sign in to. Google: Google Calendar on journal
|
||||
# pages (calendar.readonly). Microsoft: importing whole OneNote notebooks
|
||||
# (Notes.Read). Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback
|
||||
# and .../oauth/microsoft/callback as redirect URIs. Blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID=
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET=
|
||||
DOCWELL_MICROSOFT_CLIENT_ID=
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET=
|
||||
# "common" (any account), "organizations", "consumers" or a tenant id.
|
||||
DOCWELL_MICROSOFT_TENANT=common
|
||||
# Days to keep audit log entries. Blank = 365, 0 = forever.
|
||||
DOCWELL_AUDIT_RETENTION_DAYS=
|
||||
|
||||
|
||||
@@ -67,6 +67,17 @@ DOCWELL_MAX_UPLOAD_MB=50
|
||||
# between it and docwell-server. To run without it, remove the media service
|
||||
# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
|
||||
DOCWELL_MEDIA_TOKEN=
|
||||
|
||||
# Optional OAuth apps people sign in to. Google: Google Calendar on journal
|
||||
# pages (calendar.readonly). Microsoft: importing whole OneNote notebooks
|
||||
# (Notes.Read). Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback
|
||||
# and .../oauth/microsoft/callback as redirect URIs. Blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID=
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET=
|
||||
DOCWELL_MICROSOFT_CLIENT_ID=
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET=
|
||||
# "common" (any account), "organizations", "consumers" or a tenant id.
|
||||
DOCWELL_MICROSOFT_TENANT=common
|
||||
# Days to keep audit log entries. Blank = 365, 0 = forever.
|
||||
DOCWELL_AUDIT_RETENTION_DAYS=
|
||||
|
||||
|
||||
@@ -67,6 +67,17 @@ DOCWELL_MAX_UPLOAD_MB=50
|
||||
# between it and docwell-server. To run without it, remove the media service
|
||||
# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
|
||||
DOCWELL_MEDIA_TOKEN=
|
||||
|
||||
# Optional OAuth apps people sign in to. Google: Google Calendar on journal
|
||||
# pages (calendar.readonly). Microsoft: importing whole OneNote notebooks
|
||||
# (Notes.Read). Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback
|
||||
# and .../oauth/microsoft/callback as redirect URIs. Blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID=
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET=
|
||||
DOCWELL_MICROSOFT_CLIENT_ID=
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET=
|
||||
# "common" (any account), "organizations", "consumers" or a tenant id.
|
||||
DOCWELL_MICROSOFT_TENANT=common
|
||||
# Days to keep audit log entries. Blank = 365, 0 = forever.
|
||||
DOCWELL_AUDIT_RETENTION_DAYS=
|
||||
|
||||
|
||||
@@ -67,6 +67,17 @@ DOCWELL_MAX_UPLOAD_MB=50
|
||||
# between it and docwell-server. To run without it, remove the media service
|
||||
# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
|
||||
DOCWELL_MEDIA_TOKEN=
|
||||
|
||||
# Optional OAuth apps people sign in to. Google: Google Calendar on journal
|
||||
# pages (calendar.readonly). Microsoft: importing whole OneNote notebooks
|
||||
# (Notes.Read). Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback
|
||||
# and .../oauth/microsoft/callback as redirect URIs. Blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID=
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET=
|
||||
DOCWELL_MICROSOFT_CLIENT_ID=
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET=
|
||||
# "common" (any account), "organizations", "consumers" or a tenant id.
|
||||
DOCWELL_MICROSOFT_TENANT=common
|
||||
# Days to keep audit log entries. Blank = 365, 0 = forever.
|
||||
DOCWELL_AUDIT_RETENTION_DAYS=
|
||||
|
||||
|
||||
@@ -119,6 +119,12 @@ services:
|
||||
# the server cuts MP3 and WAV itself and refuses other long formats.
|
||||
DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
|
||||
DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
|
||||
# Google Calendar and OneNote sign-ins; blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID: "${DOCWELL_GOOGLE_CLIENT_ID:-}"
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET: "${DOCWELL_GOOGLE_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_ID: "${DOCWELL_MICROSOFT_CLIENT_ID:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET: "${DOCWELL_MICROSOFT_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_TENANT: "${DOCWELL_MICROSOFT_TENANT:-common}"
|
||||
# --- File storage: external S3 --------------------------------------
|
||||
# Applied by docwell-server on every start, so these win over the
|
||||
# admin panel's Storage screen. Only uploaded files move to the bucket;
|
||||
|
||||
@@ -287,6 +287,12 @@ services:
|
||||
# the server cuts MP3 and WAV itself and refuses other long formats.
|
||||
DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
|
||||
DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
|
||||
# Google Calendar and OneNote sign-ins; blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID: "${DOCWELL_GOOGLE_CLIENT_ID:-}"
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET: "${DOCWELL_GOOGLE_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_ID: "${DOCWELL_MICROSOFT_CLIENT_ID:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET: "${DOCWELL_MICROSOFT_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_TENANT: "${DOCWELL_MICROSOFT_TENANT:-common}"
|
||||
# --- File storage: the SeaweedFS in this stack ------------------------
|
||||
# Applied by docwell-server on every start, so these win over
|
||||
# the admin panel's Storage screen. Only uploaded files move to the
|
||||
|
||||
@@ -163,6 +163,12 @@ services:
|
||||
# the server cuts MP3 and WAV itself and refuses other long formats.
|
||||
DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
|
||||
DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
|
||||
# Google Calendar and OneNote sign-ins; blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID: "${DOCWELL_GOOGLE_CLIENT_ID:-}"
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET: "${DOCWELL_GOOGLE_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_ID: "${DOCWELL_MICROSOFT_CLIENT_ID:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET: "${DOCWELL_MICROSOFT_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_TENANT: "${DOCWELL_MICROSOFT_TENANT:-common}"
|
||||
# --- File storage: the SeaweedFS in this stack ------------------------
|
||||
# Applied by docwell-server on every start, so these win over
|
||||
# the admin panel's Storage screen. Only uploaded files move to the
|
||||
|
||||
@@ -106,6 +106,12 @@ services:
|
||||
# the server cuts MP3 and WAV itself and refuses other long formats.
|
||||
DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
|
||||
DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
|
||||
# Google Calendar and OneNote sign-ins; blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID: "${DOCWELL_GOOGLE_CLIENT_ID:-}"
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET: "${DOCWELL_GOOGLE_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_ID: "${DOCWELL_MICROSOFT_CLIENT_ID:-}"
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET: "${DOCWELL_MICROSOFT_CLIENT_SECRET:-}"
|
||||
DOCWELL_MICROSOFT_TENANT: "${DOCWELL_MICROSOFT_TENANT:-common}"
|
||||
networks: [default, media]
|
||||
volumes:
|
||||
# The search index only; rebuilt from the database when missing, so it
|
||||
|
||||
@@ -58,6 +58,12 @@ services:
|
||||
# the server cuts MP3 and WAV itself and refuses other long formats.
|
||||
DOCWELL_MEDIA_URL: ${DOCWELL_MEDIA_URL-http://media:8090}
|
||||
DOCWELL_MEDIA_TOKEN: ${DOCWELL_MEDIA_TOKEN:-}
|
||||
# Google Calendar and OneNote sign-ins; blank = off.
|
||||
DOCWELL_GOOGLE_CLIENT_ID: ${DOCWELL_GOOGLE_CLIENT_ID:-}
|
||||
DOCWELL_GOOGLE_CLIENT_SECRET: ${DOCWELL_GOOGLE_CLIENT_SECRET:-}
|
||||
DOCWELL_MICROSOFT_CLIENT_ID: ${DOCWELL_MICROSOFT_CLIENT_ID:-}
|
||||
DOCWELL_MICROSOFT_CLIENT_SECRET: ${DOCWELL_MICROSOFT_CLIENT_SECRET:-}
|
||||
DOCWELL_MICROSOFT_TENANT: ${DOCWELL_MICROSOFT_TENANT:-common}
|
||||
networks: [default, media]
|
||||
volumes:
|
||||
# The search index (rebuilt from the database when missing).
|
||||
|
||||
@@ -31,12 +31,15 @@ Docwell's collections in it when it starts. Change the image with `DB_IMAGE`.
|
||||
| `DOCWELL_ADMIN_NAME` | `Admin` | The display name of that account. |
|
||||
| `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. |
|
||||
| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index and the AI vectors (`ai.db`). Both are rebuilt from the database when missing, so a volume is optional but makes restarts faster (and saves embedding every page again). |
|
||||
| `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers and the passwords of people's calendars. Without it, a key derived from `DOCWELL_PB_PASSWORD` is used; changing whichever is in use means entering the keys and passwords again. |
|
||||
| `DOCWELL_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_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. |
|
||||
| `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. |
|
||||
| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, people's calendars, and the AI providers of workspaces, call loopback and link-local addresses (private networks are always allowed, so a CalDAV server on your LAN works). For development only (AI providers set up in the admin panel may always use local addresses). |
|
||||
| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, people's calendars, Readwise and OneNote imports, and the AI providers of workspaces, call loopback and link-local addresses (private networks are always allowed, so a CalDAV server on your LAN works). For development only (AI providers set up in the admin panel may always use local addresses). |
|
||||
|
||||
### PocketBase settings
|
||||
|
||||
|
||||
@@ -175,16 +175,22 @@ page new journal pages start from in the Info panel, under **Journal**; any page
|
||||
### Calendars on journal pages
|
||||
|
||||
In **Account settings → Calendars**, subscribe to your calendars; their events for the day are listed at the top of
|
||||
each journal page, in your time zone. Only you see them, and Docwell only reads them.
|
||||
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.
|
||||
|
||||
- **iCal feed:** any `.ics` or `webcal://` address. For Google Calendar, use the calendar's **Secret address in iCal
|
||||
format** (Settings → the calendar → Integrate calendar); for Outlook, publish the calendar and use its ICS link.
|
||||
- **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
|
||||
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.
|
||||
- **CalDAV account:** your server's address (for Nextcloud `https://cloud.example.com/remote.php/dav`, for iCloud
|
||||
`https://caldav.icloud.com` with an app-specific password) with your user name and password; Docwell reads every
|
||||
event calendar of the account, or only the one whose address you enter.
|
||||
|
||||
Repeating events, moved and cancelled occurrences and time zones are taken into account. Events are read again every
|
||||
15 minutes, or at once with **Refresh**; the list says when a calendar was last read, or why it could not be.
|
||||
Repeating events, moved and cancelled occurrences and time zones are taken into account. Docwell keeps a copy of
|
||||
each calendar's events (three months back, a year ahead) and reads the calendar again every 15 minutes, or at once
|
||||
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.
|
||||
|
||||
## Sharing
|
||||
|
||||
@@ -216,11 +222,20 @@ page too. Turning it off makes the link stop working at once. Pages in the trash
|
||||
space export imports back the same way.
|
||||
- **From Bear:** import a Bear backup (`.bear2bk`), or a `.zip` of notes exported as TextBundle. `#tags` and
|
||||
`#multi word tags#` become tags.
|
||||
- **From OneNote:** in OneNote for Windows, choose **File → Export**, pick a page or section and **Single File Web
|
||||
Page (\*.mht)**, and import the `.mht`. Each page becomes a page, with its pictures.
|
||||
- **From Readwise:** in Readwise, choose **Export → Export to CSV** and import the `.csv`. A **Readwise** page holds a
|
||||
page per book or article, with its highlights as quotes, your notes and locations, its author as a property and its
|
||||
document tags as tags. Readwise's Markdown export imports like any folder of Markdown.
|
||||
- **From OneNote, whole notebooks:** **OneNote** next to **Import** on a space's page list signs in to Microsoft and
|
||||
lists your notebooks; pick one and it is imported in the background. The notebook, its section groups and sections
|
||||
become pages, each OneNote page a page under its section (subpages under their page), with pictures and attached
|
||||
files. The button appears when your server has a Microsoft app set up. Docwell keeps no Microsoft sign-in after
|
||||
the import (it lasts an hour).
|
||||
- **From OneNote, a page or section:** in OneNote for Windows, choose **File → Export**, pick a page or section and
|
||||
**Single File Web Page (\*.mht)**, and import the `.mht`. Each page becomes a page, with its pictures.
|
||||
- **From Readwise, kept up to date:** in **Account settings → Readwise**, paste your access token
|
||||
(readwise.io/access_token) and pick a space. Every hour, each new book or article gets a page under a **Readwise**
|
||||
page there, and new highlights are added to the end of their book's page; **Sync now** does it at once. Pages are
|
||||
made as you, with your rights. A book page you delete or move to the trash gets a new one with the next highlights.
|
||||
- **From Readwise, once:** in Readwise, choose **Export → Export to CSV** and import the `.csv`. A **Readwise** page
|
||||
holds a page per book or article, with its highlights as quotes, your notes and locations, its author as a property
|
||||
and its document tags as tags. Readwise's Markdown export imports like any folder of Markdown.
|
||||
- **CSV:** any other `.csv` becomes a page with a database of its rows.
|
||||
- **To Notion:** export the page as Word or Markdown, then import that file with **Import** in Notion's sidebar.
|
||||
|
||||
@@ -229,7 +244,9 @@ page too. Turning it off makes the link stop working at once. Pages in the trash
|
||||
The Docwell Web Clipper (in `Web-Clipper/` of the source; Chrome, Edge and Firefox) saves the page you are reading as
|
||||
a new page: the article on it, or only what you selected, with its links and pictures, under a note saying where it
|
||||
came from. In its options, enter the address you open Docwell at and an API token with *Read and write* access
|
||||
(Account settings → API tokens), then pick the space new clips go to.
|
||||
(Account settings → API tokens), then pick the space new clips go to. `npm run package -w @docwell/web-clipper`
|
||||
builds the zips for the Chrome Web Store, Edge Add-ons and addons.mozilla.org; `Web-Clipper/store/` has the listing
|
||||
texts, permission notes and privacy policy for publishing it.
|
||||
|
||||
### Workspace snapshots
|
||||
|
||||
|
||||
@@ -90,6 +90,12 @@ export type Tag = Schemas["Tag"];
|
||||
export type CalendarAccount = Schemas["CalendarAccount"];
|
||||
export type CalendarAccountInput = Schemas["CalendarAccountInput"];
|
||||
export type CalendarEvent = Schemas["CalendarEvent"];
|
||||
export type Integrations = Schemas["Integrations"];
|
||||
export type OneNoteNotebook = Schemas["OneNoteNotebook"];
|
||||
export type OneNoteConnection = Schemas["OneNoteConnection"];
|
||||
export type OneNoteJob = Schemas["OneNoteJob"];
|
||||
export type ReadwiseConnection = Schemas["ReadwiseConnection"];
|
||||
export type ReadwiseInput = Schemas["ReadwiseInput"];
|
||||
export type TagInput = Schemas["TagInput"];
|
||||
export type DocRule = Schemas["DocRule"];
|
||||
export type DocFilter = Schemas["DocFilter"];
|
||||
@@ -570,6 +576,26 @@ export function createClient(opts: ClientOptions) {
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/properties/${encodeURIComponent(id)}`),
|
||||
},
|
||||
|
||||
/** Which outside services (Google, Microsoft, Readwise) this server can reach. */
|
||||
integrations: () => request<Integrations>("GET", "/api/v1/integrations"),
|
||||
|
||||
onenote: {
|
||||
/** Where to send the browser to sign in to Microsoft for an import into space. */
|
||||
connect: (space: string, parent = "") =>
|
||||
request<{ url: string }>("GET", `/api/v1/onenote/connect${query({ space, parent: parent || undefined })}`),
|
||||
connection: (id: string) => request<OneNoteConnection>("GET", `/api/v1/onenote/connections/${enc(id)}`),
|
||||
import: (id: string, input: { notebook: string; space: string; parent?: string }) =>
|
||||
post<OneNoteJob>(`/api/v1/onenote/connections/${enc(id)}/import`, input),
|
||||
job: (id: string) => request<OneNoteJob>("GET", `/api/v1/onenote/jobs/${enc(id)}`),
|
||||
},
|
||||
|
||||
readwise: {
|
||||
get: () => request<ReadwiseConnection>("GET", "/api/v1/readwise"),
|
||||
save: (input: ReadwiseInput) => request<ReadwiseConnection>("PUT", "/api/v1/readwise", input),
|
||||
remove: () => request<void>("DELETE", "/api/v1/readwise"),
|
||||
sync: () => post<ReadwiseConnection>("/api/v1/readwise/sync"),
|
||||
},
|
||||
|
||||
calendars: {
|
||||
list: () => request<CalendarAccount[]>("GET", "/api/v1/calendars"),
|
||||
/** Subscribes to a feed or CalDAV account; the server reads it once to check it. */
|
||||
@@ -578,6 +604,8 @@ export function createClient(opts: ClientOptions) {
|
||||
request<CalendarAccount>("PATCH", `/api/v1/calendars/${encodeURIComponent(id)}`, patch),
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/calendars/${encodeURIComponent(id)}`),
|
||||
refresh: (id: string) => post<CalendarAccount>(`/api/v1/calendars/${encodeURIComponent(id)}/refresh`),
|
||||
/** Where to send the browser to connect a Google account's calendars. */
|
||||
googleConnect: () => request<{ url: string }>("GET", "/api/v1/calendars/google/connect"),
|
||||
/** The caller's events from day from to day to (inclusive), in zone tz. */
|
||||
events: (from: string, to: string, tz?: string) =>
|
||||
request<CalendarEvent[]>("GET", `/api/v1/calendar/events${query({ from, to, tz })}`),
|
||||
|
||||
Vendored
+488
-4
@@ -2079,6 +2079,184 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/integrations": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** Which outside services this server can reach for people */
|
||||
get: operations["getIntegrations"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/oauth/{provider}/callback": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
provider: "google" | "microsoft";
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* Where Google and Microsoft send the browser back after a sign-in
|
||||
* @description Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback and {DOCWELL_PUBLIC_URL}/api/v1/oauth/microsoft/callback as redirect URIs of the OAuth apps. The signed state says who signed in and why; the browser is sent on to the web app.
|
||||
*/
|
||||
get: operations["oauthCallback"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/calendars/google/connect": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
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.
|
||||
*/
|
||||
get: operations["connectGoogleCalendar"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/onenote/connect": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* Where to send the browser to sign in to Microsoft and import OneNote notebooks into a space
|
||||
* @description Needs DOCWELL_MICROSOFT_CLIENT_ID and DOCWELL_MICROSOFT_CLIENT_SECRET. The browser returns to the space with ?onenote=<connection>.
|
||||
*/
|
||||
get: operations["connectOneNote"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/onenote/connections/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** The signed-in Microsoft account and its notebooks (a connection lasts an hour) */
|
||||
get: operations["getOneNoteConnection"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/onenote/connections/{id}/import": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Start importing a notebook into a space (editor); it runs in the background
|
||||
* @description The notebook, its section groups and sections become pages; each OneNote page a page under its section (subpages under their parent page), with pictures and attached files as attachments. At most 2000 pages and 512 MB of files.
|
||||
*/
|
||||
post: operations["importOneNoteNotebook"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/onenote/jobs/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** How a OneNote import is going */
|
||||
get: operations["getOneNoteJob"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/readwise": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** The caller's Readwise sync (connected false when there is none) */
|
||||
get: operations["getReadwise"];
|
||||
/**
|
||||
* Connect Readwise, or change where highlights go
|
||||
* @description The token (readwise.io/access_token) is checked with Readwise and sealed. Every hour new books get a page under a "Readwise" page in the space, and new highlights are added to the end of their book's page. Choosing another space starts over there.
|
||||
*/
|
||||
put: operations["saveReadwise"];
|
||||
post?: never;
|
||||
/** Disconnect Readwise (the pages stay) */
|
||||
delete: operations["deleteReadwise"];
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/readwise/sync": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Add new Readwise highlights now */
|
||||
post: operations["syncReadwise"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/calendars": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -2131,7 +2309,7 @@ export interface paths {
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Read a calendar from its source now (events are otherwise kept for 15 minutes) */
|
||||
/** Read a calendar from its source and store its events now (otherwise every 15 minutes) */
|
||||
post: operations["refreshCalendar"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
@@ -2148,7 +2326,7 @@ export interface paths {
|
||||
};
|
||||
/**
|
||||
* The caller's events between two days, from their enabled calendars
|
||||
* @description Repeating events are expanded, changed and cancelled occurrences applied. All-day events come first. A calendar that cannot be read is left out (its lastError says why).
|
||||
* @description Read from the stored copy the calendars.sync job keeps (every 15 minutes, 90 days back and 400 days ahead), so it answers at once and still shows events when a source is down. Repeating events are expanded, changed and cancelled occurrences applied. All-day events come first.
|
||||
*/
|
||||
get: operations["listCalendarEvents"];
|
||||
put?: never;
|
||||
@@ -3782,11 +3960,64 @@ export interface components {
|
||||
* @enum {string}
|
||||
*/
|
||||
PropertyType: "text" | "number" | "checkbox" | "date" | "select" | "multi_select" | "member" | "link";
|
||||
Integrations: {
|
||||
/** @description People can connect Google Calendar */
|
||||
google: boolean;
|
||||
/** @description People can import OneNote notebooks */
|
||||
microsoft: boolean;
|
||||
readwise: boolean;
|
||||
};
|
||||
ConnectURL: {
|
||||
/** @description Where to send the browser */
|
||||
url: string;
|
||||
};
|
||||
OneNoteNotebook: {
|
||||
id: string;
|
||||
name: string;
|
||||
modified: string;
|
||||
};
|
||||
OneNoteConnection: {
|
||||
/** @description The Microsoft account signed in */
|
||||
account: string;
|
||||
notebooks: components["schemas"]["OneNoteNotebook"][];
|
||||
};
|
||||
OneNoteJob: {
|
||||
id: string;
|
||||
notebook: string;
|
||||
/** @enum {string} */
|
||||
status: "running" | "done" | "failed";
|
||||
/** @description OneNote pages read so far */
|
||||
pages: number;
|
||||
error: string;
|
||||
/** @description The pages made at the top */
|
||||
created: components["schemas"]["Page"][];
|
||||
};
|
||||
ReadwiseConnection: {
|
||||
connected: boolean;
|
||||
workspace: string;
|
||||
space: string;
|
||||
/** @description The "Readwise" page books go under */
|
||||
parent: string;
|
||||
enabled: boolean;
|
||||
lastSync: string;
|
||||
lastError: string;
|
||||
highlights: number;
|
||||
books: number;
|
||||
};
|
||||
ReadwiseInput: {
|
||||
/** @description Empty keeps the stored one */
|
||||
token?: string;
|
||||
space?: string;
|
||||
enabled?: boolean;
|
||||
};
|
||||
CalendarAccount: {
|
||||
id: string;
|
||||
name: string;
|
||||
/** @enum {string} */
|
||||
kind: "ics" | "caldav";
|
||||
/**
|
||||
* @description google accounts are connected with /calendars/google/connect
|
||||
* @enum {string}
|
||||
*/
|
||||
kind: "ics" | "caldav" | "google";
|
||||
url: string;
|
||||
username: string;
|
||||
hasPassword: boolean;
|
||||
@@ -7894,6 +8125,259 @@ export interface operations {
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getIntegrations: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Integrations"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
oauthCallback: {
|
||||
parameters: {
|
||||
query?: {
|
||||
state?: string;
|
||||
code?: string;
|
||||
error?: string;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
provider: "google" | "microsoft";
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description On to the web app */
|
||||
302: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
};
|
||||
};
|
||||
connectGoogleCalendar: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ConnectURL"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
connectOneNote: {
|
||||
parameters: {
|
||||
query: {
|
||||
space: string;
|
||||
parent?: string;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ConnectURL"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getOneNoteConnection: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["OneNoteConnection"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
importOneNoteNotebook: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
notebook: string;
|
||||
space: string;
|
||||
parent?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Started */
|
||||
202: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["OneNoteJob"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getOneNoteJob: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["OneNoteJob"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getReadwise: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ReadwiseConnection"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
saveReadwise: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["ReadwiseInput"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ReadwiseConnection"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
deleteReadwise: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Disconnected */
|
||||
204: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
syncReadwise: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The sync with its result */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ReadwiseConnection"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
listCalendars: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -139,6 +139,22 @@ class DocwellApi {
|
||||
Future<void> saveContent(String page, Map<String, dynamic> doc) =>
|
||||
_send('PUT', '/api/v1/pages/${_id(page)}/content', {'content': doc});
|
||||
|
||||
/// The caller's journal page for a day (YYYY-MM-DD), made if missing.
|
||||
Future<Page> openJournal(String workspace, String date) async =>
|
||||
Page.fromJson(
|
||||
await _send(
|
||||
'PUT',
|
||||
'/api/v1/workspaces/${_id(workspace)}/journals/${_id(date)}',
|
||||
{},
|
||||
),
|
||||
);
|
||||
|
||||
/// The caller's calendar events from day from to day to (inclusive, UTC).
|
||||
Future<List<CalendarEvent>> calendarEvents(String from, String to) async =>
|
||||
(await _getList(
|
||||
'/api/v1/calendar/events?from=${_id(from)}&to=${_id(to)}',
|
||||
)).map((e) => CalendarEvent.fromJson(e as Map<String, dynamic>)).toList();
|
||||
|
||||
/// Records that the user opened the page, for their recent list.
|
||||
Future<void> visit(String page) =>
|
||||
_send('POST', '/api/v1/pages/${_id(page)}/visit');
|
||||
|
||||
@@ -3564,9 +3564,242 @@ enum PropertyType {
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class Integrations {
|
||||
const Integrations({
|
||||
required this.google,
|
||||
required this.microsoft,
|
||||
required this.readwise,
|
||||
});
|
||||
|
||||
factory Integrations.fromJson(Map<String, dynamic> json) => Integrations(
|
||||
google: json['google'] as bool,
|
||||
microsoft: json['microsoft'] as bool,
|
||||
readwise: json['readwise'] as bool,
|
||||
);
|
||||
|
||||
/// People can connect Google Calendar
|
||||
final bool google;
|
||||
|
||||
/// People can import OneNote notebooks
|
||||
final bool microsoft;
|
||||
|
||||
final bool readwise;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'google': google,
|
||||
'microsoft': microsoft,
|
||||
'readwise': readwise,
|
||||
};
|
||||
}
|
||||
|
||||
class ConnectURL {
|
||||
const ConnectURL({required this.url});
|
||||
|
||||
factory ConnectURL.fromJson(Map<String, dynamic> json) =>
|
||||
ConnectURL(url: json['url'] as String);
|
||||
|
||||
/// Where to send the browser
|
||||
final String url;
|
||||
|
||||
Map<String, dynamic> toJson() => {'url': url};
|
||||
}
|
||||
|
||||
class OneNoteNotebook {
|
||||
const OneNoteNotebook({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.modified,
|
||||
});
|
||||
|
||||
factory OneNoteNotebook.fromJson(Map<String, dynamic> json) =>
|
||||
OneNoteNotebook(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
modified: json['modified'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String name;
|
||||
|
||||
final String modified;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'modified': modified,
|
||||
};
|
||||
}
|
||||
|
||||
class OneNoteConnection {
|
||||
const OneNoteConnection({required this.account, required this.notebooks});
|
||||
|
||||
factory OneNoteConnection.fromJson(Map<String, dynamic> json) =>
|
||||
OneNoteConnection(
|
||||
account: json['account'] as String,
|
||||
notebooks: (json['notebooks'] as List)
|
||||
.map((e) => OneNoteNotebook.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
/// The Microsoft account signed in
|
||||
final String account;
|
||||
|
||||
final List<OneNoteNotebook> notebooks;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'account': account,
|
||||
'notebooks': notebooks.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
enum OneNoteJobStatus {
|
||||
running('running'),
|
||||
done('done'),
|
||||
failed('failed');
|
||||
|
||||
const OneNoteJobStatus(this.value);
|
||||
final String value;
|
||||
|
||||
static OneNoteJobStatus fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown OneNoteJobStatus', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class OneNoteJob {
|
||||
const OneNoteJob({
|
||||
required this.id,
|
||||
required this.notebook,
|
||||
required this.status,
|
||||
required this.pages,
|
||||
required this.error,
|
||||
required this.created,
|
||||
});
|
||||
|
||||
factory OneNoteJob.fromJson(Map<String, dynamic> json) => OneNoteJob(
|
||||
id: json['id'] as String,
|
||||
notebook: json['notebook'] as String,
|
||||
status: OneNoteJobStatus.fromJson(json['status'] as String),
|
||||
pages: (json['pages'] as num).toInt(),
|
||||
error: json['error'] as String,
|
||||
created: (json['created'] as List)
|
||||
.map((e) => Page.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String notebook;
|
||||
|
||||
final OneNoteJobStatus status;
|
||||
|
||||
/// OneNote pages read so far
|
||||
final int pages;
|
||||
|
||||
final String error;
|
||||
|
||||
/// The pages made at the top
|
||||
final List<Page> created;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'notebook': notebook,
|
||||
'status': status.toJson(),
|
||||
'pages': pages,
|
||||
'error': error,
|
||||
'created': created.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
class ReadwiseConnection {
|
||||
const ReadwiseConnection({
|
||||
required this.connected,
|
||||
required this.workspace,
|
||||
required this.space,
|
||||
required this.parent,
|
||||
required this.enabled,
|
||||
required this.lastSync,
|
||||
required this.lastError,
|
||||
required this.highlights,
|
||||
required this.books,
|
||||
});
|
||||
|
||||
factory ReadwiseConnection.fromJson(Map<String, dynamic> json) =>
|
||||
ReadwiseConnection(
|
||||
connected: json['connected'] as bool,
|
||||
workspace: json['workspace'] as String,
|
||||
space: json['space'] as String,
|
||||
parent: json['parent'] as String,
|
||||
enabled: json['enabled'] as bool,
|
||||
lastSync: json['lastSync'] as String,
|
||||
lastError: json['lastError'] as String,
|
||||
highlights: (json['highlights'] as num).toInt(),
|
||||
books: (json['books'] as num).toInt(),
|
||||
);
|
||||
|
||||
final bool connected;
|
||||
|
||||
final String workspace;
|
||||
|
||||
final String space;
|
||||
|
||||
/// The "Readwise" page books go under
|
||||
final String parent;
|
||||
|
||||
final bool enabled;
|
||||
|
||||
final String lastSync;
|
||||
|
||||
final String lastError;
|
||||
|
||||
final int highlights;
|
||||
|
||||
final int books;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'connected': connected,
|
||||
'workspace': workspace,
|
||||
'space': space,
|
||||
'parent': parent,
|
||||
'enabled': enabled,
|
||||
'lastSync': lastSync,
|
||||
'lastError': lastError,
|
||||
'highlights': highlights,
|
||||
'books': books,
|
||||
};
|
||||
}
|
||||
|
||||
class ReadwiseInput {
|
||||
const ReadwiseInput({this.token, this.space, this.enabled});
|
||||
|
||||
factory ReadwiseInput.fromJson(Map<String, dynamic> json) => ReadwiseInput(
|
||||
token: json['token'] == null ? null : json['token'] as String,
|
||||
space: json['space'] == null ? null : json['space'] as String,
|
||||
enabled: json['enabled'] == null ? null : json['enabled'] as bool,
|
||||
);
|
||||
|
||||
/// Empty keeps the stored one
|
||||
final String? token;
|
||||
|
||||
final String? space;
|
||||
|
||||
final bool? enabled;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'token': ?token,
|
||||
'space': ?space,
|
||||
'enabled': ?enabled,
|
||||
};
|
||||
}
|
||||
|
||||
/// google accounts are connected with /calendars/google/connect
|
||||
enum CalendarAccountKind {
|
||||
ics('ics'),
|
||||
caldav('caldav');
|
||||
caldav('caldav'),
|
||||
google('google');
|
||||
|
||||
const CalendarAccountKind(this.value);
|
||||
final String value;
|
||||
@@ -3615,6 +3848,7 @@ class CalendarAccount {
|
||||
|
||||
final String name;
|
||||
|
||||
/// google accounts are connected with /calendars/google/connect
|
||||
final CalendarAccountKind kind;
|
||||
|
||||
final String url;
|
||||
|
||||
@@ -37,6 +37,10 @@ String tr(String key, [Map<String, Object> args = const {}]) {
|
||||
|
||||
const appStrings = <String, Map<String, String>>{
|
||||
'en': {
|
||||
'journalToday': "Today's journal",
|
||||
'journalTodayHint': "Your daily page, with your calendar's events",
|
||||
'calendar': 'Calendar',
|
||||
'allDay': 'All day',
|
||||
'aiWriteTitle': 'Ask AI',
|
||||
'aiWriteNoSelection':
|
||||
'Select text in the page to rewrite, translate or summarise it.',
|
||||
@@ -177,6 +181,10 @@ const appStrings = <String, Map<String, String>>{
|
||||
'redo': 'Redo',
|
||||
},
|
||||
'pl': {
|
||||
'journalToday': 'Dzisiejszy dziennik',
|
||||
'journalTodayHint': 'Twoja strona dnia z wydarzeniami z kalendarza',
|
||||
'calendar': 'Kalendarz',
|
||||
'allDay': 'Cały dzień',
|
||||
'aiWriteTitle': 'Zapytaj AI',
|
||||
'aiWriteNoSelection':
|
||||
'Zaznacz tekst na stronie, aby go poprawić, przetłumaczyć lub podsumować.',
|
||||
@@ -317,6 +325,10 @@ const appStrings = <String, Map<String, String>>{
|
||||
'redo': 'Ponów',
|
||||
},
|
||||
'de': {
|
||||
'journalToday': 'Heutiges Journal',
|
||||
'journalTodayHint': 'Deine Tagesseite mit den Terminen aus deinem Kalender',
|
||||
'calendar': 'Kalender',
|
||||
'allDay': 'Ganztägig',
|
||||
'aiWriteTitle': 'KI fragen',
|
||||
'aiWriteNoSelection':
|
||||
'Markiere Text auf der Seite, um ihn zu überarbeiten, zu übersetzen oder zusammenzufassen.',
|
||||
@@ -460,6 +472,11 @@ const appStrings = <String, Map<String, String>>{
|
||||
'redo': 'Wiederholen',
|
||||
},
|
||||
'fr': {
|
||||
'journalToday': 'Journal du jour',
|
||||
'journalTodayHint':
|
||||
'Votre page du jour, avec les événements de votre agenda',
|
||||
'calendar': 'Agenda',
|
||||
'allDay': 'Toute la journée',
|
||||
'aiWriteTitle': 'Demander à l’IA',
|
||||
'aiWriteNoSelection':
|
||||
'Sélectionnez du texte dans la page pour le réécrire, le traduire ou le résumer.',
|
||||
@@ -603,6 +620,10 @@ const appStrings = <String, Map<String, String>>{
|
||||
'redo': 'Rétablir',
|
||||
},
|
||||
'es': {
|
||||
'journalToday': 'Diario de hoy',
|
||||
'journalTodayHint': 'Tu página del día, con los eventos de tu calendario',
|
||||
'calendar': 'Calendario',
|
||||
'allDay': 'Todo el día',
|
||||
'aiWriteTitle': 'Preguntar a la IA',
|
||||
'aiWriteNoSelection':
|
||||
'Selecciona texto de la página para reescribirlo, traducirlo o resumirlo.',
|
||||
|
||||
@@ -87,6 +87,27 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
context,
|
||||
).push(MaterialPageRoute<void>(builder: (_) => screen)).then((_) => _load());
|
||||
|
||||
/// Opens (or makes) today's page in the caller's journal.
|
||||
Future<void> _journal() async {
|
||||
final ws = _workspace;
|
||||
if (ws == null) return;
|
||||
final now = DateTime.now();
|
||||
String two(int n) => n.toString().padLeft(2, '0');
|
||||
try {
|
||||
final page = await _api.openJournal(
|
||||
ws.id,
|
||||
'${now.year}-${two(now.month)}-${two(now.day)}',
|
||||
);
|
||||
if (mounted) _open(PageScreen(session: widget.session, pageId: page.id));
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(describeError(e))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _togglePush(bool on) async {
|
||||
final push = widget.session.push;
|
||||
if (push == null) return;
|
||||
@@ -226,6 +247,14 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
subtitle: Text(tr('noWorkspacesHint')),
|
||||
)
|
||||
else ...[
|
||||
if (!_offline)
|
||||
ListTile(
|
||||
key: const Key('journal-today'),
|
||||
leading: const Icon(Icons.today_outlined),
|
||||
title: Text(tr('journalToday')),
|
||||
subtitle: Text(tr('journalTodayHint')),
|
||||
onTap: _journal,
|
||||
),
|
||||
if (_recent.isNotEmpty) ...[
|
||||
SectionTitle(tr('recent')),
|
||||
for (final p in _recent.take(5))
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api/docwell_api.dart';
|
||||
import '../l10n.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.
|
||||
class JournalEvents extends StatefulWidget {
|
||||
const JournalEvents({super.key, required this.api, required this.date});
|
||||
|
||||
final DocwellApi api;
|
||||
|
||||
/// The journal's day, YYYY-MM-DD.
|
||||
final String date;
|
||||
|
||||
@override
|
||||
State<JournalEvents> createState() => _JournalEventsState();
|
||||
}
|
||||
|
||||
/// The events of [events] that happen on [day] in the phone's time zone:
|
||||
/// timed ones overlapping it, all-day ones covering it. All-day events come
|
||||
/// first, then by start.
|
||||
List<CalendarEvent> eventsOn(List<CalendarEvent> events, DateTime day) {
|
||||
final start = DateTime(day.year, day.month, day.day);
|
||||
final end = start.add(const Duration(days: 1));
|
||||
final out = events.where((e) {
|
||||
if (e.allDay) {
|
||||
// All-day events are dates; compare them as dates.
|
||||
final s = DateTime.parse('${e.start}T00:00:00Z');
|
||||
final en = DateTime.parse('${e.end}T00:00:00Z');
|
||||
final d = DateTime.utc(day.year, day.month, day.day);
|
||||
return !s.isAfter(d) && en.isAfter(d);
|
||||
}
|
||||
final s = DateTime.parse(e.start).toLocal();
|
||||
final en = DateTime.parse(e.end).toLocal();
|
||||
return s.isBefore(end) && (en.isAfter(start) || !s.isBefore(start));
|
||||
}).toList();
|
||||
out.sort((a, b) {
|
||||
if (a.allDay != b.allDay) return a.allDay ? -1 : 1;
|
||||
return DateTime.parse(a.start).compareTo(DateTime.parse(b.start));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
String _two(int n) => n.toString().padLeft(2, '0');
|
||||
|
||||
String _day(DateTime d) => '${d.year}-${_two(d.month)}-${_two(d.day)}';
|
||||
|
||||
class _JournalEventsState extends State<JournalEvents> {
|
||||
List<CalendarEvent> _events = const [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(JournalEvents old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (old.date != widget.date) _load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final day = DateTime.tryParse(widget.date);
|
||||
if (day == null) return;
|
||||
try {
|
||||
// The server keeps UTC; ask for the days around this one and keep what
|
||||
// falls on it in the phone's zone.
|
||||
final list = await widget.api.calendarEvents(
|
||||
_day(day.subtract(const Duration(days: 1))),
|
||||
_day(day.add(const Duration(days: 1))),
|
||||
);
|
||||
if (mounted) setState(() => _events = eventsOn(list, day));
|
||||
} catch (_) {
|
||||
// Calendars are a help on the journal; their problems stay quiet here.
|
||||
}
|
||||
}
|
||||
|
||||
String _time(BuildContext context, String iso) =>
|
||||
MaterialLocalizations.of(context).formatTimeOfDay(
|
||||
TimeOfDay.fromDateTime(DateTime.parse(iso).toLocal()),
|
||||
alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_events.isEmpty) return const SizedBox.shrink();
|
||||
final theme = Theme.of(context);
|
||||
return Material(
|
||||
key: const Key('journal-events'),
|
||||
color: theme.colorScheme.surfaceContainerLow,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 180),
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
children: [
|
||||
Text(
|
||||
tr('calendar').toUpperCase(),
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
e.location.isEmpty
|
||||
? e.title
|
||||
: '${e.title} · ${e.location}',
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import '../editor/editor_screen.dart'
|
||||
import '../editor/ai_write_sheet.dart';
|
||||
import 'ai_chat_screen.dart';
|
||||
import 'comments_screen.dart';
|
||||
import 'journal_events.dart';
|
||||
import 'widgets.dart';
|
||||
import '../l10n.dart';
|
||||
|
||||
@@ -316,6 +317,11 @@ class _PageScreenState extends State<PageScreen> {
|
||||
content: Text(_bridge.error!),
|
||||
actions: const [SizedBox.shrink()],
|
||||
),
|
||||
if (page != null &&
|
||||
page.journalDate.isNotEmpty &&
|
||||
!_offline &&
|
||||
!_editing)
|
||||
JournalEvents(api: _api, date: page.journalDate),
|
||||
if (_error != null)
|
||||
Expanded(
|
||||
child: ErrorTile(message: _error!, onRetry: _load),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:docwell_mobile/api/docwell_api.dart';
|
||||
import 'package:docwell_mobile/screens/journal_events.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
CalendarEvent ev(
|
||||
String title,
|
||||
String start,
|
||||
String end, {
|
||||
bool allDay = false,
|
||||
}) => CalendarEvent.fromJson({
|
||||
'id': title,
|
||||
'calendar': 'c',
|
||||
'title': title,
|
||||
'location': '',
|
||||
'url': '',
|
||||
'start': start,
|
||||
'end': end,
|
||||
'allDay': allDay,
|
||||
'color': 'blue',
|
||||
});
|
||||
|
||||
String local(int day, int hour) =>
|
||||
DateTime(2026, 11, day, hour).toUtc().toIso8601String();
|
||||
|
||||
void main() {
|
||||
test('keeps the events of the day in the phone zone, all-day first', () {
|
||||
final events = [
|
||||
ev('Late', local(16, 22), local(16, 23)),
|
||||
ev('Holiday', '2026-11-16', '2026-11-17', allDay: true),
|
||||
ev(
|
||||
'Trip',
|
||||
'2026-11-14',
|
||||
'2026-11-16',
|
||||
allDay: true,
|
||||
), // ends the day before
|
||||
ev('Morning', local(16, 9), local(16, 10)),
|
||||
ev('Yesterday', local(15, 9), local(15, 10)),
|
||||
ev('Overnight', local(15, 23), local(16, 1)),
|
||||
ev('Tomorrow', local(17, 0), local(17, 1)),
|
||||
];
|
||||
final got = eventsOn(
|
||||
events,
|
||||
DateTime(2026, 11, 16),
|
||||
).map((e) => e.title).toList();
|
||||
expect(got, ['Holiday', 'Overnight', 'Morning', 'Late']);
|
||||
});
|
||||
}
|
||||
@@ -28,8 +28,11 @@ import (
|
||||
"docwell/server/internal/instance"
|
||||
"docwell/server/internal/jobs"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/oauth"
|
||||
"docwell/server/internal/onenote"
|
||||
"docwell/server/internal/pbschema"
|
||||
"docwell/server/internal/push"
|
||||
"docwell/server/internal/readwise"
|
||||
"docwell/server/internal/search"
|
||||
"docwell/server/internal/settings"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
@@ -175,9 +178,27 @@ func run(log *slog.Logger) error {
|
||||
reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second,
|
||||
func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) })
|
||||
go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute)
|
||||
// Calendars (ADR-16): passwords are sealed with the same secret as AI keys;
|
||||
// sources follow the webhook address rules.
|
||||
calSvc := calendar.New(db, calendar.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal})
|
||||
// Integrations (ADR-16): calendar passwords, Google tokens and Readwise
|
||||
// tokens are sealed with the same secret as AI keys; sources follow the
|
||||
// webhook address rules. Google and Microsoft sign-ins come back to one
|
||||
// callback, routed by their signed state.
|
||||
states := oauth.NewStates(secret)
|
||||
oauthRouter := oauth.NewRouter(states, cfg.WebURL)
|
||||
calSvc := calendar.New(db, calendar.Options{
|
||||
Secret: secret, AllowLocal: cfg.WebhooksAllowLocal, States: states, PublicURL: cfg.PublicURL, WebURL: cfg.WebURL,
|
||||
Google: oauth.Google(cfg.Google.ClientID, cfg.Google.ClientSecret),
|
||||
})
|
||||
oauthRouter.Handle(calendar.PurposeGoogle, calSvc.GoogleCallback)
|
||||
reg.Register("calendars.sync", "Copies the events of people's calendars for their journals", 5*time.Minute, calSvc.SyncDue)
|
||||
go reg.Every(indexCtx, "calendars.sync", 5*time.Minute)
|
||||
oneNoteSvc := onenote.New(dirSvc, onenote.Options{
|
||||
Provider: oauth.Microsoft(cfg.Microsoft.ClientID, cfg.Microsoft.ClientSecret, cfg.Microsoft.Tenant),
|
||||
States: states, PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, AllowLocal: cfg.WebhooksAllowLocal,
|
||||
})
|
||||
oauthRouter.Handle(onenote.Purpose, oneNoteSvc.Callback)
|
||||
readwiseSvc := readwise.New(db, dirSvc, readwise.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal})
|
||||
reg.Register("readwise.sync", "Adds new Readwise highlights to people's pages", 10*time.Minute, readwiseSvc.SyncDue)
|
||||
go reg.Every(indexCtx, "readwise.sync", 10*time.Minute)
|
||||
dirSvc.SetPublicURL(cfg.PublicURL)
|
||||
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
|
||||
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
|
||||
@@ -203,6 +224,9 @@ func run(log *slog.Logger) error {
|
||||
Audit: auditLog,
|
||||
Previews: unfurl.New(),
|
||||
Calendars: calSvc,
|
||||
OAuth: oauthRouter,
|
||||
OneNote: oneNoteSvc,
|
||||
Readwise: readwiseSvc,
|
||||
Push: pushSvc,
|
||||
AI: aiSvc,
|
||||
Admin: admin.Handler("/admin"),
|
||||
|
||||
+135
-13
@@ -174,6 +174,7 @@ func (e ApiTokenScope) Valid() bool {
|
||||
// Defines values for CalendarAccountKind.
|
||||
const (
|
||||
CalendarAccountKindCaldav CalendarAccountKind = "caldav"
|
||||
CalendarAccountKindGoogle CalendarAccountKind = "google"
|
||||
CalendarAccountKindIcs CalendarAccountKind = "ics"
|
||||
)
|
||||
|
||||
@@ -182,6 +183,8 @@ func (e CalendarAccountKind) Valid() bool {
|
||||
switch e {
|
||||
case CalendarAccountKindCaldav:
|
||||
return true
|
||||
case CalendarAccountKindGoogle:
|
||||
return true
|
||||
case CalendarAccountKindIcs:
|
||||
return true
|
||||
default:
|
||||
@@ -401,22 +404,43 @@ func (e NotificationType) Valid() bool {
|
||||
|
||||
// Defines values for OAuthProviderSettingsName.
|
||||
const (
|
||||
Github OAuthProviderSettingsName = "github"
|
||||
Google OAuthProviderSettingsName = "google"
|
||||
Microsoft OAuthProviderSettingsName = "microsoft"
|
||||
Oidc OAuthProviderSettingsName = "oidc"
|
||||
OAuthProviderSettingsNameGithub OAuthProviderSettingsName = "github"
|
||||
OAuthProviderSettingsNameGoogle OAuthProviderSettingsName = "google"
|
||||
OAuthProviderSettingsNameMicrosoft OAuthProviderSettingsName = "microsoft"
|
||||
OAuthProviderSettingsNameOidc OAuthProviderSettingsName = "oidc"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the OAuthProviderSettingsName enum.
|
||||
func (e OAuthProviderSettingsName) Valid() bool {
|
||||
switch e {
|
||||
case Github:
|
||||
case OAuthProviderSettingsNameGithub:
|
||||
return true
|
||||
case Google:
|
||||
case OAuthProviderSettingsNameGoogle:
|
||||
return true
|
||||
case Microsoft:
|
||||
case OAuthProviderSettingsNameMicrosoft:
|
||||
return true
|
||||
case Oidc:
|
||||
case OAuthProviderSettingsNameOidc:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for OneNoteJobStatus.
|
||||
const (
|
||||
OneNoteJobStatusDone OneNoteJobStatus = "done"
|
||||
OneNoteJobStatusFailed OneNoteJobStatus = "failed"
|
||||
OneNoteJobStatusRunning OneNoteJobStatus = "running"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the OneNoteJobStatus enum.
|
||||
func (e OneNoteJobStatus) Valid() bool {
|
||||
switch e {
|
||||
case OneNoteJobStatusDone:
|
||||
return true
|
||||
case OneNoteJobStatusFailed:
|
||||
return true
|
||||
case OneNoteJobStatusRunning:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -1315,10 +1339,12 @@ type CalendarAccount struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Events Events the source held then (repeating ones once)
|
||||
Events int `json:"events"`
|
||||
HasPassword bool `json:"hasPassword"`
|
||||
Id string `json:"id"`
|
||||
Kind CalendarAccountKind `json:"kind"`
|
||||
Events int `json:"events"`
|
||||
HasPassword bool `json:"hasPassword"`
|
||||
Id string `json:"id"`
|
||||
|
||||
// Kind google accounts are connected with /calendars/google/connect
|
||||
Kind CalendarAccountKind `json:"kind"`
|
||||
|
||||
// LastError Why the last read failed; empty when it worked
|
||||
LastError string `json:"lastError"`
|
||||
@@ -1330,7 +1356,7 @@ type CalendarAccount struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// CalendarAccountKind defines model for CalendarAccount.Kind.
|
||||
// CalendarAccountKind google accounts are connected with /calendars/google/connect
|
||||
type CalendarAccountKind string
|
||||
|
||||
// CalendarAccountInput defines model for CalendarAccountInput.
|
||||
@@ -1436,6 +1462,12 @@ type Comment struct {
|
||||
ResolvedBy *MemberUser `json:"resolvedBy"`
|
||||
}
|
||||
|
||||
// ConnectURL defines model for ConnectURL.
|
||||
type ConnectURL struct {
|
||||
// Url Where to send the browser
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
// CreateInviteRequest defines model for CreateInviteRequest.
|
||||
type CreateInviteRequest struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
@@ -1578,6 +1610,16 @@ type InstanceSettingsUpdate struct {
|
||||
Storage *StorageSettings `json:"storage,omitempty"`
|
||||
}
|
||||
|
||||
// Integrations defines model for Integrations.
|
||||
type Integrations struct {
|
||||
// Google People can connect Google Calendar
|
||||
Google bool `json:"google"`
|
||||
|
||||
// Microsoft People can import OneNote notebooks
|
||||
Microsoft bool `json:"microsoft"`
|
||||
Readwise bool `json:"readwise"`
|
||||
}
|
||||
|
||||
// Invite defines model for Invite.
|
||||
type Invite struct {
|
||||
Created string `json:"created"`
|
||||
@@ -1789,6 +1831,36 @@ type OAuthStart struct {
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
// OneNoteConnection defines model for OneNoteConnection.
|
||||
type OneNoteConnection struct {
|
||||
// Account The Microsoft account signed in
|
||||
Account string `json:"account"`
|
||||
Notebooks []OneNoteNotebook `json:"notebooks"`
|
||||
}
|
||||
|
||||
// OneNoteJob defines model for OneNoteJob.
|
||||
type OneNoteJob struct {
|
||||
// Created The pages made at the top
|
||||
Created []Page `json:"created"`
|
||||
Error string `json:"error"`
|
||||
Id string `json:"id"`
|
||||
Notebook string `json:"notebook"`
|
||||
|
||||
// Pages OneNote pages read so far
|
||||
Pages int `json:"pages"`
|
||||
Status OneNoteJobStatus `json:"status"`
|
||||
}
|
||||
|
||||
// OneNoteJobStatus defines model for OneNoteJob.Status.
|
||||
type OneNoteJobStatus string
|
||||
|
||||
// OneNoteNotebook defines model for OneNoteNotebook.
|
||||
type OneNoteNotebook struct {
|
||||
Id string `json:"id"`
|
||||
Modified string `json:"modified"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Organization defines model for Organization.
|
||||
type Organization struct {
|
||||
Created string `json:"created"`
|
||||
@@ -2062,6 +2134,30 @@ type Reaction struct {
|
||||
People []string `json:"people"`
|
||||
}
|
||||
|
||||
// ReadwiseConnection defines model for ReadwiseConnection.
|
||||
type ReadwiseConnection struct {
|
||||
Books int `json:"books"`
|
||||
Connected bool `json:"connected"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Highlights int `json:"highlights"`
|
||||
LastError string `json:"lastError"`
|
||||
LastSync string `json:"lastSync"`
|
||||
|
||||
// Parent The "Readwise" page books go under
|
||||
Parent string `json:"parent"`
|
||||
Space string `json:"space"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
|
||||
// ReadwiseInput defines model for ReadwiseInput.
|
||||
type ReadwiseInput struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
Space *string `json:"space,omitempty"`
|
||||
|
||||
// Token Empty keeps the stored one
|
||||
Token *string `json:"token,omitempty"`
|
||||
}
|
||||
|
||||
// Role Instance role. admin manages their own organization; superadmin manages everything.
|
||||
type Role string
|
||||
|
||||
@@ -2608,6 +2704,26 @@ type MarkNotificationsReadJSONBody struct {
|
||||
Ids *[]string `json:"ids,omitempty"`
|
||||
}
|
||||
|
||||
// OauthCallbackParams defines parameters for OauthCallback.
|
||||
type OauthCallbackParams struct {
|
||||
State *string `form:"state,omitempty" json:"state,omitempty"`
|
||||
Code *string `form:"code,omitempty" json:"code,omitempty"`
|
||||
Error *string `form:"error,omitempty" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ConnectOneNoteParams defines parameters for ConnectOneNote.
|
||||
type ConnectOneNoteParams struct {
|
||||
Space string `form:"space" json:"space"`
|
||||
Parent *string `form:"parent,omitempty" json:"parent,omitempty"`
|
||||
}
|
||||
|
||||
// ImportOneNoteNotebookJSONBody defines parameters for ImportOneNoteNotebook.
|
||||
type ImportOneNoteNotebookJSONBody struct {
|
||||
Notebook string `json:"notebook"`
|
||||
Parent *string `json:"parent,omitempty"`
|
||||
Space string `json:"space"`
|
||||
}
|
||||
|
||||
// DeletePageParams defines parameters for DeletePage.
|
||||
type DeletePageParams struct {
|
||||
Permanent *bool `form:"permanent,omitempty" json:"permanent,omitempty"`
|
||||
@@ -2998,6 +3114,9 @@ type MarkNotificationsReadJSONRequestBody MarkNotificationsReadJSONBody
|
||||
// SetNotificationSettingsJSONRequestBody defines body for SetNotificationSettings for application/json ContentType.
|
||||
type SetNotificationSettingsJSONRequestBody = NotificationSettings
|
||||
|
||||
// ImportOneNoteNotebookJSONRequestBody defines body for ImportOneNoteNotebook for application/json ContentType.
|
||||
type ImportOneNoteNotebookJSONRequestBody ImportOneNoteNotebookJSONBody
|
||||
|
||||
// CreateOrgJSONRequestBody defines body for CreateOrg for application/json ContentType.
|
||||
type CreateOrgJSONRequestBody = NameRequest
|
||||
|
||||
@@ -3040,6 +3159,9 @@ type SetPageWatchJSONRequestBody = WatchState
|
||||
// UpdatePropertyJSONRequestBody defines body for UpdateProperty for application/json ContentType.
|
||||
type UpdatePropertyJSONRequestBody = PropertyInput
|
||||
|
||||
// SaveReadwiseJSONRequestBody defines body for SaveReadwise for application/json ContentType.
|
||||
type SaveReadwiseJSONRequestBody = ReadwiseInput
|
||||
|
||||
// UpdateSpaceJSONRequestBody defines body for UpdateSpace for application/json ContentType.
|
||||
type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
|
||||
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
// Package calendar reads people's calendars for their journals (Phase F,
|
||||
// ADR-16): read-only subscriptions to an iCalendar feed (an .ics or webcal
|
||||
// address, Google Calendar's secret address, Outlook's published calendar)
|
||||
// or a CalDAV account (Nextcloud, iCloud, Fastmail…). Each person sees only
|
||||
// their own. Events are not stored: they are read from the source when
|
||||
// asked for and kept in memory for a while, so a journal opens fast and the
|
||||
// source is not asked on every page view.
|
||||
// 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.
|
||||
package calendar
|
||||
|
||||
import (
|
||||
@@ -30,6 +31,7 @@ import (
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/oauth"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
"docwell/server/internal/webhooks"
|
||||
)
|
||||
@@ -38,6 +40,7 @@ import (
|
||||
const (
|
||||
KindICS = "ics"
|
||||
KindCalDAV = "caldav"
|
||||
KindGoogle = "google"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -46,40 +49,56 @@ const (
|
||||
maxRange = 92
|
||||
// fetchTimeout caps one source fetch.
|
||||
fetchTimeout = 30 * time.Second
|
||||
// maxStored caps the occurrences kept per account.
|
||||
maxStored = 5000
|
||||
)
|
||||
|
||||
// The events kept: from windowBack days ago to windowAhead days ahead.
|
||||
const (
|
||||
windowBack = 90
|
||||
windowAhead = 400
|
||||
)
|
||||
|
||||
// GoogleAPI is where Google's APIs are (a variable for test builds).
|
||||
var GoogleAPI = "https://www.googleapis.com"
|
||||
|
||||
// Colours an account can have; the apps draw them from the theme.
|
||||
var colors = []string{"gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
|
||||
|
||||
// Options configure the service.
|
||||
type Options struct {
|
||||
// Secret seals the accounts' passwords (DOCWELL_SECRET_KEY).
|
||||
// Secret seals the accounts' passwords and tokens (DOCWELL_SECRET_KEY).
|
||||
Secret string
|
||||
// AllowLocal lets sources on loopback addresses through (development).
|
||||
AllowLocal bool
|
||||
// TTL is how long events stay in memory before the source is asked again (15 min).
|
||||
// TTL is how often each account is read again (15 min).
|
||||
TTL time.Duration
|
||||
// Client replaces the HTTP client (tests).
|
||||
Client *http.Client
|
||||
// Google is the OAuth app for Google Calendar; disabled when empty.
|
||||
Google oauth.Provider
|
||||
// States signs OAuth states. PublicURL is docwell-server's address (for
|
||||
// the OAuth callback), WebURL the web app's (where the callback returns).
|
||||
States *oauth.States
|
||||
PublicURL string
|
||||
WebURL string
|
||||
// GoogleAPI replaces https://www.googleapis.com (tests).
|
||||
GoogleAPI string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
pb *pocketbase.Client
|
||||
aead cipher.AEAD
|
||||
client *http.Client
|
||||
ttl time.Duration
|
||||
mu sync.Mutex
|
||||
cache map[string]*entry
|
||||
}
|
||||
|
||||
// entry is an account's last read: the iCalendar data and its parses by zone.
|
||||
type entry struct {
|
||||
mu sync.Mutex
|
||||
key string // what the data was read with; a change reads again
|
||||
at time.Time
|
||||
data []byte
|
||||
err error
|
||||
feeds map[string]*feed
|
||||
pb *pocketbase.Client
|
||||
aead cipher.AEAD
|
||||
client *http.Client
|
||||
ttl time.Duration
|
||||
google oauth.Provider
|
||||
states *oauth.States
|
||||
publicURL string
|
||||
webURL string
|
||||
googleAPI string
|
||||
// syncing holds the accounts being synced, so two syncs never overlap.
|
||||
mu sync.Mutex
|
||||
syncing map[string]bool
|
||||
}
|
||||
|
||||
func New(pb *pocketbase.Client, o Options) *Service {
|
||||
@@ -104,7 +123,19 @@ func New(pb *pocketbase.Client, o Options) *Service {
|
||||
if ttl <= 0 {
|
||||
ttl = 15 * time.Minute
|
||||
}
|
||||
return &Service{pb: pb, aead: aead, client: client, ttl: ttl, cache: map[string]*entry{}}
|
||||
api := strings.TrimRight(o.GoogleAPI, "/")
|
||||
if api == "" {
|
||||
api = GoogleAPI
|
||||
}
|
||||
states := o.States
|
||||
if states == nil {
|
||||
states = oauth.NewStates(o.Secret)
|
||||
}
|
||||
return &Service{
|
||||
pb: pb, aead: aead, client: client, ttl: ttl, google: o.Google, states: states,
|
||||
publicURL: strings.TrimRight(o.PublicURL, "/"), webURL: strings.TrimRight(o.WebURL, "/"), googleAPI: api,
|
||||
syncing: map[string]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) seal(plain string) string {
|
||||
@@ -179,8 +210,7 @@ func (r record) view() Account {
|
||||
}
|
||||
|
||||
// AccountInput creates an account, or changes the fields that are set. An
|
||||
// empty Password keeps the stored one when changing; Password "" with
|
||||
// ClearPassword removes it.
|
||||
// empty Password keeps the stored one when changing; ClearPassword removes it.
|
||||
type AccountInput struct {
|
||||
Name *string `json:"name"`
|
||||
Kind *string `json:"kind"`
|
||||
@@ -243,6 +273,9 @@ func (s *Service) patch(in AccountInput, old record) (map[string]any, record, er
|
||||
bad := func(field, msg string) (map[string]any, record, error) {
|
||||
return nil, record{}, apperr.InvalidFields(map[string]string{field: msg})
|
||||
}
|
||||
if old.Kind == KindGoogle && (in.Kind != nil || in.URL != nil || in.Username != nil || in.Password != nil || in.ClearPassword) {
|
||||
return bad("kind", "A Google account is changed by connecting it again.")
|
||||
}
|
||||
if in.Name != nil {
|
||||
name := strings.TrimSpace(*in.Name)
|
||||
if name == "" || len([]rune(name)) > 80 {
|
||||
@@ -252,16 +285,14 @@ func (s *Service) patch(in AccountInput, old record) (map[string]any, record, er
|
||||
}
|
||||
if in.Kind != nil {
|
||||
if *in.Kind != KindICS && *in.Kind != KindCalDAV {
|
||||
return bad("kind", "Kind must be ics or caldav.")
|
||||
return bad("kind", "Kind must be ics or caldav; Google accounts are connected with Connect Google.")
|
||||
}
|
||||
p["kind"], next.Kind = *in.Kind, *in.Kind
|
||||
}
|
||||
if in.URL != nil {
|
||||
u, err := feedURL(*in.URL)
|
||||
if err != nil || len(*in.URL) > 2000 {
|
||||
if _, err := feedURL(*in.URL); err != nil || len(*in.URL) > 2000 {
|
||||
return bad("url", "Enter an http, https or webcal address.")
|
||||
}
|
||||
_ = u
|
||||
v := strings.TrimSpace(*in.URL)
|
||||
p["url"], next.URL = v, v
|
||||
}
|
||||
@@ -295,7 +326,8 @@ func (s *Service) patch(in AccountInput, old record) (map[string]any, record, er
|
||||
}
|
||||
|
||||
// Create adds a calendar after reading it once, so a wrong address or
|
||||
// password is reported now rather than as an empty journal.
|
||||
// password is reported now rather than as an empty journal. Its events are
|
||||
// stored in the background.
|
||||
func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput) (Account, error) {
|
||||
if err := signedIn(c); err != nil {
|
||||
return Account{}, err
|
||||
@@ -322,19 +354,24 @@ func (s *Service) Create(ctx context.Context, c access.Caller, in AccountInput)
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
f, data, err := s.read(ctx, next)
|
||||
return s.add(ctx, c.ID, body, next)
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return Account{}, apperr.InvalidFields(map[string]string{"url": err.Error()})
|
||||
}
|
||||
body["user"] = c.ID
|
||||
body["user"] = user
|
||||
body["last_sync"] = pbTime(time.Now())
|
||||
body["last_error"] = ""
|
||||
body["events"] = f.count()
|
||||
body["events"] = count
|
||||
rec, err := pocketbase.Create[record](ctx, s.pb, "calendar_accounts", body)
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
s.store(rec, data)
|
||||
s.storeLater(rec, items)
|
||||
return rec.view(), nil
|
||||
}
|
||||
|
||||
@@ -351,43 +388,41 @@ func (s *Service) Update(ctx context.Context, c access.Caller, id string, in Acc
|
||||
if len(body) == 0 {
|
||||
return old.view(), nil
|
||||
}
|
||||
if sourceKey(next) != sourceKey(old) {
|
||||
f, data, err := s.read(ctx, next)
|
||||
if err != nil {
|
||||
var items []item
|
||||
changed := sourceKey(next) != sourceKey(old)
|
||||
if changed {
|
||||
var count int
|
||||
if items, count, 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()), "", f.count()
|
||||
s.store(next, data)
|
||||
body["last_sync"], body["last_error"], body["events"] = pbTime(time.Now()), "", count
|
||||
}
|
||||
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)
|
||||
}
|
||||
return rec.view(), nil
|
||||
}
|
||||
|
||||
// Delete removes a calendar.
|
||||
// Delete removes a calendar and its stored events.
|
||||
func (s *Service) Delete(ctx context.Context, c access.Caller, id string) error {
|
||||
r, err := s.get(ctx, c, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
delete(s.cache, r.ID)
|
||||
s.mu.Unlock()
|
||||
return s.pb.Delete(ctx, "calendar_accounts", r.ID)
|
||||
}
|
||||
|
||||
// Refresh reads a calendar from its source now.
|
||||
// Refresh reads a calendar from its source and stores its events now.
|
||||
func (s *Service) Refresh(ctx context.Context, c access.Caller, id string) (Account, error) {
|
||||
r, err := s.get(ctx, c, id)
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
delete(s.cache, r.ID)
|
||||
s.mu.Unlock()
|
||||
if _, err := s.feed(ctx, r, time.UTC); err != nil {
|
||||
if err := s.Sync(ctx, r); err != nil {
|
||||
slog.Debug("calendar refresh failed", "calendar", r.ID, "err", err)
|
||||
}
|
||||
r, err = s.get(ctx, c, id)
|
||||
@@ -400,25 +435,6 @@ func sourceKey(r record) string {
|
||||
return r.Kind + "\x00" + r.URL + "\x00" + r.Username + "\x00" + r.Secret
|
||||
}
|
||||
|
||||
// read fetches and parses a source (to check it).
|
||||
func (s *Service) read(ctx context.Context, r record) (*feed, []byte, error) {
|
||||
password, err := s.open(r.Secret)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
|
||||
defer cancel()
|
||||
data, err := fetch(ctx, s.client, source{kind: r.Kind, url: r.URL, username: r.Username, password: password})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
f, err := parseFeed(bytes.NewReader(data), time.UTC)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, data, nil
|
||||
}
|
||||
|
||||
func (f *feed) count() int {
|
||||
n := len(f.events)
|
||||
for _, o := range f.overrides {
|
||||
@@ -427,62 +443,221 @@ func (f *feed) count() int {
|
||||
return n
|
||||
}
|
||||
|
||||
func (s *Service) store(r record, data []byte) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if r.ID == "" {
|
||||
return
|
||||
}
|
||||
s.cache[r.ID] = &entry{key: sourceKey(r), at: time.Now(), data: data, feeds: map[string]*feed{}}
|
||||
// ---- Stored events -------------------------------------------------------------
|
||||
|
||||
// item is one occurrence as stored. Timed events have UTC instants;
|
||||
// all-day ones dates at 00:00 UTC (end exclusive).
|
||||
type item struct {
|
||||
key, title, location, url string
|
||||
allDay bool
|
||||
start, end time.Time
|
||||
}
|
||||
|
||||
// feed returns the account's events parsed in loc: from memory while fresh,
|
||||
// otherwise read again. A failed read keeps serving the last good data.
|
||||
func (s *Service) feed(ctx context.Context, r record, loc *time.Location) (*feed, error) {
|
||||
s.mu.Lock()
|
||||
e := s.cache[r.ID]
|
||||
if e == nil {
|
||||
e = &entry{feeds: map[string]*feed{}}
|
||||
s.cache[r.ID] = e
|
||||
}
|
||||
s.mu.Unlock()
|
||||
// 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())))
|
||||
return hex.EncodeToString(h[:12])
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
key := sourceKey(r)
|
||||
if e.key != key || time.Since(e.at) > s.ttl {
|
||||
_, data, err := s.read(ctx, r)
|
||||
e.at, e.err = time.Now(), err
|
||||
patch := map[string]any{"last_sync": pbTime(e.at), "last_error": ""}
|
||||
if err != nil {
|
||||
msg := err.Error()
|
||||
if len(msg) > 500 {
|
||||
msg = msg[:500]
|
||||
}
|
||||
patch["last_error"] = msg
|
||||
}
|
||||
if err == nil || e.key != key {
|
||||
e.data, e.key, e.feeds = data, key, map[string]*feed{}
|
||||
}
|
||||
if f, perr := parseFeed(bytes.NewReader(e.data), time.UTC); err == nil && perr == nil {
|
||||
patch["events"] = f.count()
|
||||
}
|
||||
if _, uerr := pocketbase.Update[record](context.WithoutCancel(ctx), s.pb, "calendar_accounts", r.ID, patch); uerr != nil {
|
||||
slog.Debug("calendar status not saved", "calendar", r.ID, "err", uerr)
|
||||
}
|
||||
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"`
|
||||
}
|
||||
|
||||
// window is the stretch of time stored for each account.
|
||||
func window(now time.Time) (time.Time, time.Time) {
|
||||
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
return day.AddDate(0, 0, -windowBack), day.AddDate(0, 0, windowAhead)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*fetchTimeout)
|
||||
defer cancel()
|
||||
from, to := window(time.Now())
|
||||
if r.Kind == KindGoogle {
|
||||
return s.googleItems(ctx, r, from, to)
|
||||
}
|
||||
if e.data == nil {
|
||||
return nil, e.err
|
||||
}
|
||||
if f := e.feeds[loc.String()]; f != nil {
|
||||
return f, nil
|
||||
}
|
||||
f, err := parseFeed(bytes.NewReader(e.data), loc)
|
||||
password, err := s.open(r.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
e.feeds[loc.String()] = f
|
||||
return f, nil
|
||||
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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
occ := f.between(from, to)
|
||||
items := make([]item, 0, len(occ))
|
||||
for _, o := range occ {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
return items, f.count(), nil
|
||||
}
|
||||
|
||||
// Sync reads an account and stores its events. A failed read keeps the
|
||||
// stored events and records why on the account.
|
||||
func (s *Service) Sync(ctx context.Context, r record) error {
|
||||
s.mu.Lock()
|
||||
if s.syncing[r.ID] {
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
s.syncing[r.ID] = true
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.syncing, r.ID)
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
|
||||
items, count, err := s.collect(ctx, r)
|
||||
patch := map[string]any{"last_sync": pbTime(time.Now()), "last_error": ""}
|
||||
if err != nil {
|
||||
msg := err.Error()
|
||||
if len(msg) > 500 {
|
||||
msg = msg[:500]
|
||||
}
|
||||
patch["last_error"] = msg
|
||||
} else {
|
||||
patch["events"] = count
|
||||
err = s.store(ctx, r, 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)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// storeLater stores a first read in the background, so adding a large
|
||||
// calendar does not wait on thousands of writes.
|
||||
func (s *Service) storeLater(r record, items []item) {
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
if err := s.store(ctx, r, items); err != nil {
|
||||
slog.Warn("calendar events not stored", "calendar", r.ID, "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// store makes the account's stored events match items.
|
||||
func (s *Service) store(ctx context.Context, r record, items []item) error {
|
||||
if len(items) > maxStored {
|
||||
items = items[:maxStored]
|
||||
}
|
||||
var have []eventRecord
|
||||
for page := 1; ; page++ {
|
||||
res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{
|
||||
Page: page, PerPage: 1000, Filter: fmt.Sprintf("account = '%s'", r.ID), Fields: "id,key,hash",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
have = append(have, res.Items...)
|
||||
if page >= res.TotalPages || len(res.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
old := make(map[string]eventRecord, len(have))
|
||||
for _, e := range have {
|
||||
if _, dup := old[e.Key]; dup {
|
||||
_ = s.pb.Delete(ctx, "calendar_events", e.ID)
|
||||
continue
|
||||
}
|
||||
old[e.Key] = e
|
||||
}
|
||||
seen := make(map[string]bool, len(items))
|
||||
for _, it := range items {
|
||||
if seen[it.key] {
|
||||
continue
|
||||
}
|
||||
seen[it.key] = true
|
||||
hash := it.hash()
|
||||
prev, ok := old[it.key]
|
||||
if ok && prev.Hash == 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),
|
||||
}
|
||||
if ok {
|
||||
if _, err := pocketbase.Update[eventRecord](ctx, s.pb, "calendar_events", prev.ID, body); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
body["account"], body["user"], body["key"] = r.ID, r.User, it.key
|
||||
if _, err := pocketbase.Create[eventRecord](ctx, s.pb, "calendar_events", body); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for key, e := range old {
|
||||
if !seen[key] {
|
||||
if err := s.pb.Delete(ctx, "calendar_events", e.ID); err != nil && !pocketbase.IsNotFound(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func clip(v string, n int) string {
|
||||
if len(v) <= n {
|
||||
return v
|
||||
}
|
||||
return strings.ToValidUTF8(v[:n], "")
|
||||
}
|
||||
|
||||
// SyncDue syncs every enabled account not read for a while (the
|
||||
// calendars.sync job).
|
||||
func (s *Service) SyncDue(ctx context.Context) error {
|
||||
cutoff := pbTime(time.Now().Add(-s.ttl))
|
||||
var due []record
|
||||
for page := 1; ; page++ {
|
||||
res, err := pocketbase.List[record](ctx, s.pb, "calendar_accounts", pocketbase.ListOptions{
|
||||
Page: page, PerPage: 500, Filter: fmt.Sprintf("enabled = true && (last_sync = '' || last_sync < '%s')", cutoff),
|
||||
Sort: "last_sync",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
due = append(due, res.Items...)
|
||||
if page >= res.TotalPages || len(res.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
failed := 0
|
||||
for _, r := range due {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := s.Sync(ctx, r); err != nil {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
if failed > 0 {
|
||||
slog.Info("calendars synced", "accounts", len(due), "failed", failed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- Events --------------------------------------------------------------------
|
||||
@@ -495,16 +670,20 @@ type Event struct {
|
||||
Location string `json:"location"`
|
||||
URL string `json:"url"`
|
||||
// Start and End are RFC 3339 times, or for all-day events dates
|
||||
// (YYYY-MM-DD, End exclusive) in the asked zone.
|
||||
// (YYYY-MM-DD, End exclusive).
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
AllDay bool `json:"allDay"`
|
||||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
// Events lists the caller's events from day from to day to (both
|
||||
func parsePB(v string) (time.Time, error) {
|
||||
return time.Parse("2006-01-02 15:04:05.000Z", v)
|
||||
}
|
||||
|
||||
// Events lists the caller's stored events from day from to day to (both
|
||||
// YYYY-MM-DD, inclusive) in zone tz (an IANA name; "" is UTC), from their
|
||||
// enabled calendars. A calendar that cannot be read is left out.
|
||||
// enabled calendars.
|
||||
func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz string) ([]Event, error) {
|
||||
if err := signedIn(c); err != nil {
|
||||
return nil, err
|
||||
@@ -517,58 +696,68 @@ func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz stri
|
||||
}
|
||||
loc = l
|
||||
}
|
||||
start, err1 := time.ParseInLocation(time.DateOnly, from, loc)
|
||||
end, err2 := time.ParseInLocation(time.DateOnly, to, loc)
|
||||
day1, err1 := time.Parse(time.DateOnly, from)
|
||||
day2, err2 := time.Parse(time.DateOnly, to)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, apperr.InvalidFields(map[string]string{"from": "Dates look like 2026-11-16."})
|
||||
}
|
||||
end = end.AddDate(0, 0, 1)
|
||||
if !end.After(start) || end.Sub(start) > maxRange*24*time.Hour {
|
||||
day2 = day2.AddDate(0, 0, 1)
|
||||
if !day2.After(day1) || day2.Sub(day1) > maxRange*24*time.Hour {
|
||||
return nil, apperr.InvalidFields(map[string]string{"to": fmt.Sprintf("Ask for at most %d days, ending after they start.", maxRange)})
|
||||
}
|
||||
// Timed events: the instants the days cover in loc. All-day events: the
|
||||
// dates themselves, stored at 00:00 UTC.
|
||||
start := time.Date(day1.Year(), day1.Month(), day1.Day(), 0, 0, 0, 0, loc)
|
||||
end := time.Date(day2.Year(), day2.Month(), day2.Day(), 0, 0, 0, 0, loc)
|
||||
rows, err := s.records(ctx, c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
out = []Event{}
|
||||
)
|
||||
color := map[string]string{}
|
||||
var ids []string
|
||||
for _, r := range rows {
|
||||
if !r.Enabled {
|
||||
continue
|
||||
if r.Enabled {
|
||||
color[r.ID] = r.Color
|
||||
ids = append(ids, fmt.Sprintf("account = '%s'", r.ID))
|
||||
}
|
||||
}
|
||||
out := []Event{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
filter := fmt.Sprintf("user = '%s' && (%s) && ((all_day = false && start_at < '%s' && end_at > '%s') || (all_day = true && start_at < '%s' && end_at > '%s'))",
|
||||
c.ID, strings.Join(ids, " || "), pbTime(end), pbTime(start), pbTime(day2), pbTime(day1))
|
||||
for page := 1; ; page++ {
|
||||
res, err := pocketbase.List[eventRecord](ctx, s.pb, "calendar_events", pocketbase.ListOptions{
|
||||
Page: page, PerPage: 500, Filter: filter, Sort: "start_at",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range res.Items {
|
||||
st, err1 := parsePB(e.StartAt)
|
||||
en, err2 := parsePB(e.EndAt)
|
||||
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)
|
||||
}
|
||||
if page >= res.TotalPages || len(res.Items) == 0 || len(out) >= 2000 {
|
||||
break
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(r record) {
|
||||
defer wg.Done()
|
||||
f, err := s.feed(ctx, r, loc)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
occ := f.between(start, end)
|
||||
list := make([]Event, 0, len(occ))
|
||||
for _, o := range occ {
|
||||
ev := Event{
|
||||
ID: eventID(r.ID, o), Calendar: r.ID, Title: o.def.title, Location: o.def.location,
|
||||
URL: safeLink(o.def.link), AllDay: o.def.allDay, Color: r.Color,
|
||||
}
|
||||
if ev.Title == "" {
|
||||
ev.Title = "(no title)"
|
||||
}
|
||||
if o.def.allDay {
|
||||
ev.Start, ev.End = o.start.In(loc).Format(time.DateOnly), o.end.In(loc).Format(time.DateOnly)
|
||||
} else {
|
||||
ev.Start, ev.End = o.start.UTC().Format(time.RFC3339), o.end.UTC().Format(time.RFC3339)
|
||||
}
|
||||
list = append(list, ev)
|
||||
}
|
||||
mu.Lock()
|
||||
out = append(out, list...)
|
||||
mu.Unlock()
|
||||
}(r)
|
||||
}
|
||||
wg.Wait()
|
||||
slices.SortStableFunc(out, func(a, b Event) int {
|
||||
if a.AllDay != b.AllDay {
|
||||
if a.AllDay {
|
||||
@@ -581,8 +770,8 @@ func (s *Service) Events(ctx context.Context, c access.Caller, from, to, tz stri
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func eventID(calendar string, o occurrence) string {
|
||||
h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d", calendar, o.def.uid, o.start.Unix())))
|
||||
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])
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package calendar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/oauth"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// ---- 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).
|
||||
|
||||
// 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"}
|
||||
|
||||
// GoogleEnabled reports whether the server has a Google OAuth app.
|
||||
func (s *Service) GoogleEnabled() bool { return s.google.Enabled() }
|
||||
|
||||
func (s *Service) googleRedirect() string { return s.publicURL + "/api/v1/oauth/google/callback" }
|
||||
|
||||
// GoogleConnectURL is where the caller signs in to Google to add their
|
||||
// calendars.
|
||||
func (s *Service) GoogleConnectURL(ctx context.Context, c access.Caller) (string, error) {
|
||||
if err := signedIn(c); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !s.google.Enabled() {
|
||||
return "", apperr.NotFound("Google sign-in is not set up on this server")
|
||||
}
|
||||
rows, err := s.records(ctx, c.ID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(rows) >= maxAccounts {
|
||||
return "", apperr.Invalid(fmt.Sprintf("you can add at most %d calendars", maxAccounts))
|
||||
}
|
||||
state := s.states.Sign(oauth.State{User: c.ID, Purpose: PurposeGoogle})
|
||||
return s.google.AuthCodeURL(state, s.googleRedirect(), googleScopes), nil
|
||||
}
|
||||
|
||||
// GoogleCallback finishes a sign-in: it stores the account (or replaces the
|
||||
// token of the same Google account) and returns where the browser goes next.
|
||||
func (s *Service) GoogleCallback(ctx context.Context, st oauth.State, code, providerErr string) string {
|
||||
done := func(err error) string {
|
||||
q := url.Values{"calendar": {"connected"}}
|
||||
if err != nil {
|
||||
q = url.Values{"calendarError": {err.Error()}}
|
||||
}
|
||||
return s.webURL + "/settings/account?" + q.Encode()
|
||||
}
|
||||
if providerErr != "" {
|
||||
return done(fmt.Errorf("the Google account was not connected (%s)", providerErr))
|
||||
}
|
||||
tok, err := s.google.Exchange(ctx, s.client, code, s.googleRedirect())
|
||||
if err != nil {
|
||||
return done(err)
|
||||
}
|
||||
if tok.RefreshToken == "" {
|
||||
return done(errors.New("no lasting access came from Google; remove Docwell from your Google account's third-party access and connect again"))
|
||||
}
|
||||
email, err := s.googleEmail(ctx, tok.AccessToken)
|
||||
if err != nil {
|
||||
return done(err)
|
||||
}
|
||||
rows, err := s.records(ctx, st.User)
|
||||
if err != nil {
|
||||
return done(err)
|
||||
}
|
||||
sealed := s.seal(tok.RefreshToken)
|
||||
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": ""})
|
||||
if err != nil {
|
||||
return done(err)
|
||||
}
|
||||
go func() { //nolint:gosec // the sync outlives the sign-in request on purpose
|
||||
if err := s.Sync(context.Background(), rec); err != nil {
|
||||
slog.Warn("google calendar sync failed", "calendar", rec.ID, "err", err)
|
||||
}
|
||||
}()
|
||||
return done(nil)
|
||||
}
|
||||
}
|
||||
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}
|
||||
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,
|
||||
}
|
||||
_, err = s.add(ctx, st.User, body, next)
|
||||
return done(err)
|
||||
}
|
||||
|
||||
// googleGet reads one Calendar API answer into out.
|
||||
func (s *Service) googleGet(ctx context.Context, access, path string, q url.Values, out any) error {
|
||||
u := s.googleAPI + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+access)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return friendly(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, maxFeed))
|
||||
if err != nil {
|
||||
return friendly(err)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &e)
|
||||
if e.Error.Message == "" {
|
||||
e.Error.Message = res.Status
|
||||
}
|
||||
return fmt.Errorf("the Google Calendar API answered: %s", e.Error.Message)
|
||||
}
|
||||
return json.Unmarshal(body, out)
|
||||
}
|
||||
|
||||
func (s *Service) googleEmail(ctx context.Context, access string) (string, error) {
|
||||
var info struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if err := s.googleGet(ctx, access, "/oauth2/v3/userinfo", nil, &info); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info.Email == "" {
|
||||
return "", errors.New("the Google sign-in did not say which account it was")
|
||||
}
|
||||
return info.Email, nil
|
||||
}
|
||||
|
||||
type googleTime struct {
|
||||
Date string `json:"date"`
|
||||
DateTime string `json:"dateTime"`
|
||||
}
|
||||
|
||||
func (t googleTime) parse() (time.Time, bool, error) {
|
||||
if t.Date != "" {
|
||||
d, err := time.Parse(time.DateOnly, t.Date)
|
||||
return d, true, err
|
||||
}
|
||||
d, err := time.Parse(time.RFC3339, t.DateTime)
|
||||
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) {
|
||||
refresh, err := s.open(r.Secret)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if refresh == "" {
|
||||
return nil, 0, oauth.ErrRevoked
|
||||
}
|
||||
tok, err := s.google.Refresh(ctx, s.client, refresh, nil)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
Selected bool `json:"selected"`
|
||||
Primary bool `json:"primary"`
|
||||
Hidden bool `json:"hidden"`
|
||||
} `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
|
||||
}
|
||||
var items []item
|
||||
for _, cal := range list.Items {
|
||||
if cal.Hidden || (!cal.Selected && !cal.Primary) {
|
||||
continue
|
||||
}
|
||||
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"`
|
||||
}
|
||||
if err := s.googleGet(ctx, tok.AccessToken, "/calendar/v3/calendars/"+url.PathEscape(cal.ID)+"/events", q, &res); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
for _, e := range res.Items {
|
||||
if e.Status == "cancelled" {
|
||||
continue
|
||||
}
|
||||
start, allDay, err1 := e.Start.parse()
|
||||
end, _, err2 := e.End.parse()
|
||||
if err1 != nil || err2 != nil {
|
||||
continue
|
||||
}
|
||||
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,
|
||||
})
|
||||
}
|
||||
if res.NextPageToken == "" || len(items) >= maxStored {
|
||||
break
|
||||
}
|
||||
q.Set("pageToken", res.NextPageToken)
|
||||
}
|
||||
}
|
||||
return items, len(items), nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package calendar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/oauth"
|
||||
)
|
||||
|
||||
func fakeGoogle(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("refresh_token") != "refresh-1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"access_token":"access-1","expires_in":3600}`))
|
||||
})
|
||||
auth := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer access-1" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("GET /calendar/v3/users/me/calendarList", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"items":[{"id":"me@example.com","primary":true},{"id":"team@group","selected":true},{"id":"hidden@group","selected":false}]}`))
|
||||
}))
|
||||
mux.HandleFunc("GET /calendar/v3/calendars/{id}/events", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("singleEvents") != "true" {
|
||||
t.Error("events asked without singleEvents")
|
||||
}
|
||||
switch r.PathValue("id") {
|
||||
case "me@example.com":
|
||||
if r.URL.Query().Get("pageToken") == "" {
|
||||
_, _ = w.Write([]byte(`{"items":[{"id":"e1","summary":"Lunch","start":{"dateTime":"2026-11-16T12:00:00+01:00"},"end":{"dateTime":"2026-11-16T13:00:00+01:00"},"htmlLink":"https://calendar.google.com/e1"},` +
|
||||
`{"id":"e2","status":"cancelled","start":{"date":"2026-11-16"},"end":{"date":"2026-11-17"}}],"nextPageToken":"p2"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"items":[{"id":"e3","summary":"Trip","start":{"date":"2026-11-20"},"end":{"date":"2026-11-23"}}]}`))
|
||||
case "team@group":
|
||||
_, _ = w.Write([]byte(`{"items":[{"id":"t1","summary":"Retro","location":"Room 1","start":{"dateTime":"2026-11-17T09:00:00Z"},"end":{"dateTime":"2026-11-17T10:00:00Z"}}]}`))
|
||||
default:
|
||||
t.Errorf("read a hidden calendar: %s", r.PathValue("id"))
|
||||
}
|
||||
}))
|
||||
return httptest.NewServer(mux)
|
||||
}
|
||||
|
||||
func TestGoogleItems(t *testing.T) {
|
||||
g := fakeGoogle(t)
|
||||
defer g.Close()
|
||||
s := New(nil, Options{
|
||||
Secret: "x", Client: g.Client(), GoogleAPI: g.URL,
|
||||
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)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 3 || len(items) != 3 {
|
||||
t.Fatalf("items = %+v", items)
|
||||
}
|
||||
byTitle := map[string]item{}
|
||||
for _, it := range items {
|
||||
byTitle[it.title] = it
|
||||
}
|
||||
if l := byTitle["Lunch"]; l.start != time.Date(2026, 11, 16, 11, 0, 0, 0, time.UTC) || l.allDay || l.url == "" {
|
||||
t.Errorf("lunch = %+v", l)
|
||||
}
|
||||
if tr := byTitle["Trip"]; !tr.allDay || tr.start.Format(time.DateOnly) != "2026-11-20" || tr.end.Format(time.DateOnly) != "2026-11-23" {
|
||||
t.Errorf("trip = %+v", tr)
|
||||
}
|
||||
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") {
|
||||
t.Errorf("revoked token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoogleConnectURL(t *testing.T) {
|
||||
s := New(nil, Options{Secret: "x", PublicURL: "https://api.example.com"})
|
||||
if _, err := s.GoogleConnectURL(context.Background(), access.Caller{ID: "u1"}); err == nil {
|
||||
t.Fatal("connect allowed without a Google app")
|
||||
}
|
||||
if s.GoogleEnabled() {
|
||||
t.Fatal("enabled without a Google app")
|
||||
}
|
||||
s.google = oauth.Google("client", "secret")
|
||||
// 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") {
|
||||
t.Errorf("auth url = %s", u)
|
||||
}
|
||||
if st, err := s.states.Verify(q.Get("state"), PurposeGoogle); err != nil || st.User != "u1" {
|
||||
t.Errorf("state = %+v, %v", st, err)
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,11 @@ type Config struct {
|
||||
// addresses (for development; off in production).
|
||||
WebhooksAllowLocal bool
|
||||
|
||||
// Google and Microsoft are OAuth apps people sign in to for Google
|
||||
// Calendar and OneNote imports; empty client ids turn those off.
|
||||
Google OAuthApp
|
||||
Microsoft OAuthApp
|
||||
|
||||
// PocketBase settings written on every start (settings.ApplyEnv). Empty
|
||||
// values leave the admin panel in charge.
|
||||
AppName string
|
||||
@@ -120,6 +125,12 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
|
||||
WebhooksAllowLocal: get("DOCWELL_WEBHOOKS_ALLOW_LOCAL", "false") == "true",
|
||||
}
|
||||
|
||||
cfg.Google = OAuthApp{ClientID: get("DOCWELL_GOOGLE_CLIENT_ID", ""), ClientSecret: get("DOCWELL_GOOGLE_CLIENT_SECRET", "")}
|
||||
cfg.Microsoft = OAuthApp{
|
||||
ClientID: get("DOCWELL_MICROSOFT_CLIENT_ID", ""), ClientSecret: get("DOCWELL_MICROSOFT_CLIENT_SECRET", ""),
|
||||
Tenant: get("DOCWELL_MICROSOFT_TENANT", "common"),
|
||||
}
|
||||
|
||||
cfg.AppName = get("DOCWELL_APP_NAME", "")
|
||||
cfg.MailFrom = get("DOCWELL_MAIL_FROM", "")
|
||||
cfg.SMTP = SMTP{
|
||||
@@ -203,3 +214,11 @@ func splitList(s string) []string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OAuthApp is an app registered with Google or Microsoft (Tenant: Microsoft
|
||||
// only; "common" lets any account sign in).
|
||||
type OAuthApp struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
Tenant string
|
||||
}
|
||||
@@ -54,66 +54,123 @@ func ReadReadwise(data []byte) ([]NotionPage, error) {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
pages := []NotionPage{{Title: "Readwise", Parent: -1}}
|
||||
byBook := map[string]int{}
|
||||
var books []*ReadwiseBook
|
||||
byBook := map[string]*ReadwiseBook{}
|
||||
for _, row := range rows[1:] {
|
||||
text := get(row, "highlight")
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
book := get(row, "book title")
|
||||
if book == "" {
|
||||
book = "Untitled"
|
||||
title := get(row, "book title")
|
||||
if title == "" {
|
||||
title = "Untitled"
|
||||
}
|
||||
i, ok := byBook[book]
|
||||
if !ok {
|
||||
if len(pages) > maxNotionPages {
|
||||
b := byBook[title]
|
||||
if b == nil {
|
||||
if len(books) >= maxNotionPages {
|
||||
break
|
||||
}
|
||||
i = len(pages)
|
||||
byBook[book] = i
|
||||
p := NotionPage{Title: book, Parent: 0, Doc: Node{Type: "doc"}}
|
||||
if a := get(row, "book author"); a != "" {
|
||||
p.Props = map[string]any{"Author": a}
|
||||
p.Doc.Content = append(p.Doc.Content, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: a, Marks: []Mark{{Type: "italic"}}}}})
|
||||
}
|
||||
for _, t := range strings.Split(get(row, "document tags"), ",") {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
p.Tags = append(p.Tags, t)
|
||||
}
|
||||
}
|
||||
pages = append(pages, p)
|
||||
b = &ReadwiseBook{Title: title, Author: get(row, "book author"), Tags: splitTags(get(row, "document tags"))}
|
||||
byBook[title] = b
|
||||
books = append(books, b)
|
||||
}
|
||||
p := &pages[i]
|
||||
p.Doc.Content = append(p.Doc.Content, Node{Type: "blockquote", Content: []Node{textParagraph(text, nil)}})
|
||||
if note := get(row, "note"); note != "" {
|
||||
p.Doc.Content = append(p.Doc.Content, textParagraph(note, nil))
|
||||
b.Highlights = append(b.Highlights, ReadwiseHighlight{
|
||||
Text: text, Note: get(row, "note"), Location: get(row, "location"), LocationType: get(row, "location type"),
|
||||
HighlightedAt: get(row, "highlighted at"), Tags: splitTags(get(row, "tags")),
|
||||
})
|
||||
}
|
||||
if len(books) == 0 {
|
||||
return nil, ErrNotNotion
|
||||
}
|
||||
pages := []NotionPage{{Title: "Readwise", Parent: -1, Doc: ReadwiseIndex()}}
|
||||
for _, b := range books {
|
||||
p := b.Page()
|
||||
p.Parent = 0
|
||||
pages = append(pages, p)
|
||||
}
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
func splitTags(v string) []string {
|
||||
var out []string
|
||||
for _, t := range strings.Split(v, ",") {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ReadwiseIndex is the document of the page that holds the books.
|
||||
func ReadwiseIndex() Node {
|
||||
return Node{Type: "doc", Content: []Node{textParagraph("Highlights imported from Readwise.", nil)}}
|
||||
}
|
||||
|
||||
// ReadwiseBook is a book, article or other document with its highlights,
|
||||
// from a Readwise CSV export or its API.
|
||||
type ReadwiseBook struct {
|
||||
Title, Author string
|
||||
// URL is where the document is (articles, tweets); "" for books.
|
||||
URL string
|
||||
Tags []string
|
||||
Highlights []ReadwiseHighlight
|
||||
}
|
||||
|
||||
// ReadwiseHighlight is one highlight. LocationType "order" (or "") reads as
|
||||
// a plain location.
|
||||
type ReadwiseHighlight struct {
|
||||
Text, Note, Location, LocationType, HighlightedAt string
|
||||
Tags []string
|
||||
}
|
||||
|
||||
// Page is the book's page: its author, then its highlights. Tags are the
|
||||
// document's tags, and the author is the "Author" property.
|
||||
func (b ReadwiseBook) Page() NotionPage {
|
||||
p := NotionPage{Title: b.Title, Parent: -1, Doc: Node{Type: "doc"}, Tags: b.Tags}
|
||||
if b.Author != "" {
|
||||
p.Props = map[string]any{"Author": b.Author}
|
||||
p.Doc.Content = append(p.Doc.Content, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: b.Author, Marks: []Mark{{Type: "italic"}}}}})
|
||||
}
|
||||
if strings.HasPrefix(b.URL, "https://") || strings.HasPrefix(b.URL, "http://") {
|
||||
p.Doc.Content = append(p.Doc.Content, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: b.URL, Marks: []Mark{{Type: "link", Attrs: map[string]any{
|
||||
"href": b.URL, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
|
||||
}}}}}})
|
||||
}
|
||||
p.Doc.Content = append(p.Doc.Content, ReadwiseNodes(b.Highlights)...)
|
||||
if len(p.Doc.Content) == 0 {
|
||||
p.Doc.Content = []Node{{Type: "paragraph"}}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// ReadwiseNodes are highlights as blocks: each a quote, its note, and a grey
|
||||
// line with its location, date and tags.
|
||||
func ReadwiseNodes(hs []ReadwiseHighlight) []Node {
|
||||
var out []Node
|
||||
for _, h := range hs {
|
||||
out = append(out, Node{Type: "blockquote", Content: []Node{textParagraph(h.Text, nil)}})
|
||||
if h.Note != "" {
|
||||
out = append(out, textParagraph(h.Note, nil))
|
||||
}
|
||||
var meta []string
|
||||
if loc := get(row, "location"); loc != "" {
|
||||
kind := get(row, "location type")
|
||||
if h.Location != "" {
|
||||
kind := h.LocationType
|
||||
if kind == "" || strings.EqualFold(kind, "order") {
|
||||
kind = "location"
|
||||
}
|
||||
meta = append(meta, kind+" "+loc)
|
||||
meta = append(meta, kind+" "+h.Location)
|
||||
}
|
||||
if at := get(row, "highlighted at"); len(at) >= 10 {
|
||||
meta = append(meta, at[:10])
|
||||
if len(h.HighlightedAt) >= 10 {
|
||||
meta = append(meta, h.HighlightedAt[:10])
|
||||
}
|
||||
for _, t := range strings.Split(get(row, "tags"), ",") {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
meta = append(meta, "#"+t)
|
||||
}
|
||||
for _, t := range h.Tags {
|
||||
meta = append(meta, "#"+t)
|
||||
}
|
||||
if len(meta) > 0 {
|
||||
p.Doc.Content = append(p.Doc.Content, textParagraph(strings.Join(meta, " · "), []Mark{{Type: "textColor", Attrs: map[string]any{"color": "gray"}}}))
|
||||
out = append(out, textParagraph(strings.Join(meta, " · "), []Mark{{Type: "textColor", Attrs: map[string]any{"color": "gray"}}}))
|
||||
}
|
||||
}
|
||||
if len(pages) == 1 {
|
||||
return nil, ErrNotNotion
|
||||
}
|
||||
pages[0].Doc = Node{Type: "doc", Content: []Node{textParagraph("Highlights imported from Readwise.", nil)}}
|
||||
return pages, nil
|
||||
return out
|
||||
}
|
||||
|
||||
// textParagraph is a paragraph of plain text; line breaks stay.
|
||||
|
||||
@@ -104,6 +104,19 @@ func (s *Service) getUser(ctx context.Context, id string) (auth.User, error) {
|
||||
return rec.User(), nil
|
||||
}
|
||||
|
||||
// CallerOf is the identity of user id, for work done on their behalf in the
|
||||
// background (Readwise syncs). Disabled accounts get an error.
|
||||
func (s *Service) CallerOf(ctx context.Context, id string) (access.Caller, error) {
|
||||
u, err := s.getUser(ctx, id)
|
||||
if err != nil {
|
||||
return access.Caller{}, err
|
||||
}
|
||||
if u.Status == "disabled" {
|
||||
return access.Caller{}, apperr.Forbidden("the account is disabled")
|
||||
}
|
||||
return u.Caller(), nil
|
||||
}
|
||||
|
||||
func target(u auth.User) access.Target {
|
||||
return access.Target{ID: u.ID, Role: u.Role, OrgID: u.Organization}
|
||||
}
|
||||
|
||||
@@ -189,6 +189,29 @@ func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, par
|
||||
batches = append(batches, b)
|
||||
}
|
||||
|
||||
return s.createBatches(ctx, c, a, parent, batches)
|
||||
}
|
||||
|
||||
// ImportConverted creates pages that were already read from another source
|
||||
// (a OneNote notebook) under parent ("" = top level) (editor), like
|
||||
// ImportPages does with files. Pages link to each other with
|
||||
// convert.PageRef and to assets with convert.AssetRef.
|
||||
func (s *Service) ImportConverted(ctx context.Context, c access.Caller, spaceID, parent string, pages []convert.NotionPage, assets []convert.Asset) ([]Page, error) {
|
||||
a, rules, err := s.spaceRules(ctx, c, spaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := access.CreatePageUnder(a.role, rules.role(parent), parent == ""); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pages) > maxImportPages {
|
||||
return nil, apperr.InvalidFields(map[string]string{"file": fmt.Sprintf("Import at most %d pages at once.", maxImportPages)})
|
||||
}
|
||||
return s.createBatches(ctx, c, a, parent, []importBatch{{pages: pages, assets: assets}})
|
||||
}
|
||||
|
||||
// createBatches makes the pages of read imports and returns the top ones.
|
||||
func (s *Service) createBatches(ctx context.Context, c access.Caller, a spaceAccess, parent string, batches []importBatch) ([]Page, error) {
|
||||
out := []Page{}
|
||||
meta := s.newImportMeta(c, a.space.Workspace)
|
||||
for _, b := range batches {
|
||||
|
||||
@@ -70,6 +70,9 @@ type api struct {
|
||||
push PushService
|
||||
ai AIService
|
||||
calendars CalendarService
|
||||
oauth OAuthCallbacks
|
||||
onenote OneNoteService
|
||||
readwise ReadwiseService
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
@@ -226,6 +229,7 @@ func (a *api) routes(mux *routeMux) {
|
||||
a.adminRoutes(mux)
|
||||
a.aiRoutes(mux)
|
||||
a.calendarRoutes(mux)
|
||||
a.integrationRoutes(mux)
|
||||
}
|
||||
|
||||
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
|
||||
@@ -19,6 +19,8 @@ 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)
|
||||
GoogleEnabled() bool
|
||||
GoogleConnectURL(ctx context.Context, c access.Caller) (string, error)
|
||||
}
|
||||
|
||||
var errNoCalendars = apperr.NotFound("calendars are not available on this server")
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/onenote"
|
||||
"docwell/server/internal/readwise"
|
||||
)
|
||||
|
||||
// OAuthCallbacks finishes sign-ins at Google and Microsoft: it returns where
|
||||
// the browser goes next.
|
||||
type OAuthCallbacks interface {
|
||||
Callback(ctx context.Context, q url.Values) string
|
||||
}
|
||||
|
||||
// OneNoteService imports OneNote notebooks through Microsoft Graph.
|
||||
type OneNoteService interface {
|
||||
Enabled() bool
|
||||
ConnectURL(c access.Caller, space, parent string) (string, error)
|
||||
Account(c access.Caller, connID string) (string, error)
|
||||
Notebooks(ctx context.Context, c access.Caller, connID string) ([]onenote.Notebook, error)
|
||||
Import(ctx context.Context, c access.Caller, connID, notebook, space, parent string) (onenote.Job, error)
|
||||
JobStatus(c access.Caller, id string) (onenote.Job, error)
|
||||
}
|
||||
|
||||
// ReadwiseService keeps people's Readwise highlights in Docwell.
|
||||
type ReadwiseService interface {
|
||||
Get(ctx context.Context, c access.Caller) (readwise.Connection, error)
|
||||
Save(ctx context.Context, c access.Caller, in readwise.Input) (readwise.Connection, error)
|
||||
Delete(ctx context.Context, c access.Caller) error
|
||||
SyncNow(ctx context.Context, c access.Caller) (readwise.Connection, error)
|
||||
}
|
||||
|
||||
// Integrations says which outside services this server can reach for people.
|
||||
type Integrations struct {
|
||||
// Google is set when people can connect Google Calendar.
|
||||
Google bool `json:"google"`
|
||||
// Microsoft is set when people can import OneNote notebooks.
|
||||
Microsoft bool `json:"microsoft"`
|
||||
// Readwise is set when Readwise highlights can be synced.
|
||||
Readwise bool `json:"readwise"`
|
||||
}
|
||||
|
||||
var errNoIntegration = apperr.NotFound("this integration is not available on this server")
|
||||
|
||||
func (a *api) integrationRoutes(mux *routeMux) {
|
||||
mux.HandleFunc("GET /api/v1/integrations", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
v := Integrations{Readwise: a.readwise != nil}
|
||||
if a.calendars != nil {
|
||||
v.Google = a.calendars.GoogleEnabled()
|
||||
}
|
||||
if a.onenote != nil {
|
||||
v.Microsoft = a.onenote.Enabled()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, v)
|
||||
}))
|
||||
|
||||
// The providers send the browser back here; the signed state says who
|
||||
// asked and for what, so this route needs no session.
|
||||
mux.HandleFunc("GET /api/v1/oauth/{provider}/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
if a.oauth == nil {
|
||||
a.writeError(w, errNoIntegration)
|
||||
return
|
||||
}
|
||||
switch r.PathValue("provider") {
|
||||
case "google", "microsoft":
|
||||
default:
|
||||
a.writeError(w, apperr.NotFound("not found"))
|
||||
return
|
||||
}
|
||||
// The target is built by the server from DOCWELL_WEB_URL, never taken from the request.
|
||||
http.Redirect(w, r, a.oauth.Callback(r.Context(), r.URL.Query()), http.StatusFound) //nolint:gosec // see above
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /api/v1/calendars/google/connect", a.withCalendars(func(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := a.calendars.GoogleConnectURL(r.Context(), caller(r))
|
||||
a.respond(w, map[string]string{"url": u}, err)
|
||||
}))
|
||||
|
||||
withOneNote := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
if a.onenote == nil || !a.onenote.Enabled() {
|
||||
a.writeError(w, errNoIntegration)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("GET /api/v1/onenote/connect", withOneNote(func(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := a.onenote.ConnectURL(caller(r), r.URL.Query().Get("space"), r.URL.Query().Get("parent"))
|
||||
a.respond(w, map[string]string{"url": u}, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/onenote/connections/{id}", withOneNote(func(w http.ResponseWriter, r *http.Request) {
|
||||
email, err := a.onenote.Account(caller(r), r.PathValue("id"))
|
||||
if err != nil {
|
||||
a.writeError(w, err)
|
||||
return
|
||||
}
|
||||
nbs, err := a.onenote.Notebooks(r.Context(), caller(r), r.PathValue("id"))
|
||||
a.respond(w, map[string]any{"account": email, "notebooks": nbs}, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/onenote/connections/{id}/import", withOneNote(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Notebook string `json:"notebook"`
|
||||
Space string `json:"space"`
|
||||
Parent string `json:"parent"`
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
job, err := a.onenote.Import(r.Context(), caller(r), r.PathValue("id"), in.Notebook, in.Space, in.Parent)
|
||||
a.respondStatus(w, http.StatusAccepted, job, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/onenote/jobs/{id}", withOneNote(func(w http.ResponseWriter, r *http.Request) {
|
||||
job, err := a.onenote.JobStatus(caller(r), r.PathValue("id"))
|
||||
a.respond(w, job, err)
|
||||
}))
|
||||
|
||||
withReadwise := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
if a.readwise == nil {
|
||||
a.writeError(w, errNoIntegration)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("GET /api/v1/readwise", withReadwise(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.readwise.Get(r.Context(), caller(r))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/readwise", withReadwise(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in readwise.Input
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
v, err := a.readwise.Save(r.Context(), caller(r), in)
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/v1/readwise", withReadwise(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.readwise.Delete(r.Context(), caller(r)))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/readwise/sync", withReadwise(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.readwise.SyncNow(r.Context(), caller(r))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
}
|
||||
@@ -44,8 +44,13 @@ type Deps struct {
|
||||
AI AIService
|
||||
// Calendars reads people's calendars for their journals; nil turns them off.
|
||||
Calendars CalendarService
|
||||
Admin http.Handler
|
||||
Log *slog.Logger
|
||||
// OAuth finishes Google and Microsoft sign-ins; OneNote and Readwise
|
||||
// import and sync. nil turns each off.
|
||||
OAuth OAuthCallbacks
|
||||
OneNote OneNoteService
|
||||
Readwise ReadwiseService
|
||||
Admin http.Handler
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// routeMux is a ServeMux that remembers its patterns, so a test can compare
|
||||
@@ -86,6 +91,15 @@ func newMux(d Deps) *routeMux {
|
||||
if d.Calendars != nil {
|
||||
a.calendars = d.Calendars
|
||||
}
|
||||
if d.OAuth != nil {
|
||||
a.oauth = d.OAuth
|
||||
}
|
||||
if d.OneNote != nil {
|
||||
a.onenote = d.OneNote
|
||||
}
|
||||
if d.Readwise != nil {
|
||||
a.readwise = d.Readwise
|
||||
}
|
||||
a.routes(mux)
|
||||
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
|
||||
a.collabRoute(mux, d.CORSOrigins)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package oauth signs people in to Google and Microsoft for the services
|
||||
// Docwell reads on their behalf (Google Calendar, OneNote): the
|
||||
// authorization-code flow of a confidential client, with a signed state
|
||||
// that carries who asked and why, and token refresh.
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Provider is an OAuth app at one identity provider.
|
||||
type Provider struct {
|
||||
// Name is how routes and states name it ("google", "microsoft").
|
||||
Name string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
AuthURL string
|
||||
TokenURL string
|
||||
// Extra goes into the authorization URL (access_type=offline, prompt=…).
|
||||
Extra url.Values
|
||||
}
|
||||
|
||||
// Enabled reports whether the app is configured.
|
||||
func (p Provider) Enabled() bool { return p.ClientID != "" && p.ClientSecret != "" }
|
||||
|
||||
// The providers' sign-in endpoints. Variables only so a test build can
|
||||
// point them at a stand-in (go build -ldflags "-X …").
|
||||
var (
|
||||
GoogleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
GoogleTokenURL = "https://oauth2.googleapis.com/token"
|
||||
MicrosoftLogin = "https://login.microsoftonline.com"
|
||||
)
|
||||
|
||||
// Google is Google's OAuth endpoints for app id and secret.
|
||||
func Google(id, secret string) Provider {
|
||||
return Provider{ //nolint:gosec // endpoints, not credentials
|
||||
Name: "google", ClientID: id, ClientSecret: secret,
|
||||
AuthURL: GoogleAuthURL,
|
||||
TokenURL: GoogleTokenURL,
|
||||
// A refresh token every time, so a reconnect replaces a revoked one.
|
||||
Extra: url.Values{"access_type": {"offline"}, "prompt": {"consent"}, "include_granted_scopes": {"true"}},
|
||||
}
|
||||
}
|
||||
|
||||
// Microsoft is the Microsoft identity platform (v2) for tenant ("common"
|
||||
// for any work, school or personal account).
|
||||
func Microsoft(id, secret, tenant string) Provider {
|
||||
if tenant == "" {
|
||||
tenant = "common"
|
||||
}
|
||||
base := MicrosoftLogin + "/" + url.PathEscape(tenant) + "/oauth2/v2.0"
|
||||
return Provider{
|
||||
Name: "microsoft", ClientID: id, ClientSecret: secret,
|
||||
AuthURL: base + "/authorize", TokenURL: base + "/token",
|
||||
Extra: url.Values{"prompt": {"select_account"}},
|
||||
}
|
||||
}
|
||||
|
||||
// AuthCodeURL is where the browser goes to sign in and allow scopes.
|
||||
func (p Provider) AuthCodeURL(state, redirect string, scopes []string) string {
|
||||
q := url.Values{
|
||||
"client_id": {p.ClientID}, "redirect_uri": {redirect}, "response_type": {"code"},
|
||||
"scope": {strings.Join(scopes, " ")}, "state": {state},
|
||||
}
|
||||
for k, v := range p.Extra {
|
||||
q[k] = v
|
||||
}
|
||||
return p.AuthURL + "?" + q.Encode()
|
||||
}
|
||||
|
||||
// Token is what the token endpoint answers.
|
||||
type Token struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
IDToken string `json:"id_token"`
|
||||
Scope string `json:"scope"`
|
||||
// Expires is when AccessToken stops working (set by Exchange and Refresh).
|
||||
Expires time.Time `json:"-"`
|
||||
}
|
||||
|
||||
// ErrRevoked is returned when the provider refuses a refresh token: the
|
||||
// person removed Docwell's access, or it expired.
|
||||
var ErrRevoked = errors.New("the sign-in was revoked or expired; connect the account again")
|
||||
|
||||
func (p Provider) token(ctx context.Context, client *http.Client, form url.Values) (Token, error) {
|
||||
form.Set("client_id", p.ClientID)
|
||||
form.Set("client_secret", p.ClientSecret)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.TokenURL, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return Token{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return Token{}, fmt.Errorf("%s did not answer: %w", p.Name, err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
body, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Error string `json:"error"`
|
||||
Description string `json:"error_description"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &e)
|
||||
if e.Error == "invalid_grant" {
|
||||
return Token{}, ErrRevoked
|
||||
}
|
||||
msg := e.Description
|
||||
if msg == "" {
|
||||
msg = e.Error
|
||||
}
|
||||
if msg == "" {
|
||||
msg = res.Status
|
||||
}
|
||||
return Token{}, fmt.Errorf("%s refused the sign-in: %s", p.Name, msg)
|
||||
}
|
||||
var t Token
|
||||
if err := json.Unmarshal(body, &t); err != nil || t.AccessToken == "" {
|
||||
return Token{}, fmt.Errorf("%s answered without a token", p.Name)
|
||||
}
|
||||
t.Expires = time.Now().Add(time.Duration(max(t.ExpiresIn-60, 30)) * time.Second)
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Exchange trades the code from the callback for tokens.
|
||||
func (p Provider) Exchange(ctx context.Context, client *http.Client, code, redirect string) (Token, error) {
|
||||
return p.token(ctx, client, url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {redirect}})
|
||||
}
|
||||
|
||||
// Refresh gets a new access token. Microsoft may send a new refresh token,
|
||||
// which replaces the old one.
|
||||
func (p Provider) Refresh(ctx context.Context, client *http.Client, refresh string, scopes []string) (Token, error) {
|
||||
form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}}
|
||||
if len(scopes) > 0 && p.Name == "microsoft" {
|
||||
form.Set("scope", strings.Join(scopes, " "))
|
||||
}
|
||||
t, err := p.token(ctx, client, form)
|
||||
if err == nil && t.RefreshToken == "" {
|
||||
t.RefreshToken = refresh
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
// ---- State ------------------------------------------------------------------------
|
||||
|
||||
// State travels through the provider and back to the callback: who asked,
|
||||
// for what (Purpose), and what to do after (Data). It is signed, so the
|
||||
// callback trusts it, and short-lived.
|
||||
type State struct {
|
||||
User string `json:"u"`
|
||||
Purpose string `json:"p"`
|
||||
Data map[string]string `json:"d,omitempty"`
|
||||
Expires int64 `json:"e"`
|
||||
Nonce string `json:"n"`
|
||||
}
|
||||
|
||||
// States signs and checks states with a server secret.
|
||||
type States struct{ key []byte }
|
||||
|
||||
func NewStates(secret string) *States {
|
||||
k := sha256.Sum256([]byte("docwell-oauth-state:" + secret))
|
||||
return &States{key: k[:]}
|
||||
}
|
||||
|
||||
// Sign returns s as a URL-safe string valid for 15 minutes.
|
||||
func (st *States) Sign(s State) string {
|
||||
var nonce [12]byte
|
||||
_, _ = rand.Read(nonce[:])
|
||||
s.Nonce = base64.RawURLEncoding.EncodeToString(nonce[:])
|
||||
s.Expires = time.Now().Add(15 * time.Minute).Unix()
|
||||
raw, _ := json.Marshal(s)
|
||||
payload := base64.RawURLEncoding.EncodeToString(raw)
|
||||
return payload + "." + st.mac(payload)
|
||||
}
|
||||
|
||||
func (st *States) mac(payload string) string {
|
||||
m := hmac.New(sha256.New, st.key)
|
||||
m.Write([]byte(payload))
|
||||
return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
// ErrBadState is a state that was changed, is too old, or was made for
|
||||
// something else.
|
||||
var ErrBadState = errors.New("the sign-in link is invalid or too old; start again")
|
||||
|
||||
// Verify checks a state made for purpose.
|
||||
func (st *States) Verify(raw, purpose string) (State, error) {
|
||||
payload, sig, ok := strings.Cut(raw, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(st.mac(payload))) {
|
||||
return State{}, ErrBadState
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return State{}, ErrBadState
|
||||
}
|
||||
var s State
|
||||
if json.Unmarshal(data, &s) != nil || s.Purpose != purpose || s.User == "" || time.Now().Unix() > s.Expires {
|
||||
return State{}, ErrBadState
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Peek reads a verified state's purpose without knowing it first (the
|
||||
// callback routes by it).
|
||||
func (st *States) Peek(raw string) (State, error) {
|
||||
payload, _, _ := strings.Cut(raw, ".")
|
||||
data, err := base64.RawURLEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return State{}, ErrBadState
|
||||
}
|
||||
var s State
|
||||
if json.Unmarshal(data, &s) != nil {
|
||||
return State{}, ErrBadState
|
||||
}
|
||||
return st.Verify(raw, s.Purpose)
|
||||
}
|
||||
|
||||
// ---- Callback routing -----------------------------------------------------------------
|
||||
|
||||
// Handler finishes a sign-in made for one purpose and returns where the
|
||||
// browser goes next.
|
||||
type Handler func(ctx context.Context, st State, code, providerErr string) string
|
||||
|
||||
// Router sends a provider's callback to the handler its state names.
|
||||
type Router struct {
|
||||
states *States
|
||||
handlers map[string]Handler
|
||||
fallback string
|
||||
}
|
||||
|
||||
// NewRouter routes callbacks; a state that does not check out goes to
|
||||
// fallback (the web app) with oauthError set.
|
||||
func NewRouter(states *States, fallback string) *Router {
|
||||
return &Router{states: states, handlers: map[string]Handler{}, fallback: strings.TrimRight(fallback, "/")}
|
||||
}
|
||||
|
||||
// Handle registers the handler for purpose.
|
||||
func (r *Router) Handle(purpose string, h Handler) { r.handlers[purpose] = h }
|
||||
|
||||
// Callback handles the query a provider redirects back with.
|
||||
func (r *Router) Callback(ctx context.Context, q url.Values) string {
|
||||
st, err := r.states.Peek(q.Get("state"))
|
||||
h := r.handlers[st.Purpose]
|
||||
if err != nil || h == nil {
|
||||
if err == nil {
|
||||
err = ErrBadState
|
||||
}
|
||||
return r.fallback + "/?" + url.Values{"oauthError": {err.Error()}}.Encode()
|
||||
}
|
||||
return h(ctx, st, q.Get("code"), q.Get("error"))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStates(t *testing.T) {
|
||||
st := NewStates("secret")
|
||||
raw := st.Sign(State{User: "u1", Purpose: "google-calendar", Data: map[string]string{"x": "1"}})
|
||||
s, err := st.Verify(raw, "google-calendar")
|
||||
if err != nil || s.User != "u1" || s.Data["x"] != "1" {
|
||||
t.Fatalf("verify = %+v, %v", s, err)
|
||||
}
|
||||
if p, err := st.Peek(raw); err != nil || p.Purpose != "google-calendar" {
|
||||
t.Fatalf("peek = %+v, %v", p, err)
|
||||
}
|
||||
if _, err := st.Verify(raw, "onenote"); !errors.Is(err, ErrBadState) {
|
||||
t.Error("state accepted for another purpose")
|
||||
}
|
||||
if _, err := NewStates("other").Verify(raw, "google-calendar"); !errors.Is(err, ErrBadState) {
|
||||
t.Error("state accepted with another secret")
|
||||
}
|
||||
tampered := "x" + raw
|
||||
if _, err := st.Peek(tampered); err == nil {
|
||||
t.Error("tampered state accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExchangeAndRefresh(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("client_secret") != "s" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Form.Get("grant_type") {
|
||||
case "authorization_code":
|
||||
if r.Form.Get("code") != "good" || r.Form.Get("redirect_uri") != "https://d/cb" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_request","error_description":"bad code"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"access_token":"a1","refresh_token":"r1","expires_in":3600}`))
|
||||
case "refresh_token":
|
||||
if r.Form.Get("refresh_token") != "r1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"access_token":"a2","expires_in":3600}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{Name: "test", ClientID: "c", ClientSecret: "s", AuthURL: "https://auth/x", TokenURL: srv.URL}
|
||||
ctx := context.Background()
|
||||
tok, err := p.Exchange(ctx, srv.Client(), "good", "https://d/cb")
|
||||
if err != nil || tok.AccessToken != "a1" || tok.RefreshToken != "r1" {
|
||||
t.Fatalf("exchange = %+v, %v", tok, err)
|
||||
}
|
||||
if _, err := p.Exchange(ctx, srv.Client(), "bad", "https://d/cb"); err == nil || !strings.Contains(err.Error(), "bad code") {
|
||||
t.Fatalf("bad code: %v", err)
|
||||
}
|
||||
tok, err = p.Refresh(ctx, srv.Client(), "r1", nil)
|
||||
if err != nil || tok.AccessToken != "a2" || tok.RefreshToken != "r1" {
|
||||
t.Fatalf("refresh = %+v, %v", tok, err)
|
||||
}
|
||||
if _, err := p.Refresh(ctx, srv.Client(), "gone", nil); !errors.Is(err, ErrRevoked) {
|
||||
t.Fatalf("revoked = %v", err)
|
||||
}
|
||||
u, _ := url.Parse(Google("id", "sec").AuthCodeURL("st", "https://d/cb", []string{"a", "b"}))
|
||||
if q := u.Query(); q.Get("scope") != "a b" || q.Get("access_type") != "offline" || q.Get("state") != "st" {
|
||||
t.Errorf("auth url = %s", u)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package onenote imports whole OneNote notebooks through Microsoft Graph
|
||||
// (Phase F, ADR-16). A person signs in to Microsoft (Notes.Read), picks a
|
||||
// notebook, and the import runs in the background: the notebook, its
|
||||
// section groups and sections become pages, each OneNote page a page under
|
||||
// its section (subpages under their parent page), with images and attached
|
||||
// files stored as attachments. The sign-in is kept in memory for an hour,
|
||||
// only for the import; Docwell keeps no Microsoft tokens.
|
||||
package onenote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/oauth"
|
||||
"docwell/server/internal/webhooks"
|
||||
)
|
||||
|
||||
// Purpose names the OAuth state of a OneNote sign-in.
|
||||
const Purpose = "onenote"
|
||||
|
||||
var scopes = []string{"offline_access", "openid", "email", "User.Read", "Notes.Read"}
|
||||
|
||||
const (
|
||||
connectionTTL = time.Hour
|
||||
maxPages = 2000
|
||||
maxResource = 50 << 20
|
||||
maxResources = 512 << 20
|
||||
)
|
||||
|
||||
// Importer is the part of directory.Service an import needs.
|
||||
type Importer interface {
|
||||
ImportConverted(ctx context.Context, c access.Caller, spaceID, parent string, pages []convert.NotionPage, assets []convert.Asset) ([]directory.Page, error)
|
||||
}
|
||||
|
||||
// Options configure the service.
|
||||
type Options struct {
|
||||
Provider oauth.Provider
|
||||
States *oauth.States
|
||||
PublicURL string
|
||||
WebURL string
|
||||
// Graph replaces https://graph.microsoft.com/v1.0 (tests).
|
||||
Graph string
|
||||
// Client replaces the HTTP client (tests).
|
||||
Client *http.Client
|
||||
// AllowLocal lets requests reach loopback addresses (development).
|
||||
AllowLocal bool
|
||||
}
|
||||
|
||||
// Graph is Microsoft Graph (a variable for test builds).
|
||||
var Graph = "https://graph.microsoft.com/v1.0"
|
||||
|
||||
type Service struct {
|
||||
o Options
|
||||
dir Importer
|
||||
client *http.Client
|
||||
graph string
|
||||
mu sync.Mutex
|
||||
conns map[string]*connection
|
||||
jobs map[string]*Job
|
||||
}
|
||||
|
||||
type connection struct {
|
||||
user string
|
||||
email string
|
||||
token oauth.Token
|
||||
refresh string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Job is an import running in the background.
|
||||
type Job struct {
|
||||
ID string `json:"id"`
|
||||
Notebook string `json:"notebook"`
|
||||
// Status is running, done or failed.
|
||||
Status string `json:"status"`
|
||||
// Pages counts the OneNote pages read so far.
|
||||
Pages int `json:"pages"`
|
||||
Error string `json:"error"`
|
||||
// Created lists the pages made at the top (the notebook's page).
|
||||
Created []directory.Page `json:"created"`
|
||||
user string
|
||||
ended time.Time
|
||||
}
|
||||
|
||||
// Notebook is a notebook the signed-in Microsoft account can read.
|
||||
type Notebook struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Modified string `json:"modified"`
|
||||
}
|
||||
|
||||
func New(dir Importer, o Options) *Service {
|
||||
client := o.Client
|
||||
if client == nil {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)}
|
||||
client = &http.Client{Timeout: 2 * time.Minute, Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment}}
|
||||
}
|
||||
graph := strings.TrimRight(o.Graph, "/")
|
||||
if graph == "" {
|
||||
graph = Graph
|
||||
}
|
||||
o.PublicURL = strings.TrimRight(o.PublicURL, "/")
|
||||
o.WebURL = strings.TrimRight(o.WebURL, "/")
|
||||
return &Service{o: o, dir: dir, client: client, graph: graph, conns: map[string]*connection{}, jobs: map[string]*Job{}}
|
||||
}
|
||||
|
||||
// Enabled reports whether the server has a Microsoft OAuth app.
|
||||
func (s *Service) Enabled() bool { return s.o.Provider.Enabled() }
|
||||
|
||||
func (s *Service) redirect() string { return s.o.PublicURL + "/api/v1/oauth/microsoft/callback" }
|
||||
|
||||
func newID() string {
|
||||
var b [12]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// ConnectURL is where the caller signs in to Microsoft; afterwards the
|
||||
// browser returns to the space (?onenote=<connection>).
|
||||
func (s *Service) ConnectURL(c access.Caller, space, parent string) (string, error) {
|
||||
if c.ID == "" {
|
||||
return "", apperr.NotFound("not found")
|
||||
}
|
||||
if !s.Enabled() {
|
||||
return "", apperr.NotFound("Microsoft sign-in is not set up on this server")
|
||||
}
|
||||
if space == "" || len(space) > 64 || len(parent) > 64 {
|
||||
return "", apperr.InvalidFields(map[string]string{"space": "Choose the space to import into."})
|
||||
}
|
||||
state := s.o.States.Sign(oauth.State{User: c.ID, Purpose: Purpose, Data: map[string]string{"space": space, "parent": parent}})
|
||||
return s.o.Provider.AuthCodeURL(state, s.redirect(), scopes), nil
|
||||
}
|
||||
|
||||
// Callback finishes the sign-in and returns where the browser goes next.
|
||||
func (s *Service) Callback(ctx context.Context, st oauth.State, code, providerErr string) string {
|
||||
space := st.Data["space"]
|
||||
back := func(q url.Values) string {
|
||||
if p := st.Data["parent"]; p != "" {
|
||||
q.Set("onenoteParent", p)
|
||||
}
|
||||
return s.o.WebURL + "/s/" + url.PathEscape(space) + "?" + q.Encode()
|
||||
}
|
||||
if providerErr != "" {
|
||||
return back(url.Values{"onenoteError": {"Microsoft did not connect the account (" + providerErr + ")"}})
|
||||
}
|
||||
tok, err := s.o.Provider.Exchange(ctx, s.client, code, s.redirect())
|
||||
if err != nil {
|
||||
return back(url.Values{"onenoteError": {err.Error()}})
|
||||
}
|
||||
conn := &connection{user: st.User, token: tok, refresh: tok.RefreshToken, expires: time.Now().Add(connectionTTL)}
|
||||
var me struct {
|
||||
Mail string `json:"mail"`
|
||||
UserPrincipalName string `json:"userPrincipalName"`
|
||||
}
|
||||
if err := s.get(ctx, conn, s.graph+"/me?$select=mail,userPrincipalName", &me); err == nil {
|
||||
conn.email = me.Mail
|
||||
if conn.email == "" {
|
||||
conn.email = me.UserPrincipalName
|
||||
}
|
||||
}
|
||||
id := newID()
|
||||
s.mu.Lock()
|
||||
s.sweepLocked()
|
||||
s.conns[id] = conn
|
||||
s.mu.Unlock()
|
||||
return back(url.Values{"onenote": {id}})
|
||||
}
|
||||
|
||||
func (s *Service) sweepLocked() {
|
||||
now := time.Now()
|
||||
for id, c := range s.conns {
|
||||
if now.After(c.expires) {
|
||||
delete(s.conns, id)
|
||||
}
|
||||
}
|
||||
for id, j := range s.jobs {
|
||||
if !j.ended.IsZero() && now.Sub(j.ended) > connectionTTL {
|
||||
delete(s.jobs, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) connection(c access.Caller, id string) (*connection, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
conn := s.conns[id]
|
||||
if conn == nil || conn.user != c.ID || time.Now().After(conn.expires) {
|
||||
return nil, apperr.NotFound("the Microsoft sign-in has expired; connect again")
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// ---- Graph -------------------------------------------------------------------------
|
||||
|
||||
var errThrottled = errors.New("the Microsoft Graph API is busy; try again later")
|
||||
|
||||
// do sends one Graph request, refreshing the token and waiting out
|
||||
// throttling. A nil out returns the body.
|
||||
func (s *Service) do(ctx context.Context, conn *connection, u string, out any) ([]byte, error) {
|
||||
for attempt := 0; ; attempt++ {
|
||||
if time.Now().After(conn.token.Expires) && conn.refresh != "" {
|
||||
tok, err := s.o.Provider.Refresh(ctx, s.client, conn.refresh, scopes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn.token, conn.refresh = tok, tok.RefreshToken
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+conn.token.AccessToken)
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the Microsoft Graph API did not answer: %w", err)
|
||||
}
|
||||
if res.StatusCode == http.StatusTooManyRequests || res.StatusCode == http.StatusServiceUnavailable {
|
||||
_ = res.Body.Close()
|
||||
if attempt >= 5 {
|
||||
return nil, errThrottled
|
||||
}
|
||||
wait := time.Duration(1<<attempt) * time.Second
|
||||
if sec, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && sec > 0 {
|
||||
wait = time.Duration(min(sec, 60)) * time.Second
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(wait):
|
||||
}
|
||||
continue
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, maxResource+1))
|
||||
_ = res.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &e)
|
||||
if e.Error.Message == "" {
|
||||
e.Error.Message = res.Status
|
||||
}
|
||||
return nil, fmt.Errorf("the Microsoft Graph API answered: %s", e.Error.Message)
|
||||
}
|
||||
if len(body) > maxResource {
|
||||
return nil, errors.New("a file in the notebook is larger than 50 MB")
|
||||
}
|
||||
if out != nil {
|
||||
return body, json.Unmarshal(body, out)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) get(ctx context.Context, conn *connection, u string, out any) error {
|
||||
_, err := s.do(ctx, conn, u, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// list reads every page of a Graph collection.
|
||||
func list[T any](ctx context.Context, s *Service, conn *connection, u string) ([]T, error) {
|
||||
var all []T
|
||||
for u != "" && len(all) < 10000 {
|
||||
var res struct {
|
||||
Value []T `json:"value"`
|
||||
Next string `json:"@odata.nextLink"`
|
||||
}
|
||||
if err := s.get(ctx, conn, u, &res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, res.Value...)
|
||||
u = res.Next
|
||||
if u != "" && !strings.HasPrefix(u, s.graph) {
|
||||
break // Never follow a link off Graph with the token.
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// Notebooks lists the notebooks of the signed-in Microsoft account.
|
||||
func (s *Service) Notebooks(ctx context.Context, c access.Caller, connID string) ([]Notebook, error) {
|
||||
conn, err := s.connection(c, connID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type nb struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"displayName"`
|
||||
Modified string `json:"lastModifiedDateTime"`
|
||||
}
|
||||
rows, err := list[nb](ctx, s, conn, s.graph+"/me/onenote/notebooks?$select=id,displayName,lastModifiedDateTime&$orderby=displayName")
|
||||
if err != nil {
|
||||
return nil, apperr.Invalid(err.Error())
|
||||
}
|
||||
out := make([]Notebook, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = Notebook(r)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Account is the Microsoft account a connection signed in as.
|
||||
func (s *Service) Account(c access.Caller, connID string) (string, error) {
|
||||
conn, err := s.connection(c, connID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return conn.email, nil
|
||||
}
|
||||
|
||||
// ---- Import ------------------------------------------------------------------------
|
||||
|
||||
// Import starts importing a notebook under parent in space.
|
||||
func (s *Service) Import(ctx context.Context, c access.Caller, connID, notebook, space, parent string) (Job, error) {
|
||||
conn, err := s.connection(c, connID)
|
||||
if err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
if notebook == "" || strings.ContainsAny(notebook, "/?#") {
|
||||
return Job{}, apperr.InvalidFields(map[string]string{"notebook": "Choose a notebook."})
|
||||
}
|
||||
job := &Job{ID: newID(), Notebook: notebook, Status: "running", user: c.ID, Created: []directory.Page{}}
|
||||
s.mu.Lock()
|
||||
s.jobs[job.ID] = job
|
||||
s.mu.Unlock()
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Hour)
|
||||
defer cancel()
|
||||
pages, assets, err := s.read(ctx, conn, notebook, func(n int) {
|
||||
s.mu.Lock()
|
||||
job.Pages = n
|
||||
s.mu.Unlock()
|
||||
})
|
||||
var created []directory.Page
|
||||
if err == nil {
|
||||
created, err = s.dir.ImportConverted(ctx, c, space, parent, pages, assets)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
job.ended = time.Now()
|
||||
if err != nil {
|
||||
slog.Warn("onenote import failed", "notebook", notebook, "err", err)
|
||||
job.Status, job.Error = "failed", err.Error()
|
||||
if e, ok := apperr.As(err); ok && len(e.Fields) > 0 {
|
||||
for _, v := range e.Fields {
|
||||
job.Error = v
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
job.Status, job.Created = "done", created
|
||||
}()
|
||||
return s.view(job), nil
|
||||
}
|
||||
|
||||
func (s *Service) view(j *Job) Job {
|
||||
v := *j
|
||||
v.Created = append([]directory.Page{}, j.Created...)
|
||||
return v
|
||||
}
|
||||
|
||||
// JobStatus reports an import the caller started.
|
||||
func (s *Service) JobStatus(c access.Caller, id string) (Job, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
j := s.jobs[id]
|
||||
if j == nil || j.user != c.ID {
|
||||
return Job{}, apperr.NotFound("import not found")
|
||||
}
|
||||
return s.view(j), nil
|
||||
}
|
||||
|
||||
type graphPage struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Level int `json:"level"`
|
||||
Order float64 `json:"order"`
|
||||
}
|
||||
|
||||
type graphNamed struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"displayName"`
|
||||
}
|
||||
|
||||
// read turns a notebook into pages and the files they use.
|
||||
func (s *Service) read(ctx context.Context, conn *connection, notebook string, progress func(int)) ([]convert.NotionPage, []convert.Asset, error) {
|
||||
var nb graphNamed
|
||||
if err := s.get(ctx, conn, s.graph+"/me/onenote/notebooks/"+url.PathEscape(notebook)+"?$select=id,displayName", &nb); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r := &reader{s: s, conn: conn, ctx: ctx, progress: progress, assetAt: map[string]string{}, names: map[string]string{}}
|
||||
root := r.add(convert.NotionPage{Title: nb.Name, Parent: -1, Doc: emptyDoc()})
|
||||
if err := r.container(root, "/me/onenote/notebooks/"+url.PathEscape(notebook), 0); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return r.pages, r.assets, nil
|
||||
}
|
||||
|
||||
func emptyDoc() convert.Node {
|
||||
return convert.Node{Type: "doc", Content: []convert.Node{{Type: "paragraph"}}}
|
||||
}
|
||||
|
||||
type reader struct {
|
||||
s *Service
|
||||
conn *connection
|
||||
ctx context.Context
|
||||
progress func(int)
|
||||
pages []convert.NotionPage
|
||||
assets []convert.Asset
|
||||
assetAt map[string]string
|
||||
names map[string]string // resource URL -> attached file's name
|
||||
size int64
|
||||
read int
|
||||
}
|
||||
|
||||
func (r *reader) add(p convert.NotionPage) int {
|
||||
r.pages = append(r.pages, p)
|
||||
return len(r.pages) - 1
|
||||
}
|
||||
|
||||
// container reads a notebook's or section group's section groups and sections.
|
||||
func (r *reader) container(parent int, path string, depth int) error {
|
||||
if depth > 10 {
|
||||
return nil
|
||||
}
|
||||
groups, err := list[graphNamed](r.ctx, r.s, r.conn, r.s.graph+path+"/sectionGroups?$select=id,displayName")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sections, err := list[graphNamed](r.ctx, r.s, r.conn, r.s.graph+path+"/sections?$select=id,displayName")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, sec := range sections {
|
||||
at := r.add(convert.NotionPage{Title: sec.Name, Parent: parent, Doc: emptyDoc()})
|
||||
if err := r.section(at, sec.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
at := r.add(convert.NotionPage{Title: g.Name, Parent: parent, Doc: emptyDoc()})
|
||||
if err := r.container(at, "/me/onenote/sectionGroups/"+url.PathEscape(g.ID), depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// section reads a section's pages in their order; a subpage goes under the
|
||||
// page before it one level up.
|
||||
func (r *reader) section(parent int, id string) error {
|
||||
pages, err := list[graphPage](r.ctx, r.s, r.conn, r.s.graph+"/me/onenote/sections/"+url.PathEscape(id)+"/pages?pagelevel=true&$select=id,title&$top=100")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.SliceStable(pages, func(i, j int) bool { return pages[i].Order < pages[j].Order })
|
||||
var stack []int // the last page read at each level
|
||||
for _, p := range pages {
|
||||
if len(r.pages) >= maxPages {
|
||||
return fmt.Errorf("the notebook has more than %d pages; import fewer", maxPages)
|
||||
}
|
||||
under := parent
|
||||
level := max(0, min(p.Level, len(stack)))
|
||||
if level > 0 {
|
||||
under = stack[level-1]
|
||||
}
|
||||
doc, err := r.content(p.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%q: %w", p.Title, err)
|
||||
}
|
||||
title, body := convert.Title(doc)
|
||||
if strings.TrimSpace(p.Title) != "" {
|
||||
title = p.Title
|
||||
}
|
||||
if strings.TrimSpace(title) == "" {
|
||||
title = "Untitled"
|
||||
}
|
||||
if len(body.Content) == 0 {
|
||||
body = emptyDoc()
|
||||
}
|
||||
at := r.add(convert.NotionPage{Title: strings.TrimSpace(title), Parent: under, Doc: body})
|
||||
stack = append(stack[:level], at)
|
||||
r.read++
|
||||
r.progress(r.read)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// object turns OneNote's attached files into links, which import keeps.
|
||||
var object = regexp.MustCompile(`(?is)<object\b[^>]*>.*?</object>|<object\b[^>]*/>`)
|
||||
var attr = regexp.MustCompile(`(?i)\b(data-attachment|data)\s*=\s*"([^"]*)"`)
|
||||
|
||||
// content reads one page's HTML as a document, with its files as assets.
|
||||
func (r *reader) content(id string) (convert.Node, error) {
|
||||
raw, err := r.s.do(r.ctx, r.conn, r.s.graph+"/me/onenote/pages/"+url.PathEscape(id)+"/content", nil)
|
||||
if err != nil {
|
||||
return convert.Node{}, err
|
||||
}
|
||||
html := object.ReplaceAllStringFunc(string(raw), func(tag string) string {
|
||||
var name, data string
|
||||
for _, m := range attr.FindAllStringSubmatch(tag, -1) {
|
||||
if strings.EqualFold(m[1], "data-attachment") {
|
||||
name = m[2]
|
||||
} else {
|
||||
data = m[2]
|
||||
}
|
||||
}
|
||||
if data == "" {
|
||||
return ""
|
||||
}
|
||||
if name == "" {
|
||||
name = "Attachment"
|
||||
} else {
|
||||
r.names[strings.ReplaceAll(data, "&", "&")] = name
|
||||
}
|
||||
return `<p><a href="` + data + `">` + name + `</a></p>`
|
||||
})
|
||||
var fail error
|
||||
doc, err := convert.FromHTMLWith(html, convert.ImportOptions{Resolve: func(u string) (string, bool) {
|
||||
u = strings.ReplaceAll(u, "&", "&")
|
||||
if !strings.HasPrefix(u, r.s.graph+"/") {
|
||||
return "", false
|
||||
}
|
||||
if ref, ok := r.assetAt[u]; ok {
|
||||
return ref, true
|
||||
}
|
||||
data, err := r.s.do(r.ctx, r.conn, u, nil)
|
||||
if err != nil {
|
||||
if fail == nil {
|
||||
fail = err
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
if r.size += int64(len(data)); r.size > maxResources {
|
||||
fail = errors.New("the notebook's files add up to more than 512 MB")
|
||||
return "", true
|
||||
}
|
||||
ref := convert.AssetRef(len(r.assets))
|
||||
name := r.names[u]
|
||||
if name == "" {
|
||||
name = resourceName(u, len(r.assets), data)
|
||||
}
|
||||
r.assets = append(r.assets, convert.Asset{Ref: ref, Name: name, Data: data})
|
||||
r.assetAt[u] = ref
|
||||
return ref, true
|
||||
}})
|
||||
if fail != nil {
|
||||
return convert.Node{}, fail
|
||||
}
|
||||
return doc, err
|
||||
}
|
||||
|
||||
// resourceName names a OneNote picture: Graph gives none, so its id is
|
||||
// used, with the extension of the type its bytes show.
|
||||
func resourceName(u string, n int, data []byte) string {
|
||||
ext := ""
|
||||
if exts, _ := mime.ExtensionsByType(strings.SplitN(http.DetectContentType(data), ";", 2)[0]); len(exts) > 0 {
|
||||
ext = exts[0]
|
||||
for _, e := range exts {
|
||||
if e == ".png" || e == ".jpg" || e == ".gif" || e == ".pdf" {
|
||||
ext = e
|
||||
}
|
||||
}
|
||||
}
|
||||
if i := strings.Index(u, "/resources/"); i >= 0 {
|
||||
id := strings.TrimSuffix(u[i+len("/resources/"):], "/$value")
|
||||
if j := strings.IndexAny(id, "/?!"); j >= 0 {
|
||||
id = id[:j]
|
||||
}
|
||||
if id != "" && len(id) < 120 {
|
||||
return "onenote-" + id + ext
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("onenote-file-%d%s", n+1, ext)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package onenote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/oauth"
|
||||
)
|
||||
|
||||
type fakeImporter struct {
|
||||
pages []convert.NotionPage
|
||||
assets []convert.Asset
|
||||
space string
|
||||
}
|
||||
|
||||
func (f *fakeImporter) ImportConverted(_ context.Context, _ access.Caller, space, _ string, pages []convert.NotionPage, assets []convert.Asset) ([]directory.Page, error) {
|
||||
f.pages, f.assets, f.space = pages, assets, space
|
||||
return []directory.Page{{ID: "p1", Title: pages[0].Title}}, nil
|
||||
}
|
||||
|
||||
func fakeGraph(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
png := "\x89PNG\r\n\x1a\n0000"
|
||||
var srv *httptest.Server
|
||||
mux := http.NewServeMux()
|
||||
write := func(w http.ResponseWriter, v any) { _ = json.NewEncoder(w).Encode(v) }
|
||||
auth := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer at" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("code") != "code-1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"access_token":"at","refresh_token":"rt","expires_in":3600}`))
|
||||
})
|
||||
mux.HandleFunc("GET /v1.0/me", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]string{"userPrincipalName": "ann@contoso.com"})
|
||||
}))
|
||||
throttled := false
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/notebooks", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !throttled {
|
||||
throttled = true
|
||||
w.Header().Set("Retry-After", "1")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
write(w, map[string]any{"value": []map[string]string{{"id": "nb1", "displayName": "Work"}}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/notebooks/nb1", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]string{"id": "nb1", "displayName": "Work"})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/notebooks/nb1/sectionGroups", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]any{"value": []map[string]string{{"id": "g1", "displayName": "Archive"}}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/notebooks/nb1/sections", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]any{"value": []map[string]string{{"id": "s1", "displayName": "Meetings"}}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/sectionGroups/g1/sectionGroups", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]any{"value": []any{}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/sectionGroups/g1/sections", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]any{"value": []map[string]string{{"id": "s2", "displayName": "2025"}}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/sections/s1/pages", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("pagelevel") != "true" {
|
||||
t.Error("pages asked without pagelevel")
|
||||
}
|
||||
if r.URL.Query().Get("page") == "" {
|
||||
write(w, map[string]any{
|
||||
"value": []map[string]any{{"id": "pB", "title": "Notes", "level": 1, "order": 1}, {"id": "pA", "title": "Kickoff", "level": 0, "order": 0}},
|
||||
"@odata.nextLink": srv.URL + "/v1.0/me/onenote/sections/s1/pages?pagelevel=true&page=2",
|
||||
})
|
||||
return
|
||||
}
|
||||
write(w, map[string]any{"value": []map[string]any{{"id": "pC", "title": "Retro", "level": 0, "order": 2}}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/sections/s2/pages", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
write(w, map[string]any{"value": []any{}})
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/me/onenote/pages/{id}/content", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
res := srv.URL + "/v1.0/users('ann')/onenote/resources/r1/$value"
|
||||
switch r.PathValue("id") {
|
||||
case "pA":
|
||||
_, _ = w.Write([]byte(`<html><head><title>Kickoff</title></head><body><div><p>Agenda</p><img src="` + res + `" data-src-type="image/png">` +
|
||||
`<object data-attachment="plan.pdf" type="application/pdf" data="` + srv.URL + `/v1.0/users('ann')/onenote/resources/r2/$value"></object></div></body></html>`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`<html><body><p>Page ` + r.PathValue("id") + `</p><img src="` + res + `"></body></html>`))
|
||||
}
|
||||
}))
|
||||
mux.HandleFunc("GET /v1.0/{who}/onenote/resources/{rest...}", auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "/resources/r2/") {
|
||||
_, _ = w.Write([]byte("%PDF-1.4 plan"))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(png))
|
||||
}))
|
||||
srv = httptest.NewServer(mux)
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestImportNotebook(t *testing.T) {
|
||||
g := fakeGraph(t)
|
||||
defer g.Close()
|
||||
imp := &fakeImporter{}
|
||||
s := New(imp, Options{
|
||||
Provider: oauth.Provider{Name: "microsoft", ClientID: "c", ClientSecret: "s", AuthURL: g.URL + "/auth", TokenURL: g.URL + "/token"},
|
||||
States: oauth.NewStates("x"), PublicURL: "https://api.test", WebURL: "https://web.test",
|
||||
Graph: g.URL + "/v1.0", Client: g.Client(),
|
||||
})
|
||||
ann := access.Caller{ID: "ann"}
|
||||
start, err := s.ConnectURL(ann, "space1", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(start)
|
||||
st, err := s.o.States.Verify(u.Query().Get("state"), Purpose)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
back, _ := url.Parse(s.Callback(context.Background(), st, "code-1", ""))
|
||||
conn := back.Query().Get("onenote")
|
||||
if back.Path != "/s/space1" || conn == "" {
|
||||
t.Fatalf("callback went to %s", back)
|
||||
}
|
||||
if email, _ := s.Account(ann, conn); email != "ann@contoso.com" {
|
||||
t.Errorf("account = %q", email)
|
||||
}
|
||||
if _, err := s.Notebooks(context.Background(), access.Caller{ID: "bob"}, conn); err == nil {
|
||||
t.Fatal("someone else used the connection")
|
||||
}
|
||||
nbs, err := s.Notebooks(context.Background(), ann, conn)
|
||||
if err != nil || len(nbs) != 1 || nbs[0].Name != "Work" {
|
||||
t.Fatalf("notebooks = %+v, %v", nbs, err)
|
||||
}
|
||||
job, err := s.Import(context.Background(), ann, conn, "nb1", "space1", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) {
|
||||
if job, _ = s.JobStatus(ann, job.ID); job.Status != "running" || time.Now().After(deadline) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if job.Status != "done" || job.Pages != 3 || len(job.Created) != 1 {
|
||||
t.Fatalf("job = %+v", job)
|
||||
}
|
||||
var titles []string
|
||||
parent := map[string]string{}
|
||||
for _, p := range imp.pages {
|
||||
titles = append(titles, p.Title)
|
||||
if p.Parent >= 0 {
|
||||
parent[p.Title] = imp.pages[p.Parent].Title
|
||||
}
|
||||
}
|
||||
if strings.Join(titles, ",") != "Work,Meetings,Kickoff,Notes,Retro,Archive,2025" {
|
||||
t.Errorf("pages = %v", titles)
|
||||
}
|
||||
if parent["Notes"] != "Kickoff" || parent["Kickoff"] != "Meetings" || parent["Retro"] != "Meetings" || parent["2025"] != "Archive" {
|
||||
t.Errorf("parents = %v", parent)
|
||||
}
|
||||
if len(imp.assets) != 2 || imp.assets[0].Name != "onenote-r1.png" || imp.assets[1].Name != "plan.pdf" {
|
||||
t.Errorf("assets = %+v", imp.assets)
|
||||
}
|
||||
kick, _ := json.Marshal(imp.pages[2].Doc)
|
||||
if !strings.Contains(string(kick), `"src":"asset:0"`) || !strings.Contains(string(kick), `"href":"asset:1"`) || !strings.Contains(string(kick), "plan.pdf") {
|
||||
t.Errorf("kickoff = %s", kick)
|
||||
}
|
||||
}
|
||||
@@ -5246,7 +5246,8 @@
|
||||
"type": "select",
|
||||
"values": [
|
||||
"ics",
|
||||
"caldav"
|
||||
"caldav",
|
||||
"google"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -5390,5 +5391,393 @@
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
},
|
||||
{
|
||||
"createRule": null,
|
||||
"deleteRule": null,
|
||||
"fields": [
|
||||
{
|
||||
"autogeneratePattern": "[a-z0-9]{15}",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3208210256",
|
||||
"max": 15,
|
||||
"min": 15,
|
||||
"name": "id",
|
||||
"pattern": "^[a-z0-9]+$",
|
||||
"presentable": false,
|
||||
"primaryKey": true,
|
||||
"required": true,
|
||||
"system": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "pbc_1382459093",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation2100713124",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "account",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "_pb_users_auth_",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation2375276105",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "user",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text2324736937",
|
||||
"max": 64,
|
||||
"min": 0,
|
||||
"name": "key",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3518522040",
|
||||
"max": 64,
|
||||
"min": 0,
|
||||
"name": "hash",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text724990059",
|
||||
"max": 1000,
|
||||
"min": 0,
|
||||
"name": "title",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text1587448267",
|
||||
"max": 1000,
|
||||
"min": 0,
|
||||
"name": "location",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text4101391790",
|
||||
"max": 2000,
|
||||
"min": 0,
|
||||
"name": "url",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "bool450241076",
|
||||
"name": "all_day",
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "bool"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "date3075695607",
|
||||
"max": "",
|
||||
"min": "",
|
||||
"name": "start_at",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "date"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "date936579196",
|
||||
"max": "",
|
||||
"min": "",
|
||||
"name": "end_at",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "date"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate2990389176",
|
||||
"name": "created",
|
||||
"onCreate": true,
|
||||
"onUpdate": false,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate3332085495",
|
||||
"name": "updated",
|
||||
"onCreate": true,
|
||||
"onUpdate": true,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
}
|
||||
],
|
||||
"id": "pbc_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)"
|
||||
],
|
||||
"listRule": null,
|
||||
"name": "calendar_events",
|
||||
"system": false,
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
},
|
||||
{
|
||||
"createRule": null,
|
||||
"deleteRule": null,
|
||||
"fields": [
|
||||
{
|
||||
"autogeneratePattern": "[a-z0-9]{15}",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3208210256",
|
||||
"max": 15,
|
||||
"min": 15,
|
||||
"name": "id",
|
||||
"pattern": "^[a-z0-9]+$",
|
||||
"presentable": false,
|
||||
"primaryKey": true,
|
||||
"required": true,
|
||||
"system": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "_pb_users_auth_",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation2375276105",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "user",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "pbc_2170078043",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation2375286809",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "workspace",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "pbc_3929545014",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation695386426",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "space",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text1032740943",
|
||||
"max": 64,
|
||||
"min": 0,
|
||||
"name": "parent",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text1554180325",
|
||||
"max": 2000,
|
||||
"min": 0,
|
||||
"name": "secret",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "bool1358543748",
|
||||
"name": "enabled",
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "bool"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3313461902",
|
||||
"max": 64,
|
||||
"min": 0,
|
||||
"name": "cursor",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "json1243294354",
|
||||
"maxSize": 5000000,
|
||||
"name": "books",
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "json"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "date3120574758",
|
||||
"max": "",
|
||||
"min": "",
|
||||
"name": "last_sync",
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "date"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text1066830442",
|
||||
"max": 500,
|
||||
"min": 0,
|
||||
"name": "last_error",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "number980656998",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"name": "highlights",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate2990389176",
|
||||
"name": "created",
|
||||
"onCreate": true,
|
||||
"onUpdate": false,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate3332085495",
|
||||
"name": "updated",
|
||||
"onCreate": true,
|
||||
"onUpdate": true,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
}
|
||||
],
|
||||
"id": "pbc_846969572",
|
||||
"indexes": [
|
||||
"CREATE UNIQUE INDEX idx_readwise_syncs_user ON readwise_syncs (user)"
|
||||
],
|
||||
"listRule": null,
|
||||
"name": "readwise_syncs",
|
||||
"system": false,
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,604 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package readwise keeps a person's Readwise highlights in Docwell (Phase F,
|
||||
// ADR-16). With their Readwise access token, the readwise.sync job asks the
|
||||
// Readwise export API every hour for what changed: a new book, article or
|
||||
// tweet thread gets a page under a "Readwise" page in the space they chose,
|
||||
// and new highlights are added to the end of the page that already has the
|
||||
// book. Pages are made and changed as the person, with their rights.
|
||||
package readwise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
"docwell/server/internal/webhooks"
|
||||
)
|
||||
|
||||
// Directory is the part of directory.Service a sync needs.
|
||||
type Directory interface {
|
||||
CallerOf(ctx context.Context, id string) (access.Caller, error)
|
||||
GetSpace(ctx context.Context, c access.Caller, id string) (directory.Space, error)
|
||||
GetPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
|
||||
CreatePage(ctx context.Context, c access.Caller, spaceID string, in directory.CreatePageInput) (directory.Page, error)
|
||||
GetPageContent(ctx context.Context, c access.Caller, id string) (directory.PageContent, error)
|
||||
SavePageContent(ctx context.Context, c access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error)
|
||||
ImportConverted(ctx context.Context, c access.Caller, spaceID, parent string, pages []convert.NotionPage, assets []convert.Asset) ([]directory.Page, error)
|
||||
}
|
||||
|
||||
// Options configure the service.
|
||||
type Options struct {
|
||||
Secret string
|
||||
// API replaces https://readwise.io (tests).
|
||||
API string
|
||||
// Client replaces the HTTP client (tests).
|
||||
Client *http.Client
|
||||
// Every is how often each connection is synced (1 h).
|
||||
Every time.Duration
|
||||
// AllowLocal lets requests reach loopback addresses (development).
|
||||
AllowLocal bool
|
||||
}
|
||||
|
||||
// API is Readwise (a variable for test builds).
|
||||
var API = "https://readwise.io"
|
||||
|
||||
type Service struct {
|
||||
pb *pocketbase.Client
|
||||
dir Directory
|
||||
aead cipher.AEAD
|
||||
api string
|
||||
client *http.Client
|
||||
every time.Duration
|
||||
mu sync.Mutex
|
||||
busy map[string]bool
|
||||
}
|
||||
|
||||
func New(pb *pocketbase.Client, dir Directory, o Options) *Service {
|
||||
key := sha256.Sum256([]byte("docwell-readwise:" + o.Secret))
|
||||
block, _ := aes.NewCipher(key[:])
|
||||
aead, _ := cipher.NewGCM(block)
|
||||
api := strings.TrimRight(o.API, "/")
|
||||
if api == "" {
|
||||
api = API
|
||||
}
|
||||
client := o.Client
|
||||
if client == nil {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)}
|
||||
client = &http.Client{Timeout: time.Minute, Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment}}
|
||||
}
|
||||
every := o.Every
|
||||
if every <= 0 {
|
||||
every = time.Hour
|
||||
}
|
||||
return &Service{pb: pb, dir: dir, aead: aead, api: api, client: client, every: every, busy: map[string]bool{}}
|
||||
}
|
||||
|
||||
func (s *Service) seal(plain string) string {
|
||||
nonce := make([]byte, s.aead.NonceSize())
|
||||
_, _ = rand.Read(nonce)
|
||||
return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil))
|
||||
}
|
||||
|
||||
func (s *Service) open(sealed string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:"))
|
||||
n := s.aead.NonceSize()
|
||||
if err != nil || len(raw) < n {
|
||||
return "", errors.New("the stored Readwise token cannot be decrypted (the server secret changed); enter it again")
|
||||
}
|
||||
plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil)
|
||||
if err != nil {
|
||||
return "", errors.New("the stored Readwise token cannot be decrypted (the server secret changed); enter it again")
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// book is what a sync remembers of a Readwise book: its page and the
|
||||
// highlights already on it.
|
||||
type book struct {
|
||||
Page string `json:"page"`
|
||||
Highlights []int64 `json:"highlights"`
|
||||
}
|
||||
|
||||
type record struct {
|
||||
ID string `json:"id"`
|
||||
User string `json:"user"`
|
||||
Workspace string `json:"workspace"`
|
||||
Space string `json:"space"`
|
||||
Parent string `json:"parent"`
|
||||
Secret string `json:"secret"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Cursor string `json:"cursor"`
|
||||
Books map[string]*book `json:"books"`
|
||||
LastSync string `json:"last_sync"`
|
||||
LastError string `json:"last_error"`
|
||||
Highlights float64 `json:"highlights"`
|
||||
}
|
||||
|
||||
// Connection is a person's Readwise sync as they see it (never the token).
|
||||
type Connection struct {
|
||||
Connected bool `json:"connected"`
|
||||
Workspace string `json:"workspace"`
|
||||
Space string `json:"space"`
|
||||
Parent string `json:"parent"`
|
||||
Enabled bool `json:"enabled"`
|
||||
LastSync string `json:"lastSync"`
|
||||
LastError string `json:"lastError"`
|
||||
Highlights int `json:"highlights"`
|
||||
Books int `json:"books"`
|
||||
}
|
||||
|
||||
func (r record) view() Connection {
|
||||
return Connection{
|
||||
Connected: true, Workspace: r.Workspace, Space: r.Space, Parent: r.Parent, Enabled: r.Enabled,
|
||||
LastSync: r.LastSync, LastError: r.LastError, Highlights: int(r.Highlights), Books: len(r.Books),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) find(ctx context.Context, user string) (*record, error) {
|
||||
if user == "" {
|
||||
return nil, apperr.NotFound("not found")
|
||||
}
|
||||
res, err := pocketbase.List[record](ctx, s.pb, "readwise_syncs", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("user = '%s'", user)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(res.Items) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return &res.Items[0], nil
|
||||
}
|
||||
|
||||
// Get returns the caller's connection ({connected: false} when there is none).
|
||||
func (s *Service) Get(ctx context.Context, c access.Caller) (Connection, error) {
|
||||
r, err := s.find(ctx, c.ID)
|
||||
if err != nil || r == nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
return r.view(), nil
|
||||
}
|
||||
|
||||
// Input sets up or changes the caller's sync. An empty Token keeps the
|
||||
// stored one.
|
||||
type Input struct {
|
||||
Token string `json:"token"`
|
||||
Space string `json:"space"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// Save checks the token with Readwise and the space with Docwell, stores
|
||||
// the connection and starts a first sync in the background.
|
||||
func (s *Service) Save(ctx context.Context, c access.Caller, in Input) (Connection, error) {
|
||||
r, err := s.find(ctx, c.ID)
|
||||
if err != nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
body := map[string]any{}
|
||||
if t := strings.TrimSpace(in.Token); t != "" {
|
||||
if len(t) > 200 {
|
||||
return Connection{}, apperr.InvalidFields(map[string]string{"token": "The token is too long."})
|
||||
}
|
||||
if err := s.checkToken(ctx, t); err != nil {
|
||||
return Connection{}, apperr.InvalidFields(map[string]string{"token": err.Error()})
|
||||
}
|
||||
body["secret"] = s.seal(t)
|
||||
} else if r == nil {
|
||||
return Connection{}, apperr.InvalidFields(map[string]string{"token": "Paste your Readwise access token."}) //nolint:gosec // a message, not a credential
|
||||
}
|
||||
if in.Space != "" && (r == nil || in.Space != r.Space) {
|
||||
sp, err := s.dir.GetSpace(ctx, c, in.Space)
|
||||
if err != nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
if sp.Role != access.SpaceEditor && sp.Role != access.SpaceAdmin {
|
||||
return Connection{}, apperr.InvalidFields(map[string]string{"space": "Choose a space you can add pages to."})
|
||||
}
|
||||
body["space"], body["workspace"], body["parent"] = sp.ID, sp.Workspace, ""
|
||||
// Another space starts over: its books are not there yet.
|
||||
body["books"], body["cursor"], body["highlights"] = map[string]any{}, "", 0
|
||||
} else if r == nil {
|
||||
return Connection{}, apperr.InvalidFields(map[string]string{"space": "Choose the space highlights go to."})
|
||||
}
|
||||
if in.Enabled != nil {
|
||||
body["enabled"] = *in.Enabled
|
||||
} else if r == nil {
|
||||
body["enabled"] = true
|
||||
}
|
||||
var saved record
|
||||
if r == nil {
|
||||
body["user"] = c.ID
|
||||
saved, err = pocketbase.Create[record](ctx, s.pb, "readwise_syncs", body)
|
||||
} else {
|
||||
saved, err = pocketbase.Update[record](ctx, s.pb, "readwise_syncs", r.ID, body)
|
||||
}
|
||||
if err != nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
if saved.Enabled {
|
||||
go func() { //nolint:gosec // the first sync outlives the request on purpose
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
if err := s.sync(ctx, saved); err != nil {
|
||||
slog.Info("readwise sync failed", "user", saved.User, "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
return saved.view(), nil
|
||||
}
|
||||
|
||||
// Delete disconnects Readwise; the pages made so far stay.
|
||||
func (s *Service) Delete(ctx context.Context, c access.Caller) error {
|
||||
r, err := s.find(ctx, c.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return apperr.NotFound("Readwise is not connected")
|
||||
}
|
||||
return s.pb.Delete(ctx, "readwise_syncs", r.ID)
|
||||
}
|
||||
|
||||
// SyncNow syncs the caller's highlights and returns the result.
|
||||
func (s *Service) SyncNow(ctx context.Context, c access.Caller) (Connection, error) {
|
||||
r, err := s.find(ctx, c.ID)
|
||||
if err != nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
if r == nil {
|
||||
return Connection{}, apperr.NotFound("Readwise is not connected")
|
||||
}
|
||||
if err := s.sync(ctx, *r); err != nil {
|
||||
slog.Debug("readwise sync failed", "user", r.User, "err", err)
|
||||
}
|
||||
r, err = s.find(ctx, c.ID)
|
||||
if err != nil || r == nil {
|
||||
return Connection{}, err
|
||||
}
|
||||
return r.view(), nil
|
||||
}
|
||||
|
||||
// SyncDue syncs every connection not synced for an hour (the readwise.sync job).
|
||||
func (s *Service) SyncDue(ctx context.Context) error {
|
||||
cutoff := time.Now().Add(-s.every).UTC().Format("2006-01-02 15:04:05.000Z")
|
||||
for page := 1; ; page++ {
|
||||
res, err := pocketbase.List[record](ctx, s.pb, "readwise_syncs", pocketbase.ListOptions{
|
||||
Page: page, PerPage: 200, Filter: fmt.Sprintf("enabled = true && (last_sync = '' || last_sync < '%s')", cutoff),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range res.Items {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := s.sync(ctx, r); err != nil {
|
||||
slog.Info("readwise sync failed", "user", r.User, "err", err)
|
||||
}
|
||||
}
|
||||
if page >= res.TotalPages || len(res.Items) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Readwise API -------------------------------------------------------------------
|
||||
|
||||
func (s *Service) call(ctx context.Context, token, path string, q url.Values, out any) (int, error) {
|
||||
u := s.api + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Token "+token)
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("the Readwise API did not answer: %w", err)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 64<<20))
|
||||
_ = res.Body.Close()
|
||||
if err != nil {
|
||||
return res.StatusCode, err
|
||||
}
|
||||
if res.StatusCode == http.StatusTooManyRequests && attempt < 4 {
|
||||
wait := 5 * time.Second
|
||||
if sec, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && sec > 0 {
|
||||
wait = time.Duration(min(sec, 120)) * time.Second
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0, ctx.Err()
|
||||
case <-time.After(wait):
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
|
||||
return res.StatusCode, errors.New("the access token was refused by Readwise")
|
||||
case res.StatusCode >= 300:
|
||||
return res.StatusCode, fmt.Errorf("the Readwise API answered %s", res.Status)
|
||||
}
|
||||
if out != nil && len(body) > 0 {
|
||||
return res.StatusCode, json.Unmarshal(body, out)
|
||||
}
|
||||
return res.StatusCode, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) checkToken(ctx context.Context, token string) error {
|
||||
code, err := s.call(ctx, token, "/api/v2/auth/", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if code != http.StatusNoContent && code != http.StatusOK {
|
||||
return errors.New("the token was not accepted by Readwise")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type apiTag struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type apiHighlight struct {
|
||||
ID int64 `json:"id"`
|
||||
Text string `json:"text"`
|
||||
Note string `json:"note"`
|
||||
Location any `json:"location"`
|
||||
LocationType string `json:"location_type"`
|
||||
HighlightedAt string `json:"highlighted_at"`
|
||||
Deleted bool `json:"is_deleted"`
|
||||
Tags []apiTag `json:"tags"`
|
||||
}
|
||||
|
||||
type apiBook struct {
|
||||
ID int64 `json:"user_book_id"`
|
||||
Title string `json:"readable_title"`
|
||||
RawTitle string `json:"title"`
|
||||
Author string `json:"author"`
|
||||
SourceURL string `json:"source_url"`
|
||||
UniqueURL string `json:"unique_url"`
|
||||
Tags []apiTag `json:"book_tags"`
|
||||
Highlights []apiHighlight `json:"highlights"`
|
||||
}
|
||||
|
||||
func names(tags []apiTag) []string {
|
||||
var out []string
|
||||
for _, t := range tags {
|
||||
if t.Name != "" {
|
||||
out = append(out, t.Name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h apiHighlight) convert() convert.ReadwiseHighlight {
|
||||
loc := ""
|
||||
switch v := h.Location.(type) {
|
||||
case float64:
|
||||
loc = strconv.FormatFloat(v, 'f', -1, 64)
|
||||
case string:
|
||||
loc = v
|
||||
}
|
||||
return convert.ReadwiseHighlight{
|
||||
Text: h.Text, Note: h.Note, Location: loc, LocationType: h.LocationType,
|
||||
HighlightedAt: h.HighlightedAt, Tags: names(h.Tags),
|
||||
}
|
||||
}
|
||||
|
||||
// export reads every book that changed since cursor ("" = all).
|
||||
func (s *Service) export(ctx context.Context, token, cursor string) ([]apiBook, error) {
|
||||
var books []apiBook
|
||||
q := url.Values{}
|
||||
if cursor != "" {
|
||||
q.Set("updatedAfter", cursor)
|
||||
}
|
||||
for pages := 0; pages < 1000; pages++ {
|
||||
var res struct {
|
||||
Results []apiBook `json:"results"`
|
||||
NextCursor any `json:"nextPageCursor"`
|
||||
}
|
||||
if _, err := s.call(ctx, token, "/api/v2/export/", q, &res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
books = append(books, res.Results...)
|
||||
next := ""
|
||||
switch v := res.NextCursor.(type) {
|
||||
case string:
|
||||
next = v
|
||||
case float64:
|
||||
next = strconv.FormatFloat(v, 'f', -1, 64)
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
q.Set("pageCursor", next)
|
||||
}
|
||||
return books, nil
|
||||
}
|
||||
|
||||
// ---- Sync -------------------------------------------------------------------------------
|
||||
|
||||
// sync brings one connection up to date.
|
||||
func (s *Service) sync(ctx context.Context, r record) (err error) {
|
||||
s.mu.Lock()
|
||||
if s.busy[r.ID] {
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
s.busy[r.ID] = true
|
||||
s.mu.Unlock()
|
||||
started := time.Now().UTC()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.busy, r.ID)
|
||||
s.mu.Unlock()
|
||||
patch := map[string]any{"last_sync": started.Format("2006-01-02 15:04:05.000Z"), "last_error": "", "books": r.Books, "parent": r.Parent}
|
||||
if err != nil {
|
||||
msg := err.Error()
|
||||
if len(msg) > 500 {
|
||||
msg = msg[:500]
|
||||
}
|
||||
patch["last_error"] = msg
|
||||
} else {
|
||||
patch["cursor"] = started.Format(time.RFC3339)
|
||||
}
|
||||
n := 0
|
||||
for _, b := range r.Books {
|
||||
n += len(b.Highlights)
|
||||
}
|
||||
patch["highlights"] = n
|
||||
if _, uerr := pocketbase.Update[record](context.WithoutCancel(ctx), s.pb, "readwise_syncs", r.ID, patch); uerr != nil {
|
||||
slog.Warn("readwise status not saved", "user", r.User, "err", uerr)
|
||||
}
|
||||
}()
|
||||
if r.Books == nil {
|
||||
r.Books = map[string]*book{}
|
||||
}
|
||||
c, err := s.dir.CallerOf(ctx, r.User)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := s.open(r.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
books, err := s.export(ctx, token, r.Cursor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, b := range books {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := s.syncBook(ctx, c, &r, b); err != nil {
|
||||
return fmt.Errorf("%q: %w", b.title(), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b apiBook) title() string {
|
||||
if strings.TrimSpace(b.Title) != "" {
|
||||
return strings.TrimSpace(b.Title)
|
||||
}
|
||||
if strings.TrimSpace(b.RawTitle) != "" {
|
||||
return strings.TrimSpace(b.RawTitle)
|
||||
}
|
||||
return "Untitled"
|
||||
}
|
||||
|
||||
// parent is the "Readwise" page books go under, made when missing.
|
||||
func (s *Service) parent(ctx context.Context, c access.Caller, r *record) (string, error) {
|
||||
if r.Parent != "" {
|
||||
if p, err := s.dir.GetPage(ctx, c, r.Parent); err == nil && !p.InTrash && p.Space == r.Space {
|
||||
return r.Parent, nil
|
||||
}
|
||||
}
|
||||
p, err := s.dir.CreatePage(ctx, c, r.Space, directory.CreatePageInput{Title: "Readwise"})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, _ := json.Marshal(convert.ReadwiseIndex())
|
||||
if _, err := s.dir.SavePageContent(ctx, c, p.ID, directory.SavePageContentInput{Content: raw}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
r.Parent = p.ID
|
||||
return p.ID, nil
|
||||
}
|
||||
|
||||
func (s *Service) syncBook(ctx context.Context, c access.Caller, r *record, b apiBook) error {
|
||||
key := strconv.FormatInt(b.ID, 10)
|
||||
known := r.Books[key]
|
||||
have := map[int64]bool{}
|
||||
if known != nil {
|
||||
for _, id := range known.Highlights {
|
||||
have[id] = true
|
||||
}
|
||||
}
|
||||
var fresh []apiHighlight
|
||||
for _, h := range b.Highlights {
|
||||
if !h.Deleted && !have[h.ID] && strings.TrimSpace(h.Text) != "" {
|
||||
fresh = append(fresh, h)
|
||||
}
|
||||
}
|
||||
if len(fresh) == 0 {
|
||||
return nil
|
||||
}
|
||||
hs := make([]convert.ReadwiseHighlight, len(fresh))
|
||||
for i, h := range fresh {
|
||||
hs[i] = h.convert()
|
||||
}
|
||||
// A book whose page is gone (deleted, or in the trash) gets a new one.
|
||||
if known != nil {
|
||||
if p, err := s.dir.GetPage(ctx, c, known.Page); err != nil || p.InTrash {
|
||||
known = nil
|
||||
}
|
||||
}
|
||||
if known == nil {
|
||||
parent, err := s.parent(ctx, c, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
link := b.SourceURL
|
||||
if link == "" {
|
||||
link = b.UniqueURL
|
||||
}
|
||||
page := convert.ReadwiseBook{Title: b.title(), Author: b.Author, URL: link, Tags: names(b.Tags), Highlights: hs}.Page()
|
||||
created, err := s.dir.ImportConverted(ctx, c, r.Space, parent, []convert.NotionPage{page}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(created) == 0 {
|
||||
return errors.New("no page was made")
|
||||
}
|
||||
known = &book{Page: created[0].ID}
|
||||
r.Books[key] = known
|
||||
} else {
|
||||
content, err := s.dir.GetPageContent(ctx, c, known.Page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
doc := convert.Node{Type: "doc"}
|
||||
if len(content.Content) > 0 && string(content.Content) != "null" {
|
||||
if err := json.Unmarshal(content.Content, &doc); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
doc.Content = append(doc.Content, convert.ReadwiseNodes(hs)...)
|
||||
raw, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.dir.SavePageContent(ctx, c, known.Page, directory.SavePageContentInput{Content: raw}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, h := range fresh {
|
||||
known.Highlights = append(known.Highlights, h.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package readwise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/directory"
|
||||
)
|
||||
|
||||
type fakeDir struct {
|
||||
pages map[string]*directory.Page
|
||||
content map[string]json.RawMessage
|
||||
n int
|
||||
}
|
||||
|
||||
func newFakeDir() *fakeDir {
|
||||
return &fakeDir{pages: map[string]*directory.Page{}, content: map[string]json.RawMessage{}}
|
||||
}
|
||||
|
||||
func (f *fakeDir) CallerOf(context.Context, string) (access.Caller, error) {
|
||||
return access.Caller{ID: "u1"}, nil
|
||||
}
|
||||
func (f *fakeDir) GetSpace(context.Context, access.Caller, string) (directory.Space, error) {
|
||||
return directory.Space{ID: "sp", Workspace: "ws", Role: access.SpaceEditor}, nil
|
||||
}
|
||||
func (f *fakeDir) GetPage(_ context.Context, _ access.Caller, id string) (directory.Page, error) {
|
||||
if p := f.pages[id]; p != nil {
|
||||
return *p, nil
|
||||
}
|
||||
return directory.Page{}, fmt.Errorf("page not found")
|
||||
}
|
||||
func (f *fakeDir) add(space, parent, title string) directory.Page {
|
||||
f.n++
|
||||
p := &directory.Page{ID: fmt.Sprintf("p%d", f.n), Space: space, Parent: parent, Title: title}
|
||||
f.pages[p.ID] = p
|
||||
return *p
|
||||
}
|
||||
func (f *fakeDir) CreatePage(_ context.Context, _ access.Caller, space string, in directory.CreatePageInput) (directory.Page, error) {
|
||||
return f.add(space, in.Parent, in.Title), nil
|
||||
}
|
||||
func (f *fakeDir) GetPageContent(_ context.Context, _ access.Caller, id string) (directory.PageContent, error) {
|
||||
return directory.PageContent{Content: f.content[id]}, nil
|
||||
}
|
||||
func (f *fakeDir) SavePageContent(_ context.Context, _ access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error) {
|
||||
f.content[id] = in.Content
|
||||
return directory.PageContent{Content: in.Content}, nil
|
||||
}
|
||||
func (f *fakeDir) ImportConverted(_ context.Context, _ access.Caller, space, parent string, pages []convert.NotionPage, _ []convert.Asset) ([]directory.Page, error) {
|
||||
p := f.add(space, parent, pages[0].Title)
|
||||
raw, _ := json.Marshal(pages[0].Doc)
|
||||
f.content[p.ID] = raw
|
||||
return []directory.Page{p}, nil
|
||||
}
|
||||
|
||||
func TestSyncBooks(t *testing.T) {
|
||||
round := 1
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Token tok" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v2/auth/":
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case "/api/v2/export/":
|
||||
if round == 1 && r.URL.Query().Get("pageCursor") == "" {
|
||||
_, _ = w.Write([]byte(`{"results":[{"user_book_id":1,"readable_title":"Deep Work","author":"Cal Newport","book_tags":[{"name":"books"}],` +
|
||||
`"highlights":[{"id":11,"text":"Focus matters","location":12,"location_type":"location","highlighted_at":"2024-03-01T10:00:00Z","tags":[{"name":"focus"}]},` +
|
||||
`{"id":12,"text":"gone","is_deleted":true}]}],"nextPageCursor":"c2"}`))
|
||||
return
|
||||
}
|
||||
if round == 1 {
|
||||
_, _ = w.Write([]byte(`{"results":[{"user_book_id":2,"readable_title":"An Article","source_url":"https://blog.example.com/a","highlights":[{"id":21,"text":"Quote"}]}],"nextPageCursor":null}`))
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("updatedAfter") == "" {
|
||||
t.Error("second sync without updatedAfter")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"results":[{"user_book_id":1,"readable_title":"Deep Work","highlights":[{"id":11,"text":"Focus matters"},{"id":13,"text":"New one","note":"mine"}]}]}`))
|
||||
}
|
||||
}))
|
||||
defer api.Close()
|
||||
dir := newFakeDir()
|
||||
s := New(nil, dir, Options{Secret: "x", API: api.URL, Client: api.Client()})
|
||||
ctx := context.Background()
|
||||
if err := s.checkToken(ctx, "tok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.checkToken(ctx, "bad"); err == nil || !strings.Contains(err.Error(), "refused") {
|
||||
t.Fatalf("bad token: %v", err)
|
||||
}
|
||||
r := &record{Space: "sp", Books: map[string]*book{}}
|
||||
c := access.Caller{ID: "u1"}
|
||||
run := func() {
|
||||
books, err := s.export(ctx, "tok", r.Cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range books {
|
||||
if err := s.syncBook(ctx, c, r, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r.Cursor = "2026-11-16T00:00:00Z"
|
||||
}
|
||||
run()
|
||||
if len(r.Books) != 2 || r.Parent == "" || dir.pages[r.Parent].Title != "Readwise" {
|
||||
t.Fatalf("books %v parent %q", r.Books, r.Parent)
|
||||
}
|
||||
deep := r.Books["1"]
|
||||
if dir.pages[deep.Page].Parent != r.Parent || len(deep.Highlights) != 1 {
|
||||
t.Fatalf("deep work = %+v", deep)
|
||||
}
|
||||
j := string(dir.content[deep.Page])
|
||||
if !strings.Contains(j, "Focus matters") || strings.Contains(j, "gone") || !strings.Contains(j, "location 12 · 2024-03-01 · #focus") {
|
||||
t.Errorf("deep work content = %s", j)
|
||||
}
|
||||
if a := string(dir.content[r.Books["2"].Page]); !strings.Contains(a, "https://blog.example.com/a") {
|
||||
t.Errorf("article content = %s", a)
|
||||
}
|
||||
|
||||
round = 2
|
||||
run()
|
||||
j = string(dir.content[deep.Page])
|
||||
if strings.Count(j, "Focus matters") != 1 || !strings.Contains(j, "New one") || !strings.Contains(j, "mine") || len(deep.Highlights) != 2 {
|
||||
t.Errorf("after second sync: %s, %v", j, deep.Highlights)
|
||||
}
|
||||
|
||||
// A page moved to the trash gets a new page with the new highlights.
|
||||
dir.pages[deep.Page].InTrash = true
|
||||
old := deep.Page
|
||||
if err := s.syncBook(ctx, c, r, apiBook{ID: 1, Title: "Deep Work", Highlights: []apiHighlight{{ID: 14, Text: "After trash"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Books["1"].Page == old || !strings.Contains(string(dir.content[r.Books["1"].Page]), "After trash") {
|
||||
t.Errorf("trashed page not replaced: %+v", r.Books["1"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSealToken(t *testing.T) {
|
||||
s := New(nil, newFakeDir(), Options{Secret: "a"})
|
||||
got, err := s.open(s.seal("tok"))
|
||||
if err != nil || got != "tok" {
|
||||
t.Fatalf("open = %q, %v", got, err)
|
||||
}
|
||||
if _, err := New(nil, newFakeDir(), Options{Secret: "b"}).open(s.seal("tok")); err == nil {
|
||||
t.Fatal("opened with another secret")
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,16 @@ import { ApiError } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import FormField from "./FormField.vue";
|
||||
|
||||
// The signed-in person's calendars (ADR-16): iCalendar feeds and CalDAV
|
||||
// accounts whose events show on their journal pages. Only they see them.
|
||||
// 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.
|
||||
const api = useApi();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t, locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
|
||||
@@ -20,6 +23,10 @@ const accounts = ref<CalendarAccount[]>([]);
|
||||
const available = ref(true);
|
||||
const busy = ref(false);
|
||||
const adding = ref(false);
|
||||
// Whether the server has a Google OAuth app, and the outcome of a Google
|
||||
// sign-in the browser just came back from.
|
||||
const google = ref(false);
|
||||
const connected = ref(false);
|
||||
|
||||
const colors: LabelColor[] = ["blue", "green", "orange", "purple", "red", "teal", "yellow", "pink", "gray"];
|
||||
const blank = (): Required<Pick<CalendarAccountInput, "name" | "kind" | "url" | "username" | "password">> => ({
|
||||
@@ -32,14 +39,35 @@ const blank = (): Required<Pick<CalendarAccountInput, "name" | "kind" | "url" |
|
||||
const form = ref(blank());
|
||||
|
||||
onMounted(async () => {
|
||||
const q = route.query;
|
||||
if (q.calendar === "connected") connected.value = true;
|
||||
if (typeof q.calendarError === "string") errors.message.value = q.calendarError;
|
||||
if (q.calendar || q.calendarError) {
|
||||
const rest = { ...q };
|
||||
delete rest.calendar;
|
||||
delete rest.calendarError;
|
||||
void router.replace({ query: rest });
|
||||
}
|
||||
try {
|
||||
accounts.value = await api.calendars.list();
|
||||
const [list, integrations] = await Promise.all([
|
||||
api.calendars.list(),
|
||||
api.integrations().catch(() => ({ google: false, microsoft: false, readwise: false })),
|
||||
]);
|
||||
accounts.value = list;
|
||||
google.value = integrations.google;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 404) available.value = false;
|
||||
else errors.show(e);
|
||||
}
|
||||
});
|
||||
|
||||
// Google sign-in happens on Google's site; it comes back to this page.
|
||||
const connectGoogle = () =>
|
||||
run(async () => {
|
||||
const { url } = await api.calendars.googleConnect();
|
||||
window.location.assign(url);
|
||||
});
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
@@ -88,6 +116,9 @@ const when = (iso: string) =>
|
||||
<p class="mt-1 text-ui-md text-ink-muted">{{ $t("calendars.hint") }}</p>
|
||||
</div>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
|
||||
<DwCallout v-else-if="connected" tone="success" size="ui" data-testid="calendar-connected">
|
||||
{{ $t("calendars.googleConnected") }}
|
||||
</DwCallout>
|
||||
|
||||
<ul v-if="accounts.length" class="divide-y divide-line rounded-md border border-line" data-testid="calendar-list">
|
||||
<li v-for="a in accounts" :key="a.id" class="flex flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2">
|
||||
@@ -110,10 +141,12 @@ const when = (iso: string) =>
|
||||
/>
|
||||
<span class="truncate">{{ a.name }}</span>
|
||||
<span class="text-ui-xs font-normal text-ink-muted uppercase">{{
|
||||
a.kind === "caldav" ? "CalDAV" : "iCal"
|
||||
a.kind === "caldav" ? "CalDAV" : a.kind === "google" ? "Google" : "iCal"
|
||||
}}</span>
|
||||
</span>
|
||||
<span class="block truncate text-ui-sm text-ink-muted" :title="a.url">{{ a.url }}</span>
|
||||
<span class="block truncate text-ui-sm text-ink-muted" :title="a.url">{{
|
||||
a.kind === "google" ? a.username : a.url
|
||||
}}</span>
|
||||
<span v-if="a.lastError" class="block text-ui-sm text-danger" data-testid="calendar-error">{{
|
||||
a.lastError
|
||||
}}</span>
|
||||
@@ -184,6 +217,11 @@ const when = (iso: string) =>
|
||||
<DwButton variant="ghost" :disabled="busy" @click="adding = false">{{ $t("calendars.cancel") }}</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
<DwButton v-else icon="plus" data-testid="calendar-new" @click="adding = true">{{ $t("calendars.new") }}</DwButton>
|
||||
<div v-else class="flex flex-wrap gap-2">
|
||||
<DwButton icon="plus" data-testid="calendar-new" @click="adding = true">{{ $t("calendars.new") }}</DwButton>
|
||||
<DwButton v-if="google" icon="link" :disabled="busy" data-testid="calendar-google" @click="connectGoogle">
|
||||
{{ $t("calendars.connectGoogle") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,126 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { OneNoteConnection, OneNoteJob } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useApi } from "../api";
|
||||
|
||||
// Importing a whole OneNote notebook into a space through Microsoft Graph
|
||||
// (ADR-16): sign in to Microsoft (the browser comes back with
|
||||
// ?onenote=<connection>), pick a notebook, and follow the import.
|
||||
const props = defineProps<{ space: string }>();
|
||||
const emit = defineEmits<{ done: [pageId: string]; error: [err: unknown] }>();
|
||||
const api = useApi();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const enabled = ref(false);
|
||||
const connection = ref("");
|
||||
const info = ref<OneNoteConnection | null>(null);
|
||||
const notebook = ref("");
|
||||
const job = ref<OneNoteJob | null>(null);
|
||||
const failure = ref("");
|
||||
const busy = ref(false);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
onMounted(async () => {
|
||||
const q = route.query;
|
||||
if (typeof q.onenoteError === "string") failure.value = q.onenoteError;
|
||||
if (typeof q.onenote === "string") connection.value = q.onenote;
|
||||
if (q.onenote || q.onenoteError || q.onenoteParent) {
|
||||
const rest = { ...q };
|
||||
delete rest.onenote;
|
||||
delete rest.onenoteError;
|
||||
delete rest.onenoteParent;
|
||||
void router.replace({ query: rest });
|
||||
}
|
||||
enabled.value = (await api.integrations().catch(() => null))?.microsoft ?? false;
|
||||
if (connection.value) {
|
||||
try {
|
||||
info.value = await api.onenote.connection(connection.value);
|
||||
notebook.value = info.value.notebooks[0]?.id ?? "";
|
||||
} catch (e) {
|
||||
connection.value = "";
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => clearTimeout(timer));
|
||||
|
||||
async function connect() {
|
||||
busy.value = true;
|
||||
try {
|
||||
const { url } = await api.onenote.connect(props.space);
|
||||
window.location.assign(url);
|
||||
} catch (e) {
|
||||
busy.value = false;
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function follow(id: string) {
|
||||
try {
|
||||
job.value = await api.onenote.job(id);
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
return;
|
||||
}
|
||||
if (job.value.status === "running") {
|
||||
timer = setTimeout(() => void follow(id), 1500);
|
||||
return;
|
||||
}
|
||||
busy.value = false;
|
||||
if (job.value.status === "done") {
|
||||
const top = job.value.created[0];
|
||||
connection.value = "";
|
||||
info.value = null;
|
||||
if (top) emit("done", top.id);
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!notebook.value) return;
|
||||
busy.value = true;
|
||||
failure.value = "";
|
||||
try {
|
||||
const j = await api.onenote.import(connection.value, { notebook: notebook.value, space: props.space });
|
||||
job.value = j;
|
||||
void follow(j.id);
|
||||
} catch (e) {
|
||||
busy.value = false;
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ enabled, connect });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<DwCallout v-if="failure" tone="danger" size="ui" class="mt-4">{{ failure }}</DwCallout>
|
||||
<DwCallout v-else-if="job?.status === 'failed'" tone="danger" size="ui" class="mt-4">{{ job.error }}</DwCallout>
|
||||
<section v-if="info" class="mt-4 space-y-3 dw-card" data-testid="onenote-import">
|
||||
<h2 class="text-ui-lg">{{ $t("onenote.title") }}</h2>
|
||||
<p class="text-ui-sm text-ink-muted">{{ $t("onenote.signedIn", { account: info.account || "Microsoft" }) }}</p>
|
||||
<p v-if="!info.notebooks.length" class="text-ui-md">{{ $t("onenote.none") }}</p>
|
||||
<template v-else>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("onenote.notebook") }}</span>
|
||||
<select v-model="notebook" class="dw-input" :disabled="busy" data-testid="onenote-notebook">
|
||||
<option v-for="n in info.notebooks" :key="n.id" :value="n.id">{{ n.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="job?.status === 'running'" class="text-ui-sm text-ink-muted" role="status">
|
||||
{{ $t("onenote.progress", { n: job.pages }) }}
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<DwButton variant="primary" :disabled="busy || !notebook" data-testid="onenote-start" @click="start">
|
||||
{{ $t(busy ? "onenote.importing" : "onenote.import") }}
|
||||
</DwButton>
|
||||
<DwButton variant="ghost" :disabled="busy" @click="info = null">{{ $t("calendars.cancel") }}</DwButton>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,165 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { ReadwiseConnection, Space } from "@docwell/api-client";
|
||||
import { ApiError } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import { useWorkspacesStore } from "../stores/workspaces";
|
||||
import FormField from "./FormField.vue";
|
||||
|
||||
// The signed-in person's Readwise sync (ADR-16): every hour, new books get
|
||||
// a page under a "Readwise" page in the space they chose, and new highlights
|
||||
// are added to their book's page.
|
||||
const api = useApi();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const { t, locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const available = ref(true);
|
||||
const conn = ref<ReadwiseConnection | null>(null);
|
||||
const busy = ref(false);
|
||||
const editing = ref(false);
|
||||
const token = ref("");
|
||||
const workspace = ref("");
|
||||
const space = ref("");
|
||||
const spaces = ref<Space[]>([]);
|
||||
|
||||
const writable = computed(() => spaces.value.filter((s) => (s.role === "editor" || s.role === "admin") && !s.journal));
|
||||
|
||||
async function loadSpaces() {
|
||||
spaces.value = workspace.value ? await api.workspaces.spaces(workspace.value).catch(() => []) : [];
|
||||
if (!writable.value.some((s) => s.id === space.value)) space.value = writable.value[0]?.id ?? "";
|
||||
}
|
||||
watch(workspace, () => void loadSpaces());
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const integrations = await api.integrations();
|
||||
if (!integrations.readwise) {
|
||||
available.value = false;
|
||||
return;
|
||||
}
|
||||
conn.value = await api.readwise.get();
|
||||
if (!workspaces.loaded) await workspaces.load();
|
||||
workspace.value = conn.value.connected ? conn.value.workspace : (workspaces.items[0]?.id ?? "");
|
||||
space.value = conn.value.space;
|
||||
await loadSpaces();
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 404) available.value = false;
|
||||
else errors.show(e);
|
||||
}
|
||||
});
|
||||
|
||||
async function run(action: () => Promise<ReadwiseConnection | void>) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
const res = await action();
|
||||
conn.value = res ?? (await api.readwise.get());
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const save = () =>
|
||||
run(async () => {
|
||||
const res = await api.readwise.save({ token: token.value.trim() || undefined, space: space.value });
|
||||
token.value = "";
|
||||
editing.value = false;
|
||||
return res;
|
||||
});
|
||||
const toggle = () => run(() => api.readwise.save({ enabled: !conn.value?.enabled }));
|
||||
const syncNow = () => run(() => api.readwise.sync());
|
||||
const disconnect = () => {
|
||||
if (confirm(t("readwise.confirmDisconnect"))) void run(() => api.readwise.remove());
|
||||
};
|
||||
|
||||
const spaceName = computed(() => spaces.value.find((s) => s.id === conn.value?.space)?.name ?? "");
|
||||
const when = (iso: string) =>
|
||||
iso
|
||||
? new Intl.DateTimeFormat(locale.value, { dateStyle: "medium", timeStyle: "short" }).format(
|
||||
new Date(iso.replace(" ", "T")),
|
||||
)
|
||||
: "";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="available" class="space-y-4 dw-card" data-testid="readwise-section">
|
||||
<div>
|
||||
<h2 class="text-ui-lg">{{ $t("readwise.title") }}</h2>
|
||||
<p class="mt-1 text-ui-md text-ink-muted">{{ $t("readwise.hint") }}</p>
|
||||
</div>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<div v-if="conn?.connected && !editing" class="space-y-2" data-testid="readwise-status">
|
||||
<p class="text-ui-md">
|
||||
{{ $t("readwise.goesTo", { space: spaceName || "…" }) }}
|
||||
</p>
|
||||
<p v-if="conn.lastError" class="text-ui-sm text-danger">{{ conn.lastError }}</p>
|
||||
<p v-else-if="conn.lastSync" class="text-ui-sm text-ink-muted">
|
||||
{{ $t("readwise.synced", { date: when(conn.lastSync), books: conn.books, n: conn.highlights }) }}
|
||||
</p>
|
||||
<p v-else class="text-ui-sm text-ink-muted">{{ $t("readwise.pending") }}</p>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-1.5 text-ui-sm">
|
||||
<input type="checkbox" :checked="conn.enabled" :disabled="busy" @change="toggle" />
|
||||
{{ $t("readwise.enabled") }}
|
||||
</label>
|
||||
<DwButton size="sm" icon="restore" :disabled="busy" data-testid="readwise-sync" @click="syncNow">
|
||||
{{ $t(busy ? "readwise.syncing" : "readwise.syncNow") }}
|
||||
</DwButton>
|
||||
<DwButton size="sm" variant="ghost" :disabled="busy" @click="editing = true">{{
|
||||
$t("readwise.change")
|
||||
}}</DwButton>
|
||||
<DwButton size="sm" variant="danger" :disabled="busy" @click="disconnect">{{
|
||||
$t("readwise.disconnect")
|
||||
}}</DwButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form v-else class="space-y-3" data-testid="readwise-form" @submit.prevent="save">
|
||||
<FormField
|
||||
v-model="token"
|
||||
:label="$t('readwise.token')"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
:required="!conn?.connected"
|
||||
:hint="$t('readwise.tokenHint')"
|
||||
:error="errors.fields.value.token"
|
||||
/>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<label class="flex min-w-48 flex-1 flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("readwise.workspace") }}</span>
|
||||
<select v-model="workspace" class="dw-input">
|
||||
<option v-for="w in workspaces.items" :key="w.id" :value="w.id">{{ w.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex min-w-48 flex-1 flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("readwise.space") }}</span>
|
||||
<select v-model="space" class="dw-input" data-testid="readwise-space">
|
||||
<option v-for="s in writable" :key="s.id" :value="s.id">{{ s.name }}</option>
|
||||
</select>
|
||||
<span v-if="errors.fields.value.space" class="text-ui-sm text-danger">{{ errors.fields.value.space }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<DwButton
|
||||
type="submit"
|
||||
variant="primary"
|
||||
:disabled="busy || !space || (!conn?.connected && !token.trim())"
|
||||
data-testid="readwise-save"
|
||||
>
|
||||
{{ $t(busy ? "readwise.checking" : "readwise.connect") }}
|
||||
</DwButton>
|
||||
<DwButton v-if="conn?.connected" variant="ghost" :disabled="busy" @click="editing = false">
|
||||
{{ $t("calendars.cancel") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1473,6 +1473,38 @@
|
||||
"confirmRemove": "Den Kalender „{name}“ entfernen?",
|
||||
"synced": "Gelesen {date} · {n} Termine",
|
||||
"today": "Kalender",
|
||||
"allDay": "Ganztägig"
|
||||
"allDay": "Ganztägig",
|
||||
"connectGoogle": "Google Kalender verbinden",
|
||||
"googleConnected": "Google Kalender ist verbunden. Seine Termine erscheinen in einer Minute auf deinen Journalseiten."
|
||||
},
|
||||
"onenote": {
|
||||
"button": "OneNote",
|
||||
"hint": "Ein ganzes OneNote-Notizbuch importieren: bei Microsoft anmelden und auswählen",
|
||||
"title": "Aus OneNote importieren",
|
||||
"signedIn": "Angemeldet als {account}. Das Notizbuch, seine Abschnitte und Seiten werden hier zu Seiten, mit ihren Bildern und Dateien.",
|
||||
"none": "Dieses Microsoft-Konto hat keine Notizbücher.",
|
||||
"notebook": "Notizbuch",
|
||||
"import": "Notizbuch importieren",
|
||||
"importing": "Wird importiert…",
|
||||
"progress": "{n} Seiten gelesen…"
|
||||
},
|
||||
"readwise": {
|
||||
"title": "Readwise",
|
||||
"hint": "Behalte deine Readwise-Markierungen in Docwell: Jede Stunde bekommen neue Bücher und Artikel eine Seite unter einer Seite „Readwise“, und neue Markierungen werden ihrer Seite hinzugefügt.",
|
||||
"token": "Readwise-Zugriffstoken",
|
||||
"tokenHint": "Von readwise.io/access_token. Leer lassen, um das gespeicherte zu behalten.",
|
||||
"workspace": "Workspace",
|
||||
"space": "Bereich",
|
||||
"connect": "Speichern",
|
||||
"checking": "Wird geprüft…",
|
||||
"goesTo": "Markierungen kommen in den Bereich „{space}“.",
|
||||
"synced": "Synchronisiert {date} · Bücher: {books} · Markierungen: {n}",
|
||||
"pending": "Die erste Synchronisierung läuft.",
|
||||
"enabled": "Stündlich synchronisieren",
|
||||
"syncNow": "Jetzt synchronisieren",
|
||||
"syncing": "Wird synchronisiert…",
|
||||
"change": "Ändern",
|
||||
"disconnect": "Trennen",
|
||||
"confirmDisconnect": "Readwise trennen? Die bisher erstellten Seiten bleiben."
|
||||
}
|
||||
}
|
||||
@@ -1473,6 +1473,38 @@
|
||||
"confirmRemove": "Remove the calendar “{name}”?",
|
||||
"synced": "Read {date} · {n} events",
|
||||
"today": "Calendar",
|
||||
"allDay": "All day"
|
||||
"allDay": "All day",
|
||||
"connectGoogle": "Connect Google Calendar",
|
||||
"googleConnected": "Google Calendar is connected. Its events appear on your journal pages in a minute."
|
||||
},
|
||||
"onenote": {
|
||||
"button": "OneNote",
|
||||
"hint": "Import a whole OneNote notebook: sign in to Microsoft and pick it",
|
||||
"title": "Import from OneNote",
|
||||
"signedIn": "Signed in as {account}. The notebook, its sections and pages become pages here, with their pictures and files.",
|
||||
"none": "This Microsoft account has no notebooks.",
|
||||
"notebook": "Notebook",
|
||||
"import": "Import notebook",
|
||||
"importing": "Importing…",
|
||||
"progress": "{n} pages read…"
|
||||
},
|
||||
"readwise": {
|
||||
"title": "Readwise",
|
||||
"hint": "Keep your Readwise highlights in Docwell: every hour, new books and articles get a page under a “Readwise” page, and new highlights are added to their page.",
|
||||
"token": "Readwise access token",
|
||||
"tokenHint": "From readwise.io/access_token. Leave it empty to keep the one you saved.",
|
||||
"workspace": "Workspace",
|
||||
"space": "Space",
|
||||
"connect": "Save",
|
||||
"checking": "Checking…",
|
||||
"goesTo": "Highlights go to the space “{space}”.",
|
||||
"synced": "Synced {date} · books: {books} · highlights: {n}",
|
||||
"pending": "The first sync is running.",
|
||||
"enabled": "Sync every hour",
|
||||
"syncNow": "Sync now",
|
||||
"syncing": "Syncing…",
|
||||
"change": "Change",
|
||||
"disconnect": "Disconnect",
|
||||
"confirmDisconnect": "Disconnect Readwise? The pages made so far stay."
|
||||
}
|
||||
}
|
||||
@@ -1473,6 +1473,38 @@
|
||||
"confirmRemove": "¿Quitar el calendario «{name}»?",
|
||||
"synced": "Leído {date} · {n} eventos",
|
||||
"today": "Calendario",
|
||||
"allDay": "Todo el día"
|
||||
"allDay": "Todo el día",
|
||||
"connectGoogle": "Conectar Google Calendar",
|
||||
"googleConnected": "Google Calendar está conectado. Sus eventos aparecerán en un minuto en tus páginas de diario."
|
||||
},
|
||||
"onenote": {
|
||||
"button": "OneNote",
|
||||
"hint": "Importar un bloc de notas de OneNote entero: inicia sesión en Microsoft y elígelo",
|
||||
"title": "Importar desde OneNote",
|
||||
"signedIn": "Sesión iniciada como {account}. El bloc de notas, sus secciones y páginas se convierten aquí en páginas, con sus imágenes y archivos.",
|
||||
"none": "Esta cuenta de Microsoft no tiene blocs de notas.",
|
||||
"notebook": "Bloc de notas",
|
||||
"import": "Importar bloc de notas",
|
||||
"importing": "Importando…",
|
||||
"progress": "{n} páginas leídas…"
|
||||
},
|
||||
"readwise": {
|
||||
"title": "Readwise",
|
||||
"hint": "Guarda tus subrayados de Readwise en Docwell: cada hora, los libros y artículos nuevos tienen una página bajo una página «Readwise», y los subrayados nuevos se añaden a su página.",
|
||||
"token": "Token de acceso de Readwise",
|
||||
"tokenHint": "En readwise.io/access_token. Déjalo vacío para conservar el guardado.",
|
||||
"workspace": "Espacio de trabajo",
|
||||
"space": "Espacio",
|
||||
"connect": "Guardar",
|
||||
"checking": "Comprobando…",
|
||||
"goesTo": "Los subrayados van al espacio «{space}».",
|
||||
"synced": "Sincronizado {date} · libros: {books} · subrayados: {n}",
|
||||
"pending": "La primera sincronización está en curso.",
|
||||
"enabled": "Sincronizar cada hora",
|
||||
"syncNow": "Sincronizar ahora",
|
||||
"syncing": "Sincronizando…",
|
||||
"change": "Cambiar",
|
||||
"disconnect": "Desconectar",
|
||||
"confirmDisconnect": "¿Desconectar Readwise? Las páginas creadas se mantienen."
|
||||
}
|
||||
}
|
||||
@@ -1473,6 +1473,38 @@
|
||||
"confirmRemove": "Retirer l'agenda « {name} » ?",
|
||||
"synced": "Lu {date} · {n} événements",
|
||||
"today": "Agenda",
|
||||
"allDay": "Toute la journée"
|
||||
"allDay": "Toute la journée",
|
||||
"connectGoogle": "Connecter Google Agenda",
|
||||
"googleConnected": "Google Agenda est connecté. Ses événements apparaîtront dans une minute sur vos pages de journal."
|
||||
},
|
||||
"onenote": {
|
||||
"button": "OneNote",
|
||||
"hint": "Importer tout un bloc-notes OneNote : connectez-vous à Microsoft et choisissez-le",
|
||||
"title": "Importer depuis OneNote",
|
||||
"signedIn": "Connecté en tant que {account}. Le bloc-notes, ses sections et ses pages deviennent des pages ici, avec leurs images et fichiers.",
|
||||
"none": "Ce compte Microsoft n'a aucun bloc-notes.",
|
||||
"notebook": "Bloc-notes",
|
||||
"import": "Importer le bloc-notes",
|
||||
"importing": "Import en cours…",
|
||||
"progress": "{n} pages lues…"
|
||||
},
|
||||
"readwise": {
|
||||
"title": "Readwise",
|
||||
"hint": "Gardez vos surlignages Readwise dans Docwell : chaque heure, les nouveaux livres et articles ont une page sous une page « Readwise », et les nouveaux surlignages sont ajoutés à leur page.",
|
||||
"token": "Jeton d'accès Readwise",
|
||||
"tokenHint": "Sur readwise.io/access_token. Laissez vide pour garder celui enregistré.",
|
||||
"workspace": "Espace de travail",
|
||||
"space": "Espace",
|
||||
"connect": "Enregistrer",
|
||||
"checking": "Vérification…",
|
||||
"goesTo": "Les surlignages vont dans l'espace « {space} ».",
|
||||
"synced": "Synchronisé {date} · livres : {books} · surlignages : {n}",
|
||||
"pending": "La première synchronisation est en cours.",
|
||||
"enabled": "Synchroniser chaque heure",
|
||||
"syncNow": "Synchroniser maintenant",
|
||||
"syncing": "Synchronisation…",
|
||||
"change": "Modifier",
|
||||
"disconnect": "Déconnecter",
|
||||
"confirmDisconnect": "Déconnecter Readwise ? Les pages déjà créées restent."
|
||||
}
|
||||
}
|
||||
@@ -1473,6 +1473,38 @@
|
||||
"confirmRemove": "Usunąć kalendarz „{name}”?",
|
||||
"synced": "Odczytano {date} · wydarzeń: {n}",
|
||||
"today": "Kalendarz",
|
||||
"allDay": "Cały dzień"
|
||||
"allDay": "Cały dzień",
|
||||
"connectGoogle": "Połącz Kalendarz Google",
|
||||
"googleConnected": "Kalendarz Google jest połączony. Jego wydarzenia pojawią się za minutę na stronach dziennika."
|
||||
},
|
||||
"onenote": {
|
||||
"button": "OneNote",
|
||||
"hint": "Zaimportuj cały notes OneNote: zaloguj się do Microsoft i wybierz go",
|
||||
"title": "Import z OneNote",
|
||||
"signedIn": "Zalogowano jako {account}. Notes, jego sekcje i strony staną się tu stronami, z obrazami i plikami.",
|
||||
"none": "To konto Microsoft nie ma notesów.",
|
||||
"notebook": "Notes",
|
||||
"import": "Importuj notes",
|
||||
"importing": "Importowanie…",
|
||||
"progress": "Odczytano stron: {n}…"
|
||||
},
|
||||
"readwise": {
|
||||
"title": "Readwise",
|
||||
"hint": "Trzymaj zakreślenia z Readwise w Docwell: co godzinę nowe książki i artykuły dostają stronę pod stroną „Readwise”, a nowe zakreślenia są dopisywane do ich strony.",
|
||||
"token": "Token dostępu Readwise",
|
||||
"tokenHint": "Z readwise.io/access_token. Zostaw puste, aby zachować zapisany.",
|
||||
"workspace": "Obszar roboczy",
|
||||
"space": "Przestrzeń",
|
||||
"connect": "Zapisz",
|
||||
"checking": "Sprawdzanie…",
|
||||
"goesTo": "Zakreślenia trafiają do przestrzeni „{space}”.",
|
||||
"synced": "Zsynchronizowano {date} · książek: {books} · zakreśleń: {n}",
|
||||
"pending": "Trwa pierwsza synchronizacja.",
|
||||
"enabled": "Synchronizuj co godzinę",
|
||||
"syncNow": "Synchronizuj teraz",
|
||||
"syncing": "Synchronizowanie…",
|
||||
"change": "Zmień",
|
||||
"disconnect": "Odłącz",
|
||||
"confirmDisconnect": "Odłączyć Readwise? Utworzone strony pozostaną."
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { useApi } from "../../api";
|
||||
import { useEditorPrefs } from "../../stores/preferences";
|
||||
import { localeNames, storedLocale, storeLocale, supportedLocales, type Locale } from "../../i18n";
|
||||
import CalendarAccounts from "../../components/CalendarAccounts.vue";
|
||||
import ReadwiseSync from "../../components/ReadwiseSync.vue";
|
||||
import FormField from "../../components/FormField.vue";
|
||||
import PageShell from "../../components/PageShell.vue";
|
||||
import { useFormErrors } from "../../composables/useFormErrors";
|
||||
@@ -259,6 +260,7 @@ const when = (s: string) =>
|
||||
</section>
|
||||
|
||||
<CalendarAccounts />
|
||||
<ReadwiseSync />
|
||||
|
||||
<!-- API tokens -->
|
||||
<section class="space-y-4 dw-card" data-testid="tokens-section">
|
||||
|
||||
@@ -6,6 +6,7 @@ import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import OneNoteImport from "../../components/OneNoteImport.vue";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import { saveBlob } from "../../lib/download";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
@@ -62,6 +63,13 @@ async function importPicked() {
|
||||
}
|
||||
}
|
||||
|
||||
// OneNote notebooks come in through Microsoft Graph (see OneNoteImport).
|
||||
const onenote = ref<InstanceType<typeof OneNoteImport> | null>(null);
|
||||
async function oneNoteDone(id: string) {
|
||||
await spaces.loadTree(props.id);
|
||||
router.push({ name: "page", params: { id } });
|
||||
}
|
||||
|
||||
// The whole space as a zip: one file per page, folders for subpages.
|
||||
const exporting = ref(false);
|
||||
async function exportSpace(format: "markdown" | "html") {
|
||||
@@ -184,12 +192,30 @@ async function newPage() {
|
||||
>
|
||||
{{ $t(importing ? "space.importing" : "space.import") }}
|
||||
</DwButton>
|
||||
<DwButton
|
||||
v-if="onenote?.enabled"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="upload"
|
||||
:title="$t('onenote.hint')"
|
||||
data-testid="onenote-connect"
|
||||
@click="onenote?.connect()"
|
||||
>
|
||||
{{ $t("onenote.button") }}
|
||||
</DwButton>
|
||||
<DwButton variant="ghost" size="sm" icon="plus" @click="newPage">
|
||||
{{ $t("app.newPage") }}
|
||||
</DwButton>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<OneNoteImport
|
||||
v-if="spaceAtLeast(space.role, 'editor')"
|
||||
ref="onenote"
|
||||
:space="space.id"
|
||||
@done="oneNoteDone"
|
||||
@error="emit('error', $event)"
|
||||
/>
|
||||
<PageList v-if="pages.length" :items="pages" class="mt-2" />
|
||||
<div
|
||||
v-else
|
||||
|
||||
@@ -27,3 +27,7 @@ The clipper finds the API through the web app's `/config.json`, so it works when
|
||||
## Use
|
||||
|
||||
Click the Docwell button in the toolbar. Check the title and the space, then *Clip article* (or *Clip selection* when text is selected), or *Whole page* to keep everything on the page. When it is saved, *Open in Docwell* opens the new page.
|
||||
|
||||
## Publish
|
||||
|
||||
`npm run package -w @docwell/web-clipper` builds store-ready zips for Chrome, Edge and Firefox (plus the source zip Firefox reviewers ask for) in `Web-Clipper/release/`. [store/STORE.md](store/STORE.md) walks through each store with the listing texts and permission justifications, and [store/PRIVACY.md](store/PRIVACY.md) is the privacy policy to link from the listings.
|
||||
@@ -8,7 +8,8 @@
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"package": "npm run build && node scripts/package.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mozilla/readability": "0.6.0",
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Packs the built extension (dist/) for the stores, into release/:
|
||||
//
|
||||
// docwell-web-clipper-<version>-chrome.zip Chrome Web Store, Edge Add-ons
|
||||
// docwell-web-clipper-<version>-firefox.zip addons.mozilla.org
|
||||
// docwell-web-clipper-<version>-source.zip the source AMO asks for, since dist/ is built
|
||||
//
|
||||
// Run `npm run package -w @docwell/web-clipper` (it builds first). Uses only
|
||||
// Node's own modules: the zips are written by hand with zlib's deflate.
|
||||
|
||||
import { deflateRawSync } from "node:zlib";
|
||||
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, relative, resolve, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const dist = join(root, "dist");
|
||||
const out = join(root, "release");
|
||||
|
||||
const crcTable = new Uint32Array(256).map((_, n) => {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
return c >>> 0;
|
||||
});
|
||||
function crc32(buf) {
|
||||
let c = 0xffffffff;
|
||||
for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
// A fixed time, so the same files make the same zip.
|
||||
const DOS_TIME = 0;
|
||||
const DOS_DATE = ((2024 - 1980) << 9) | (1 << 5) | 1;
|
||||
|
||||
/** Writes files ({name, data}) as a zip. */
|
||||
function zip(path, files) {
|
||||
const parts = [];
|
||||
const central = [];
|
||||
let offset = 0;
|
||||
for (const { name, data } of files) {
|
||||
const nameBuf = Buffer.from(name, "utf8");
|
||||
const packed = deflateRawSync(data, { level: 9 });
|
||||
const stored = packed.length >= data.length;
|
||||
const body = stored ? data : packed;
|
||||
const crc = crc32(data);
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
||||
local.writeUInt16LE(stored ? 0 : 8, 8);
|
||||
local.writeUInt16LE(DOS_TIME, 10);
|
||||
local.writeUInt16LE(DOS_DATE, 12);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(body.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(nameBuf.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
parts.push(local, nameBuf, body);
|
||||
const entry = Buffer.alloc(46);
|
||||
entry.writeUInt32LE(0x02014b50, 0);
|
||||
entry.writeUInt16LE(20, 4);
|
||||
entry.writeUInt16LE(20, 6);
|
||||
entry.writeUInt16LE(0x0800, 8);
|
||||
entry.writeUInt16LE(stored ? 0 : 8, 10);
|
||||
entry.writeUInt16LE(DOS_TIME, 12);
|
||||
entry.writeUInt16LE(DOS_DATE, 14);
|
||||
entry.writeUInt32LE(crc, 16);
|
||||
entry.writeUInt32LE(body.length, 20);
|
||||
entry.writeUInt32LE(data.length, 24);
|
||||
entry.writeUInt16LE(nameBuf.length, 28);
|
||||
entry.writeUInt32LE(offset, 42);
|
||||
central.push(entry, nameBuf);
|
||||
offset += local.length + nameBuf.length + body.length;
|
||||
}
|
||||
const centralBuf = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralBuf.length, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
writeFileSync(path, Buffer.concat([...parts, centralBuf, end]));
|
||||
console.log(`${relative(root, path)} (${files.length} files)`);
|
||||
}
|
||||
|
||||
/** Every file under dir, as zip names relative to base. */
|
||||
function walk(dir, base, skip = () => false) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(dir).sort()) {
|
||||
const full = join(dir, entry);
|
||||
const name = relative(base, full).split(sep).join("/");
|
||||
if (skip(name)) continue;
|
||||
if (statSync(full).isDirectory()) files.push(...walk(full, base, skip));
|
||||
else files.push({ name, data: readFileSync(full) });
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(readFileSync(join(dist, "manifest.json"), "utf8"));
|
||||
const version = manifest.version;
|
||||
mkdirSync(out, { recursive: true });
|
||||
const built = walk(dist, dist).filter((f) => f.name !== "manifest.json");
|
||||
const withManifest = (m) => [{ name: "manifest.json", data: Buffer.from(JSON.stringify(m, null, 2) + "\n") }, ...built];
|
||||
|
||||
// Chrome and Edge do not know Firefox's settings and warn about them.
|
||||
const chrome = { ...manifest };
|
||||
delete chrome.browser_specific_settings;
|
||||
zip(join(out, `docwell-web-clipper-${version}-chrome.zip`), withManifest(chrome));
|
||||
zip(join(out, `docwell-web-clipper-${version}-firefox.zip`), withManifest(manifest));
|
||||
|
||||
// AMO reviews the code the extension is built from: this folder as
|
||||
// Web-Clipper/, next to the repository files its build reads. It builds on
|
||||
// its own: cd Web-Clipper && npm install && npm run build.
|
||||
const repo = resolve(root, "..");
|
||||
const source = walk(root, root, (n) => /^(node_modules|dist|release)(\/|$)/.test(n)).map((f) => ({
|
||||
...f,
|
||||
name: `Web-Clipper/${f.name}`,
|
||||
}));
|
||||
for (const f of ["tsconfig.base.json", "LICENSE"]) source.push({ name: f, data: readFileSync(join(repo, f)) });
|
||||
zip(join(out, `docwell-web-clipper-${version}-source.zip`), source);
|
||||
@@ -0,0 +1,24 @@
|
||||
# Docwell Web Clipper — privacy policy
|
||||
|
||||
The Docwell Web Clipper is a browser extension that saves web pages to a Docwell server that you choose. It is published by the operator of that listing and is free software (AGPL-3.0); its source is in the Docwell repository, in `Web-Clipper/`.
|
||||
|
||||
## What the extension handles
|
||||
|
||||
- **The page you clip.** Only when you click the clipper's button, it reads the current tab's HTML, address, title and your selection. It turns them into Markdown inside the extension and sends that to your Docwell server as a new page. It reads nothing on pages you do not clip, and nothing in the background.
|
||||
- **Your settings.** The address of your Docwell server, your Docwell API token, and the workspace and space you picked are stored in the browser's extension storage on this device.
|
||||
|
||||
## Where it goes
|
||||
|
||||
Clips and requests go only to the Docwell server you entered in the options, over the connection that server offers (use `https://`). The extension sends nothing to the extension's publisher or to any other party, has no analytics or tracking, and loads no code from elsewhere.
|
||||
|
||||
What happens to a clip on your Docwell server is up to whoever runs that server; ask them for their privacy policy.
|
||||
|
||||
## Your control
|
||||
|
||||
- Remove a clip by deleting its page in Docwell.
|
||||
- Revoke the extension's access by deleting its API token in Docwell (*Account settings → API tokens*).
|
||||
- Remove the stored settings by removing the extension from the browser.
|
||||
|
||||
## Contact
|
||||
|
||||
Questions about this policy go to the publisher shown on the extension's store listing.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Publishing the Docwell Web Clipper
|
||||
|
||||
The packages come from one command:
|
||||
|
||||
```sh
|
||||
npm run package -w @docwell/web-clipper
|
||||
```
|
||||
|
||||
It builds the extension and writes three files to `Web-Clipper/release/`:
|
||||
|
||||
| File | For |
|
||||
|---|---|
|
||||
| `docwell-web-clipper-<version>-chrome.zip` | Chrome Web Store and Microsoft Edge Add-ons |
|
||||
| `docwell-web-clipper-<version>-firefox.zip` | addons.mozilla.org (AMO) |
|
||||
| `docwell-web-clipper-<version>-source.zip` | AMO's "source code" upload (the extension is built with Vite) |
|
||||
|
||||
Raise `version` in `public/manifest.json` (and `package.json`) before each new upload; the stores refuse a version they already have.
|
||||
|
||||
## Chrome Web Store
|
||||
|
||||
1. Sign in at <https://chrome.google.com/webstore/devconsole> with the account that will own the listing (a one-time developer registration fee applies).
|
||||
2. **New item** → upload the `-chrome.zip`.
|
||||
3. **Store listing:** paste the texts below, pick the category *Productivity → Tools* (or *Workflow & Planning*), upload the 128×128 icon (`public/icons/icon-128.png`) and at least one screenshot of 1280×800 or 640×400 (the popup over an article, and the options page, work well).
|
||||
4. **Privacy:** single purpose and permission justifications below; data use: the extension handles *website content* only to send it to the server the user configured, and sells or shares nothing. Link the privacy policy: publish `store/PRIVACY.md` somewhere public (the Docwell docs site, a repository page) and paste its address.
|
||||
5. Submit for review. Unlisted is fine if only your organization should find it.
|
||||
|
||||
## Microsoft Edge Add-ons
|
||||
|
||||
1. Sign in at <https://partner.microsoft.com/dashboard/microsoftedge> (registration is free).
|
||||
2. **Create new extension** → upload the same `-chrome.zip`.
|
||||
3. Fill in the same texts, category *Productivity*, the privacy policy address, and screenshots (1280×800).
|
||||
|
||||
## Firefox (addons.mozilla.org)
|
||||
|
||||
1. Sign in at <https://addons.mozilla.org/developers/> → **Submit a New Add-on**.
|
||||
2. Choose **On this site** (listed) or **On your own** (self-distributed, signed but not listed), and upload the `-firefox.zip`. The add-on id is `web-clipper@docwell.app` (in `public/manifest.json`); change it before the first upload if you publish under your own name.
|
||||
3. When asked whether the code is generated, answer yes and upload the `-source.zip`. Build instructions for the reviewer:
|
||||
|
||||
> Node 22 or later. Unzip, then `cd Web-Clipper && npm install && npm run build`. The extension is in `Web-Clipper/dist/`; it matches the uploaded package except for the source-path comments Vite writes at the top of each bundled module.
|
||||
|
||||
4. Fill in the listing texts, category *Other* or *Feeds, News & Blogging*, and the privacy policy.
|
||||
|
||||
## Listing texts
|
||||
|
||||
**Name:** Docwell Web Clipper
|
||||
|
||||
**Summary (max. 132 characters):** Save articles, pages and selections to your own Docwell server as new pages, with their links and pictures.
|
||||
|
||||
**Description:**
|
||||
|
||||
> Docwell Web Clipper saves what you are reading to Docwell, the open-source, self-hosted knowledge base.
|
||||
>
|
||||
> • Clip the article on a page: the clipper finds the main text (with Mozilla's Readability) and leaves menus, ads and sidebars out.
|
||||
> • Clip only what you selected, or the whole page.
|
||||
> • Links, pictures, code blocks and tables come along, under a note saying where the clip came from and when.
|
||||
> • Pick the space each clip goes to, and edit its title first.
|
||||
>
|
||||
> The clipper talks only to the Docwell server you connect it to, with a personal API token. It reads a page only when you click its button, and turns it into Markdown inside the extension before sending it.
|
||||
>
|
||||
> You need a Docwell server and an account on it. Docwell is free software (AGPL-3.0).
|
||||
|
||||
**Single purpose:** Save the web page the user is viewing, or the part they selected, as a new page on the user's own Docwell server.
|
||||
|
||||
**Permission justifications:**
|
||||
|
||||
| Permission | Why |
|
||||
|---|---|
|
||||
| `activeTab` | Reads the page in the current tab, and only when the user clicks the clipper's button. |
|
||||
| `scripting` | Runs the function that returns the page's HTML and the selection from that tab. |
|
||||
| `storage` | Keeps the server address, API token and chosen space on this device. |
|
||||
| Optional host access (`https://*/*`, `http://*/*`) | Asked for one origin only, the Docwell server the user enters in the options, so the clipper can send clips to it. No other site is requested. |
|
||||
|
||||
**Remote code:** none; everything the extension runs is in the package.
|
||||
+235
-3
@@ -2619,6 +2619,182 @@ paths:
|
||||
schema: { $ref: "#/components/schemas/Collection" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/integrations:
|
||||
get:
|
||||
operationId: getIntegrations
|
||||
tags: [integrations]
|
||||
summary: Which outside services this server can reach for people
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Integrations" }
|
||||
/api/v1/oauth/{provider}/callback:
|
||||
parameters:
|
||||
- { name: provider, in: path, required: true, schema: { type: string, enum: [google, microsoft] } }
|
||||
get:
|
||||
operationId: oauthCallback
|
||||
tags: [integrations]
|
||||
summary: Where Google and Microsoft send the browser back after a sign-in
|
||||
description: >-
|
||||
Register {DOCWELL_PUBLIC_URL}/api/v1/oauth/google/callback and
|
||||
{DOCWELL_PUBLIC_URL}/api/v1/oauth/microsoft/callback as redirect URIs of the OAuth apps.
|
||||
The signed state says who signed in and why; the browser is sent on to the web app.
|
||||
parameters:
|
||||
- { name: state, in: query, schema: { type: string } }
|
||||
- { name: code, in: query, schema: { type: string } }
|
||||
- { name: error, in: query, schema: { type: string } }
|
||||
responses:
|
||||
"302": { description: On to the web app }
|
||||
/api/v1/calendars/google/connect:
|
||||
get:
|
||||
operationId: connectGoogleCalendar
|
||||
tags: [calendars]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ConnectURL" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/onenote/connect:
|
||||
get:
|
||||
operationId: connectOneNote
|
||||
tags: [integrations]
|
||||
summary: Where to send the browser to sign in to Microsoft and import OneNote notebooks into a space
|
||||
description: Needs DOCWELL_MICROSOFT_CLIENT_ID and DOCWELL_MICROSOFT_CLIENT_SECRET. The browser returns to the space with ?onenote=<connection>.
|
||||
security: [{ bearer: [] }]
|
||||
parameters:
|
||||
- { name: space, in: query, required: true, schema: { type: string } }
|
||||
- { name: parent, in: query, schema: { type: string } }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ConnectURL" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/onenote/connections/{id}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getOneNoteConnection
|
||||
tags: [integrations]
|
||||
summary: The signed-in Microsoft account and its notebooks (a connection lasts an hour)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/OneNoteConnection" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/onenote/connections/{id}/import:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: importOneNoteNotebook
|
||||
tags: [integrations]
|
||||
summary: Start importing a notebook into a space (editor); it runs in the background
|
||||
description: >-
|
||||
The notebook, its section groups and sections become pages; each OneNote page a page under
|
||||
its section (subpages under their parent page), with pictures and attached files as
|
||||
attachments. At most 2000 pages and 512 MB of files.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [notebook, space]
|
||||
properties:
|
||||
notebook: { type: string }
|
||||
space: { type: string }
|
||||
parent: { type: string }
|
||||
responses:
|
||||
"202":
|
||||
description: Started
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/OneNoteJob" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/onenote/jobs/{id}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getOneNoteJob
|
||||
tags: [integrations]
|
||||
summary: How a OneNote import is going
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/OneNoteJob" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/readwise:
|
||||
get:
|
||||
operationId: getReadwise
|
||||
tags: [integrations]
|
||||
summary: The caller's Readwise sync (connected false when there is none)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ReadwiseConnection" }
|
||||
put:
|
||||
operationId: saveReadwise
|
||||
tags: [integrations]
|
||||
summary: Connect Readwise, or change where highlights go
|
||||
description: >-
|
||||
The token (readwise.io/access_token) is checked with Readwise and sealed. Every hour new
|
||||
books get a page under a "Readwise" page in the space, and new highlights are added to
|
||||
the end of their book's page. Choosing another space starts over there.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ReadwiseInput" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ReadwiseConnection" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
delete:
|
||||
operationId: deleteReadwise
|
||||
tags: [integrations]
|
||||
summary: Disconnect Readwise (the pages stay)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"204": { description: Disconnected }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/readwise/sync:
|
||||
post:
|
||||
operationId: syncReadwise
|
||||
tags: [integrations]
|
||||
summary: Add new Readwise highlights now
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: The sync with its result
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/ReadwiseConnection" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/calendars:
|
||||
get:
|
||||
operationId: listCalendars
|
||||
@@ -2691,7 +2867,7 @@ paths:
|
||||
post:
|
||||
operationId: refreshCalendar
|
||||
tags: [calendars]
|
||||
summary: Read a calendar from its source now (events are otherwise kept for 15 minutes)
|
||||
summary: Read a calendar from its source and store its events now (otherwise every 15 minutes)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
@@ -2706,8 +2882,10 @@ paths:
|
||||
tags: [calendars]
|
||||
summary: The caller's events between two days, from their enabled calendars
|
||||
description: >-
|
||||
Read from the stored copy the calendars.sync job keeps (every 15 minutes, 90 days back
|
||||
and 400 days ahead), so it answers at once and still shows events when a source is down.
|
||||
Repeating events are expanded, changed and cancelled occurrences applied. All-day events
|
||||
come first. A calendar that cannot be read is left out (its lastError says why).
|
||||
come first.
|
||||
security: [{ bearer: [] }]
|
||||
parameters:
|
||||
- { name: from, in: query, required: true, schema: { type: string, format: date } }
|
||||
@@ -4584,13 +4762,67 @@ components:
|
||||
What a value looks like: text and link a string, number a number, checkbox a
|
||||
boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option
|
||||
ids, member a list of user ids.
|
||||
Integrations:
|
||||
type: object
|
||||
required: [google, microsoft, readwise]
|
||||
properties:
|
||||
google: { type: boolean, description: People can connect Google Calendar }
|
||||
microsoft: { type: boolean, description: People can import OneNote notebooks }
|
||||
readwise: { type: boolean }
|
||||
ConnectURL:
|
||||
type: object
|
||||
required: [url]
|
||||
properties:
|
||||
url: { type: string, description: Where to send the browser }
|
||||
OneNoteNotebook:
|
||||
type: object
|
||||
required: [id, name, modified]
|
||||
properties:
|
||||
id: { type: string }
|
||||
name: { type: string }
|
||||
modified: { type: string }
|
||||
OneNoteConnection:
|
||||
type: object
|
||||
required: [account, notebooks]
|
||||
properties:
|
||||
account: { type: string, description: The Microsoft account signed in }
|
||||
notebooks: { type: array, items: { $ref: "#/components/schemas/OneNoteNotebook" } }
|
||||
OneNoteJob:
|
||||
type: object
|
||||
required: [id, notebook, status, pages, error, created]
|
||||
properties:
|
||||
id: { type: string }
|
||||
notebook: { type: string }
|
||||
status: { type: string, enum: [running, done, failed] }
|
||||
pages: { type: integer, description: OneNote pages read so far }
|
||||
error: { type: string }
|
||||
created: { type: array, items: { $ref: "#/components/schemas/Page" }, description: The pages made at the top }
|
||||
ReadwiseConnection:
|
||||
type: object
|
||||
required: [connected, workspace, space, parent, enabled, lastSync, lastError, highlights, books]
|
||||
properties:
|
||||
connected: { type: boolean }
|
||||
workspace: { type: string }
|
||||
space: { type: string }
|
||||
parent: { type: string, description: The "Readwise" page books go under }
|
||||
enabled: { type: boolean }
|
||||
lastSync: { type: string }
|
||||
lastError: { type: string }
|
||||
highlights: { type: integer }
|
||||
books: { type: integer }
|
||||
ReadwiseInput:
|
||||
type: object
|
||||
properties:
|
||||
token: { type: string, maxLength: 200, description: Empty keeps the stored one }
|
||||
space: { type: string }
|
||||
enabled: { type: boolean }
|
||||
CalendarAccount:
|
||||
type: object
|
||||
required: [id, name, kind, url, username, hasPassword, color, enabled, lastSync, lastError, events, created]
|
||||
properties:
|
||||
id: { type: string }
|
||||
name: { type: string }
|
||||
kind: { type: string, enum: [ics, caldav] }
|
||||
kind: { type: string, enum: [ics, caldav, google], description: "google accounts are connected with /calendars/google/connect" }
|
||||
url: { type: string }
|
||||
username: { type: string }
|
||||
hasPassword: { type: boolean }
|
||||
|
||||
Reference in new issue
Block a user