Files
Docwell/Phone-App/lib/api/docwell_api.dart
T
tajniak81andClaude Opus 5.5 0ebf064173
CI / go (Server) (push) Failing after 25m5s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m38s
CI / desktop (ubuntu-latest) (push) Successful in 1h41m20s
CI / mobile (push) Failing after 4m19s
CI / docker (push) Failing after 44m8s
Docs / build (push) Successful in 17m11s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add audio transcripts, monthly AI limits, PDF sources and AI chat on phones
Follow-ups to Phase E (ADR-15):

- Transcription (E2): OpenAI-compatible profiles can name a speech-to-text
  model; POST /files/{id}/transcribe turns an audio or video attachment
  (up to 25 MB) into text and a summary with key points and action items.
  The editor gets a Transcribe button on media files that inserts the
  summary and the transcript in a toggle.
- Monthly token limits: ai_usage counts requests and tokens per workspace
  and month. Workspace admins can cap their workspace; superadmins can cap
  what each workspace uses through the server's providers, after which
  the workspace's own providers keep working. The admin panel lists usage.
- PDF text for extra retrieval files (ledongthuc/pdf, pure Go).
- Phone app: an AI chat screen for the workspace or a page, with streamed
  answers and sources that open the cited block.
- OpenAPI, generated clients, migration, translations and docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:26:27 +01:00

398 lines
13 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)}');
// ---- 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) async* {
final req = http.Request(
'POST',
Uri.parse('$baseUrl/api/v1/ai/sessions/${_id(session)}/messages'),
);
req.headers['Accept'] = 'text/event-stream';
req.headers['Content-Type'] = 'application/json';
if (token != null) req.headers['Authorization'] = 'Bearer $token';
req.body = jsonEncode({'content': question});
final res = await _client.send(req).timeout(const Duration(seconds: 30));
if (res.statusCode >= 300) {
final text = await res.stream.bytesToString();
Map<String, dynamic> data = {};
try {
data = jsonDecode(text) as Map<String, dynamic>;
} catch (_) {}
throw DocwellApiException(
res.statusCode,
code: data['error'] as String? ?? 'unknown',
message: data['message'] as String? ?? '',
);
}
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';
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;
}
/// 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 = '',
});
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)';
}