Mobile app (Android):
- Sign-in to any server, with authenticator codes. The server address and
token are kept in secure storage; a dropped connection never signs out.
- Workspaces, recent pages, spaces and a foldable page tree; search; the
inbox with mark-read.
- Pages open read-only in the shared editor from their saved content and
join the live document to edit (with the native toolbar). Page links in
the text open in the app (new "navigate" bridge message).
- Comments: threads, replies, resolve.
- "Save to Docwell" in the Android share sheet makes a page from shared
text, with web addresses as links.
- Offline reading: every answer the app reads is kept on the phone, and
used when the server can't be reached.
- Push through UnifiedPush (ntfy, NextPush, ...). The app uses the Android
connector directly; the umbrella package pulls in a native crypto build
for Linux that breaks `dart run` and tests.
Server:
- /me/devices registers a phone's UnifiedPush endpoint and Web Push keys
(new push_devices collection). Each notification is also pushed,
encrypted with RFC 8291 aes128gcm so the distributor can't read it; the
app drops messages that don't decrypt. Endpoints answering 404/410 are
forgotten. Endpoints follow the webhook address rules.
- /collab accepts the apps' own origins ("null" for the mobile editor page,
wails:// for the desktop app). Sign-in is a token in the first message,
not a cookie, so this opens no cross-site hijacking.
Tried on an Android 15 emulator: sign-in, browsing, reading, live editing,
sharing and offline reading. Not covered: push end to end (no distributor
on the emulator), iOS, and YouTube embeds, which refuse to play from the
app's local editor page (error 153).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
303 lines
9.6 KiB
Dart
303 lines
9.6 KiB
Dart
// 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<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});
|
|
|
|
/// 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)}');
|
|
|
|
// ---- 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';
|
|
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? ?? '',
|
|
);
|
|
}
|
|
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)';
|
|
}
|