// SPDX-License-Identifier: AGPL-3.0-or-later 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}); /// 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)}'); // ---- 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'; 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? ?? '', ); } 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; } class DocwellApiException implements Exception { DocwellApiException( this.status, { this.code = 'unknown', this.challenge = '', this.message = '', }); 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; @override String toString() => 'Docwell API error $status ($code)'; }