// 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 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 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 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 refresh() async => _session(await _send('POST', '/api/v1/auth/refresh')); User _session(Map 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); } /// The signed-in user (cached, so the app can start offline). Future me() async => User.fromJson(await _get('/api/v1/auth/me')); void logout() => token = null; // ---- Browsing (cached for offline reading) ------------------------------- Future> workspaces() async => (await _getList( '/api/v1/workspaces', )).map((e) => Workspace.fromJson(e as Map)).toList(); Future> spaces(String workspace) async => (await _getList( '/api/v1/workspaces/${_id(workspace)}/spaces', )).map((e) => Space.fromJson(e as Map)).toList(); /// The space's page tree as a flat list in depth-first order. Future> pages(String space) async => (await _getList( '/api/v1/spaces/${_id(space)}/pages', )).map((e) => PageNode.fromJson(e as Map)).toList(); Future page(String id) async => Page.fromJson(await _get('/api/v1/pages/${_id(id)}')); Future content(String id) async => PageContent.fromJson(await _get('/api/v1/pages/${_id(id)}/content')); Future> recent(String workspace) async => (await _getList( '/api/v1/workspaces/${_id(workspace)}/recent', )).map((e) => PageItem.fromJson(e as Map)).toList(); Future 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 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 saveContent(String page, Map 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 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> calendars() async => (await _getList( '/api/v1/calendars', )).map((e) => CalendarAccount.fromJson(e as Map)).toList(); /// Adds an event to a calendar, written to its source at once (ADR-19). Future createCalendarEvent(CalendarEventInput input) async => CalendarEvent.fromJson( await _send('POST', '/api/v1/calendar/events', input.toJson()), ); /// Changes an editable event; a 409 means it changed in its calendar since /// the last sync, and nothing was overwritten. Future updateCalendarEvent( String id, CalendarEventInput input, ) async => CalendarEvent.fromJson( await _send('PATCH', '/api/v1/calendar/events/${_id(id)}', input.toJson()), ); Future deleteCalendarEvent(String id) => _send('DELETE', '/api/v1/calendar/events/${_id(id)}'); /// The caller's calendar events from day from to day to (inclusive, UTC). Future> calendarEvents(String from, String to) async => (await _getList( '/api/v1/calendar/events?from=${_id(from)}&to=${_id(to)}', )).map((e) => CalendarEvent.fromJson(e as Map)).toList(); /// Records that the user opened the page, for their recent list. Future visit(String page) => _send('POST', '/api/v1/pages/${_id(page)}/visit'); // ---- Comments ------------------------------------------------------------ Future> comments(String page) async => (await _getList( '/api/v1/pages/${_id(page)}/comments', )).map((e) => Comment.fromJson(e as Map)).toList(); Future 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 resolveComment(String id, bool resolved) => _send( 'POST', '/api/v1/comments/${_id(id)}/resolve', {'resolved': resolved}, ); // ---- Notifications ------------------------------------------------------- Future notifications() async => NotificationList.fromJson( await _send('GET', '/api/v1/notifications?limit=50'), ); Future markRead({List 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 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 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(String workspace) async => AiAvailability.fromJson( await _send('GET', '/api/v1/workspaces/${_id(workspace)}/ai'), ); Future> aiSessions(String workspace) async => ((await _send( 'GET', '/api/v1/workspaces/${_id(workspace)}/ai/sessions', ))['items'] as List) .map((e) => AiSessionSummary.fromJson(e as Map)) .toList(); Future aiSession(String id) async => AiSession.fromJson(await _send('GET', '/api/v1/ai/sessions/${_id(id)}')); Future 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 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 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 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 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); } DocwellApiException _apiError(int status, String text) { Map data = {}; try { data = jsonDecode(text) as Map; } catch (_) {} return DocwellApiException( status, code: data['error'] as String? ?? 'unknown', message: data['message'] as String? ?? '', ); } Stream _stream(String path, Map 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> _get(String path) async => (await _cached(path)) as Map; Future> _getList(String path) async => (await _cached(path)) as List; /// A GET that falls back to the cached copy when the server is unreachable. Future _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> _send( String method, String path, [ Object? body, ]) async { final raw = await _raw(method, path, body); if (raw.isEmpty) return {}; final data = jsonDecode(raw); return data is Map ? data : {'items': data}; } Future _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 data = {}; try { data = jsonDecode(text) as Map; } 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? ?? 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 data; } /// Splits a text/event-stream into events with JSON data. Stream parseEventStream(Stream 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 ? 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 fields; /// The most specific explanation the server gave, or ''. String get explanation => fields.values.firstOrNull ?? message; @override String toString() => 'Docwell API error $status ($code)'; }