Files
Docwell/Phone-App/lib/app.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

182 lines
4.9 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:async';
import 'package:flutter/material.dart';
import 'api/docwell_api.dart';
import 'push.dart';
import 'screens/home_screen.dart';
import 'screens/login_screen.dart';
import 'screens/page_screen.dart';
import 'screens/share_screen.dart';
import 'session.dart';
import 'share.dart';
/// Makes a client for a server address (with its offline cache).
typedef ApiFactory = DocwellApi Function(String server);
/// What the signed-in screens share.
class AppSession {
AppSession({required this.api, required this.user, this.push});
final DocwellApi api;
final User user;
final PushService? push;
}
class DocwellApp extends StatefulWidget {
const DocwellApp({
super.key,
required this.sessions,
required this.apiFor,
this.push,
this.shares,
this.defaultServer = '',
});
final SessionStore sessions;
final ApiFactory apiFor;
final PushService? push;
final ShareReceiver? shares;
/// Pre-filled on the sign-in screen the first time.
final String defaultServer;
@override
State<DocwellApp> createState() => _DocwellAppState();
}
class _DocwellAppState extends State<DocwellApp> {
final _navigator = GlobalKey<NavigatorState>();
AppSession? _session;
bool _restoring = true;
String _server = '';
// A route or share that arrived before sign-in finished.
String? _pendingRoute;
SharedText? _pendingShare;
@override
void initState() {
super.initState();
unawaited(_restore());
unawaited(widget.push?.init(_openRoute));
unawaited(widget.shares?.listen(_openShare));
}
/// Signs back in with the saved token. Only the server rejecting it signs
/// out; without a connection the app starts offline with cached pages.
Future<void> _restore() async {
_server = await widget.sessions.lastServer() ?? widget.defaultServer;
final saved = await widget.sessions.load();
if (saved != null) {
final api = widget.apiFor(saved.server)..token = saved.token;
try {
final user = await api.refresh();
await widget.sessions.save(saved.server, api.token!);
_signedIn(api, user);
} on DocwellApiException {
await widget.sessions.clearToken();
} catch (_) {
try {
// Offline: the last /auth/me answer is in the cache.
_signedIn(api, await api.me());
} catch (_) {}
}
}
if (mounted) setState(() => _restoring = false);
}
void _signedIn(DocwellApi api, User user) {
api.onUnauthorized = _signOut;
widget.push?.api = api;
setState(
() => _session = AppSession(api: api, user: user, push: widget.push),
);
final route = _pendingRoute;
final share = _pendingShare;
_pendingRoute = null;
_pendingShare = null;
if (route != null) _openRoute(route);
if (share != null) _openShare(share);
}
Future<void> _onLogin(DocwellApi api, User user) async {
await widget.sessions.save(api.baseUrl, api.token!);
_server = api.baseUrl;
_signedIn(api, user);
}
Future<void> _signOut() async {
final s = _session;
if (s == null) return;
await widget.push?.disable();
widget.push?.api = null;
s.api.logout();
await s.api.cache.clear();
await widget.sessions.clearToken();
_navigator.currentState?.popUntil((r) => r.isFirst);
if (mounted) setState(() => _session = null);
}
/// Opens an app route from a notification: `/p/<id>` (with `?comment=…`).
void _openRoute(String route) {
final s = _session;
if (s == null) {
_pendingRoute = route;
return;
}
final uri = Uri.parse(route);
if (uri.pathSegments.length == 2 && uri.pathSegments[0] == 'p') {
_navigator.currentState?.push(
MaterialPageRoute<void>(
builder: (_) => PageScreen(
session: s,
pageId: uri.pathSegments[1],
openComment: uri.queryParameters['comment'],
),
),
);
}
}
void _openShare(SharedText shared) {
final s = _session;
if (s == null) {
_pendingShare = shared;
return;
}
_navigator.currentState?.push(
MaterialPageRoute<void>(
builder: (_) => ShareScreen(session: s, shared: shared),
),
);
}
@override
Widget build(BuildContext context) {
const brand = Color(0xFF2F7D6D);
final s = _session;
return MaterialApp(
title: 'Docwell',
navigatorKey: _navigator,
theme: ThemeData(colorSchemeSeed: brand, useMaterial3: true),
darkTheme: ThemeData(
colorSchemeSeed: brand,
brightness: Brightness.dark,
useMaterial3: true,
),
home: _restoring
? const Scaffold(body: Center(child: CircularProgressIndicator()))
: s == null
? LoginScreen(
server: _server,
apiFor: widget.apiFor,
onSignedIn: _onLogin,
)
: HomeScreen(session: s, onSignOut: _signOut),
);
}
}