CalDAV and Google calendars can now be written to from the journal on
the web and in the phone app. Each change goes to the source at once
with If-Match set to the ETag the last sync read, so a change made
elsewhere is refused (409) instead of overwritten; the account is then
read again. Repeating events, iCal feeds and read-only Google calendars
stay read-only.
- calendar_events keep each event's calendar, object/event id, ETag and
whether it repeats; accounts keep their writable calendars and the
one new events go to (migration 1764800000_calendar_writes).
- Google sign-in asks for calendar.events; older read-only accounts are
offered "Connect again".
- New API: POST /calendar/events, PATCH and DELETE /calendar/events/{id}.
- Translations, Docs-Site guides and changelog updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
495 lines
17 KiB
Dart
495 lines
17 KiB
Dart
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import '../l10n.dart';
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import 'generated/models.dart';
|
|
import 'response_cache.dart';
|
|
|
|
export 'generated/models.dart';
|
|
export 'response_cache.dart';
|
|
|
|
/// docwell-server client. Requests are written by hand; the models are
|
|
/// generated from api/openapi.yaml (tool/generate_api.dart).
|
|
///
|
|
/// Reads go through [cache]: every successful GET is kept, and when the
|
|
/// server can't be reached the last copy is returned instead, so pages read
|
|
/// before stay readable offline. [offline] says whether the last read came
|
|
/// from the cache.
|
|
class DocwellApi {
|
|
DocwellApi(
|
|
String baseUrl, {
|
|
http.Client? client,
|
|
ResponseCache? cache,
|
|
this.onUnauthorized,
|
|
}) : baseUrl = baseUrl.replaceAll(RegExp(r'/+$'), ''),
|
|
_client = client ?? http.Client(),
|
|
cache = cache ?? MemoryCache();
|
|
|
|
final String baseUrl;
|
|
final http.Client _client;
|
|
final ResponseCache cache;
|
|
|
|
/// Called when the server rejects the token (expired, signed out elsewhere).
|
|
void Function()? onUnauthorized;
|
|
|
|
/// PocketBase auth token of the signed-in user, sent as a bearer token.
|
|
String? token;
|
|
|
|
/// Whether the last read came from the offline cache.
|
|
bool offline = false;
|
|
|
|
/// The live-editing WebSocket address.
|
|
String get collabUrl =>
|
|
'${baseUrl.replaceFirst(RegExp('^http'), 'ws')}/collab';
|
|
|
|
Future<String> version() async {
|
|
final body = await _send('GET', '/api/v1/version');
|
|
return body['version'] as String;
|
|
}
|
|
|
|
// ---- Sign-in -------------------------------------------------------------
|
|
|
|
/// Signs in with email and password and keeps the token for later calls.
|
|
/// Accounts with two-step sign-in answer [TotpRequired].
|
|
Future<User> login(String email, String password) async {
|
|
final body = await _send('POST', '/api/v1/auth/login', {
|
|
'email': email,
|
|
'password': password,
|
|
});
|
|
return _session(body);
|
|
}
|
|
|
|
/// Second step: a code from an authenticator app, or a recovery code.
|
|
Future<User> verifyTotp(String challenge, String code) async => _session(
|
|
await _send('POST', '/api/v1/auth/totp/verify', {
|
|
'challenge': challenge,
|
|
'code': code,
|
|
}),
|
|
);
|
|
|
|
/// Swaps the saved token for a fresh one at start-up.
|
|
Future<User> refresh() async =>
|
|
_session(await _send('POST', '/api/v1/auth/refresh'));
|
|
|
|
User _session(Map<String, dynamic> body) {
|
|
token = body['token'] as String;
|
|
// Kept so the next start without a connection still knows who this is.
|
|
unawaited(cache.write('/api/v1/auth/me', jsonEncode(body['user'])));
|
|
return User.fromJson(body['user'] as Map<String, dynamic>);
|
|
}
|
|
|
|
/// The signed-in user (cached, so the app can start offline).
|
|
Future<User> me() async => User.fromJson(await _get('/api/v1/auth/me'));
|
|
|
|
void logout() => token = null;
|
|
|
|
// ---- Browsing (cached for offline reading) -------------------------------
|
|
|
|
Future<List<Workspace>> workspaces() async => (await _getList(
|
|
'/api/v1/workspaces',
|
|
)).map((e) => Workspace.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
Future<List<Space>> spaces(String workspace) async => (await _getList(
|
|
'/api/v1/workspaces/${_id(workspace)}/spaces',
|
|
)).map((e) => Space.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
/// The space's page tree as a flat list in depth-first order.
|
|
Future<List<PageNode>> pages(String space) async => (await _getList(
|
|
'/api/v1/spaces/${_id(space)}/pages',
|
|
)).map((e) => PageNode.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
Future<Page> page(String id) async =>
|
|
Page.fromJson(await _get('/api/v1/pages/${_id(id)}'));
|
|
|
|
Future<PageContent> content(String id) async =>
|
|
PageContent.fromJson(await _get('/api/v1/pages/${_id(id)}/content'));
|
|
|
|
Future<List<PageItem>> recent(String workspace) async => (await _getList(
|
|
'/api/v1/workspaces/${_id(workspace)}/recent',
|
|
)).map((e) => PageItem.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
Future<SearchResult> search(
|
|
String workspace,
|
|
String q,
|
|
) async => SearchResult.fromJson(
|
|
await _send(
|
|
'GET',
|
|
'/api/v1/workspaces/${_id(workspace)}/search?q=${Uri.encodeQueryComponent(q)}&limit=30',
|
|
),
|
|
);
|
|
|
|
// ---- Writing -------------------------------------------------------------
|
|
|
|
Future<Page> createPage(
|
|
String space, {
|
|
String title = '',
|
|
String parent = '',
|
|
}) async => Page.fromJson(
|
|
await _send('POST', '/api/v1/spaces/${_id(space)}/pages', {
|
|
'title': title,
|
|
if (parent.isNotEmpty) 'parent': parent,
|
|
}),
|
|
);
|
|
|
|
/// Replaces the page's document (Tiptap JSON).
|
|
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 calendars (ADR-16); the ones with canWrite take new events.
|
|
Future<List<CalendarAccount>> calendars() async => (await _getList(
|
|
'/api/v1/calendars',
|
|
)).map((e) => CalendarAccount.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
/// Adds an event to a calendar, written to its source at once (ADR-19).
|
|
Future<CalendarEvent> createCalendarEvent(CalendarEventInput input) async =>
|
|
CalendarEvent.fromJson(
|
|
await _send('POST', '/api/v1/calendar/events', input.toJson()),
|
|
);
|
|
|
|
/// Changes an editable event; a 409 means it changed in its calendar since
|
|
/// the last sync, and nothing was overwritten.
|
|
Future<CalendarEvent> updateCalendarEvent(
|
|
String id,
|
|
CalendarEventInput input,
|
|
) async => CalendarEvent.fromJson(
|
|
await _send('PATCH', '/api/v1/calendar/events/${_id(id)}', input.toJson()),
|
|
);
|
|
|
|
Future<void> deleteCalendarEvent(String id) =>
|
|
_send('DELETE', '/api/v1/calendar/events/${_id(id)}');
|
|
|
|
/// The caller's calendar events from day from to day to (inclusive, UTC).
|
|
Future<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');
|
|
|
|
// ---- Comments ------------------------------------------------------------
|
|
|
|
Future<List<Comment>> comments(String page) async => (await _getList(
|
|
'/api/v1/pages/${_id(page)}/comments',
|
|
)).map((e) => Comment.fromJson(e as Map<String, dynamic>)).toList();
|
|
|
|
Future<Comment> addComment(
|
|
String page,
|
|
String body, {
|
|
String parent = '',
|
|
}) async => Comment.fromJson(
|
|
await _send('POST', '/api/v1/pages/${_id(page)}/comments', {
|
|
'body': body,
|
|
if (parent.isNotEmpty) 'parent': parent,
|
|
}),
|
|
);
|
|
|
|
/// Resolves a thread, or opens it again.
|
|
Future<void> resolveComment(String id, bool resolved) => _send(
|
|
'POST',
|
|
'/api/v1/comments/${_id(id)}/resolve',
|
|
{'resolved': resolved},
|
|
);
|
|
|
|
// ---- Notifications -------------------------------------------------------
|
|
|
|
Future<NotificationList> notifications() async => NotificationList.fromJson(
|
|
await _send('GET', '/api/v1/notifications?limit=50'),
|
|
);
|
|
|
|
Future<void> markRead({List<String> ids = const [], bool all = false}) =>
|
|
_send('POST', '/api/v1/notifications/read', {'ids': ids, 'all': all});
|
|
|
|
/// Registers this phone's UnifiedPush endpoint and Web Push keys.
|
|
Future<PushDevice> registerDevice({
|
|
required String endpoint,
|
|
required String p256dh,
|
|
required String auth,
|
|
String name = '',
|
|
}) async => PushDevice.fromJson(
|
|
await _send('POST', '/api/v1/me/devices', {
|
|
'endpoint': endpoint,
|
|
'p256dh': p256dh,
|
|
'auth': auth,
|
|
'name': name,
|
|
}),
|
|
);
|
|
|
|
Future<void> removeDevice(String id) =>
|
|
_send('DELETE', '/api/v1/me/devices/${_id(id)}');
|
|
|
|
// ---- AI (ADR-15) ----------------------------------------------------------
|
|
|
|
/// What AI offers in a workspace. A server without AI answers 404.
|
|
Future<AiAvailability> aiAvailability(String workspace) async =>
|
|
AiAvailability.fromJson(
|
|
await _send('GET', '/api/v1/workspaces/${_id(workspace)}/ai'),
|
|
);
|
|
|
|
Future<List<AiSessionSummary>> aiSessions(String workspace) async =>
|
|
((await _send(
|
|
'GET',
|
|
'/api/v1/workspaces/${_id(workspace)}/ai/sessions',
|
|
))['items']
|
|
as List<dynamic>)
|
|
.map((e) => AiSessionSummary.fromJson(e as Map<String, dynamic>))
|
|
.toList();
|
|
|
|
Future<AiSession> aiSession(String id) async =>
|
|
AiSession.fromJson(await _send('GET', '/api/v1/ai/sessions/${_id(id)}'));
|
|
|
|
Future<AiSession> createAiSession(
|
|
String workspace,
|
|
AiScope scope, {
|
|
String scopeId = '',
|
|
}) async => AiSession.fromJson(
|
|
await _send('POST', '/api/v1/workspaces/${_id(workspace)}/ai/sessions', {
|
|
'scope': scope.value,
|
|
'scopeId': scopeId,
|
|
}),
|
|
);
|
|
|
|
Future<void> deleteAiSession(String id) =>
|
|
_send('DELETE', '/api/v1/ai/sessions/${_id(id)}');
|
|
|
|
/// Asks a question; the answer streams as events: sources {citations},
|
|
/// delta {text}, then done {user, message} or error {message}.
|
|
Stream<AiEvent> ask(String session, String question) => _stream(
|
|
'/api/v1/ai/sessions/${_id(session)}/messages',
|
|
{'content': question},
|
|
);
|
|
|
|
/// A writing action on text (AiWriteInput); the result (Markdown) streams
|
|
/// as delta {text} events, then done {} or error {message}.
|
|
Stream<AiEvent> write(
|
|
String workspace, {
|
|
required String action,
|
|
required String text,
|
|
String before = '',
|
|
String language = '',
|
|
String instruction = '',
|
|
}) => _stream('/api/v1/workspaces/${_id(workspace)}/ai/write', {
|
|
'action': action,
|
|
'text': text,
|
|
'before': before,
|
|
'language': language,
|
|
'instruction': instruction,
|
|
});
|
|
|
|
/// Turns an audio or video attachment into text and a summary. Long
|
|
/// recordings take a while, so this waits up to 30 minutes.
|
|
Future<AiTranscript> transcribe(String fileId) async {
|
|
final req = http.Request(
|
|
'POST',
|
|
Uri.parse('$baseUrl/api/v1/files/${_id(fileId)}/transcribe'),
|
|
);
|
|
req.headers['Accept'] = 'application/json';
|
|
req.headers['Content-Type'] = 'application/json';
|
|
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
|
// The server writes its messages in the language the app shows.
|
|
req.headers['Accept-Language'] = appLanguage;
|
|
req.body = jsonEncode({'summarize': true});
|
|
final res = await http.Response.fromStream(
|
|
await _client.send(req).timeout(const Duration(minutes: 30)),
|
|
);
|
|
final text = utf8.decode(res.bodyBytes);
|
|
if (res.statusCode >= 300) throw _apiError(res.statusCode, text);
|
|
return AiTranscript.fromJson(jsonDecode(text) as Map<String, dynamic>);
|
|
}
|
|
|
|
DocwellApiException _apiError(int status, String text) {
|
|
Map<String, dynamic> data = {};
|
|
try {
|
|
data = jsonDecode(text) as Map<String, dynamic>;
|
|
} catch (_) {}
|
|
return DocwellApiException(
|
|
status,
|
|
code: data['error'] as String? ?? 'unknown',
|
|
message: data['message'] as String? ?? '',
|
|
);
|
|
}
|
|
|
|
Stream<AiEvent> _stream(String path, Map<String, dynamic> body) async* {
|
|
final req = http.Request('POST', Uri.parse('$baseUrl$path'));
|
|
req.headers['Accept'] = 'text/event-stream';
|
|
req.headers['Content-Type'] = 'application/json';
|
|
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
|
// The server writes its messages in the language the app shows.
|
|
req.headers['Accept-Language'] = appLanguage;
|
|
req.body = jsonEncode(body);
|
|
final res = await _client.send(req).timeout(const Duration(seconds: 30));
|
|
if (res.statusCode >= 300) {
|
|
throw _apiError(res.statusCode, await res.stream.bytesToString());
|
|
}
|
|
yield* parseEventStream(res.stream.transform(utf8.decoder));
|
|
}
|
|
|
|
// ---- Transport -----------------------------------------------------------
|
|
|
|
static String _id(String id) => Uri.encodeComponent(id);
|
|
|
|
Future<Map<String, dynamic>> _get(String path) async =>
|
|
(await _cached(path)) as Map<String, dynamic>;
|
|
|
|
Future<List<dynamic>> _getList(String path) async =>
|
|
(await _cached(path)) as List<dynamic>;
|
|
|
|
/// A GET that falls back to the cached copy when the server is unreachable.
|
|
Future<Object?> _cached(String path) async {
|
|
try {
|
|
final raw = await _raw('GET', path);
|
|
offline = false;
|
|
unawaited(cache.write(path, raw));
|
|
return raw.isEmpty ? null : jsonDecode(raw);
|
|
} on DocwellApiException {
|
|
rethrow;
|
|
} catch (e) {
|
|
final copy = await cache.read(path);
|
|
if (copy == null) rethrow;
|
|
offline = true;
|
|
return jsonDecode(copy);
|
|
}
|
|
}
|
|
|
|
Future<Map<String, dynamic>> _send(
|
|
String method,
|
|
String path, [
|
|
Object? body,
|
|
]) async {
|
|
final raw = await _raw(method, path, body);
|
|
if (raw.isEmpty) return <String, dynamic>{};
|
|
final data = jsonDecode(raw);
|
|
return data is Map<String, dynamic> ? data : {'items': data};
|
|
}
|
|
|
|
Future<String> _raw(String method, String path, [Object? body]) async {
|
|
final req = http.Request(method, Uri.parse('$baseUrl$path'));
|
|
req.headers['Accept'] = 'application/json';
|
|
if (token != null) req.headers['Authorization'] = 'Bearer $token';
|
|
// The server writes its messages in the language the app shows.
|
|
req.headers['Accept-Language'] = appLanguage;
|
|
if (body != null) {
|
|
req.headers['Content-Type'] = 'application/json';
|
|
req.body = jsonEncode(body);
|
|
}
|
|
final res = await http.Response.fromStream(
|
|
await _client.send(req).timeout(const Duration(seconds: 15)),
|
|
);
|
|
final text = utf8.decode(res.bodyBytes);
|
|
if (res.statusCode >= 300) {
|
|
Map<String, dynamic> data = {};
|
|
try {
|
|
data = jsonDecode(text) as Map<String, dynamic>;
|
|
} catch (_) {}
|
|
if (res.statusCode == HttpStatus.unauthorized &&
|
|
token != null &&
|
|
!path.startsWith('/api/v1/auth/')) {
|
|
onUnauthorized?.call();
|
|
}
|
|
throw DocwellApiException(
|
|
res.statusCode,
|
|
code: data['error'] as String? ?? 'unknown',
|
|
challenge: data['challenge'] as String? ?? '',
|
|
message: data['message'] as String? ?? '',
|
|
fields: (data['fields'] as Map<String, dynamic>? ?? const {}).map(
|
|
(k, v) => MapEntry(k, '$v'),
|
|
),
|
|
);
|
|
}
|
|
return text;
|
|
}
|
|
}
|
|
|
|
extension UserRoles on User {
|
|
/// Admins manage their organization; superadmins manage everything.
|
|
bool get isManager => role == Role.admin || role == Role.superadmin;
|
|
}
|
|
|
|
extension SpaceRoles on SpaceRole {
|
|
/// May change the page's text.
|
|
bool get canEdit => this == SpaceRole.admin || this == SpaceRole.editor;
|
|
|
|
/// May add comments.
|
|
bool get canComment => canEdit || this == SpaceRole.commenter;
|
|
}
|
|
|
|
/// One server-sent event of a streamed AI answer.
|
|
class AiEvent {
|
|
const AiEvent(this.name, this.data);
|
|
final String name;
|
|
final Map<String, dynamic> data;
|
|
}
|
|
|
|
/// Splits a text/event-stream into events with JSON data.
|
|
Stream<AiEvent> parseEventStream(Stream<String> chunks) async* {
|
|
var buf = '';
|
|
await for (final chunk in chunks) {
|
|
buf += chunk.replaceAll('\r\n', '\n');
|
|
var cut = buf.indexOf('\n\n');
|
|
while (cut >= 0) {
|
|
final block = buf.substring(0, cut);
|
|
buf = buf.substring(cut + 2);
|
|
var name = 'message';
|
|
final data = StringBuffer();
|
|
for (final line in block.split('\n')) {
|
|
if (line.startsWith('event:')) {
|
|
name = line.substring(6).trim();
|
|
} else if (line.startsWith('data:')) {
|
|
data.write(line.substring(5).trimLeft());
|
|
}
|
|
}
|
|
if (data.isNotEmpty) {
|
|
final decoded = jsonDecode(data.toString());
|
|
yield AiEvent(name, decoded is Map<String, dynamic> ? decoded : {});
|
|
}
|
|
cut = buf.indexOf('\n\n');
|
|
}
|
|
}
|
|
}
|
|
|
|
class DocwellApiException implements Exception {
|
|
DocwellApiException(
|
|
this.status, {
|
|
this.code = 'unknown',
|
|
this.challenge = '',
|
|
this.message = '',
|
|
this.fields = const {},
|
|
});
|
|
|
|
final int status;
|
|
|
|
/// Machine-readable error code from the server, e.g. "invalid_credentials".
|
|
final String code;
|
|
|
|
/// Set with "totp_required": send it to [DocwellApi.verifyTotp] with a code.
|
|
final String challenge;
|
|
|
|
/// The server's human-readable explanation, when it sent one.
|
|
final String message;
|
|
|
|
/// Per-field explanations of a "validation" error.
|
|
final Map<String, String> fields;
|
|
|
|
/// The most specific explanation the server gave, or ''.
|
|
String get explanation => fields.values.firstOrNull ?? message;
|
|
|
|
@override
|
|
String toString() => 'Docwell API error $status ($code)';
|
|
}
|