Files
Docwell/Phone-App/lib/editor/bridge.dart
T
tajniak81andClaude Opus 5.5 1f580ca6f8 Add Mobile 1.0 and UnifiedPush notifications
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>
2026-11-01 14:52:20 +01:00

178 lines
5.1 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
// The native side of the editor bridge (ADR-4). The editor page lives in
// Packages/editor-bridge; keep these messages in sync with its protocol.ts.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
/// Protocol version this app speaks. The page reports its own in "ready".
const editorProtocolVersion = 1;
/// Formatting the native toolbar can apply.
enum EditorCommand {
bold,
italic,
strike,
code,
heading1,
heading2,
heading3,
bulletList,
orderedList,
blockquote,
codeBlock,
undo,
redo,
}
/// Toolbar state reported by the page.
@immutable
class EditorState {
const EditorState({
this.active = const {},
this.canUndo = false,
this.canRedo = false,
this.focused = false,
});
factory EditorState.fromJson(Map<String, dynamic> json) => EditorState(
active: {
for (final name in (json['active'] as List).cast<String>())
...EditorCommand.values.where((c) => c.name == name),
},
canUndo: json['canUndo'] as bool,
canRedo: json['canRedo'] as bool,
focused: json['focused'] as bool,
);
final Set<EditorCommand> active;
final bool canUndo;
final bool canRedo;
final bool focused;
}
/// Drives the editor page. It does not know about the WebView: [evaluate]
/// runs JavaScript in the page, and the host passes every message the page
/// sends to [handleMessage].
class EditorBridge extends ChangeNotifier {
EditorBridge({required this.evaluate, this._content});
final Future<void> Function(String script) evaluate;
Map<String, dynamic>? _content;
EditorState _state = const EditorState();
bool _ready = false;
String? _error;
final _readyCompleter = Completer<void>();
final _changes = StreamController<Map<String, dynamic>>.broadcast();
final _navigations = StreamController<String>.broadcast();
/// The latest document (Tiptap JSON), null until there is one.
Map<String, dynamic>? get content => _content;
EditorState get state => _state;
bool get isReady => _ready;
/// Live-editing status after [connect]: connecting, connected, offline,
/// denied or changed (see CollabStatus in @docwell/editor).
String? get collabStatus => _collabStatus;
String? _collabStatus;
/// Set when the page is missing, outdated or reported a problem.
String? get error => _error;
/// Completes once the page answered and holds the initial content.
Future<void> get ready => _readyCompleter.future;
/// Every edit the user makes.
Stream<Map<String, dynamic>> get changes => _changes.stream;
/// App routes of page links the user followed, e.g. `/p/<id>`.
Stream<String> get navigations => _navigations.stream;
/// Call once the page has loaded.
Future<void> hello() => _post({'type': 'hello'});
Future<void> run(EditorCommand c) =>
_post({'type': 'command', 'command': c.name});
Future<void> setContent(Map<String, dynamic>? content) {
_content = content;
return _post({'type': 'setContent', 'content': content});
}
Future<void> setEditable(bool editable) =>
_post({'type': 'setEditable', 'editable': editable});
Future<void> setTheme({required bool dark}) =>
_post({'type': 'setTheme', 'dark': dark});
Future<void> focus() => _post({'type': 'focus'});
/// Edits the live page through docwell-server instead of local content.
Future<void> connect({
required String url,
required String page,
required String token,
required String userName,
required String userColor,
}) => _post({
'type': 'connect',
'url': url,
'page': page,
'token': token,
'user': {'name': userName, 'color': userColor},
});
/// Handles one JSON message from the page.
void handleMessage(String json) {
final msg = jsonDecode(json) as Map<String, dynamic>;
switch (msg['type']) {
case 'ready':
final version = msg['version'] as int;
if (version != editorProtocolVersion) {
_error =
'Editor page speaks protocol $version, app expects '
'$editorProtocolVersion';
notifyListeners();
return;
}
// The page may say ready twice (start-up and hello); load content once.
if (_ready) return;
_ready = true;
unawaited(
setContent(_content).then((_) {
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
}),
);
notifyListeners();
case 'change':
_content = msg['content'] as Map<String, dynamic>;
_changes.add(_content!);
case 'state':
_state = EditorState.fromJson(msg['state'] as Map<String, dynamic>);
notifyListeners();
case 'collab':
_collabStatus = msg['status'] as String;
notifyListeners();
case 'navigate':
_navigations.add(msg['path'] as String);
case 'error':
_error = msg['message'] as String;
notifyListeners();
}
}
Future<void> _post(Map<String, dynamic> msg) =>
evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})');
@override
void dispose() {
_changes.close();
_navigations.close();
super.dispose();
}
}