// 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'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'l10n.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 createState() => _DocwellAppState(); } class _DocwellAppState extends State { final _navigator = GlobalKey(); 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 _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 _onLogin(DocwellApi api, User user) async { await widget.sessions.save(api.baseUrl, api.token!); _server = api.baseUrl; _signedIn(api, user); } Future _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/` (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( 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( builder: (_) => ShareScreen(session: s, shared: shared), ), ); } @override Widget build(BuildContext context) { const brand = Color(0xFF2F7D6D); final s = _session; return MaterialApp( title: 'Docwell', // The phone's language where the app has it (lib/l10n.dart), else English. supportedLocales: [for (final l in appLanguages) Locale(l)], localizationsDelegates: GlobalMaterialLocalizations.delegates, localeListResolutionCallback: (phone, _) { final lang = pickLanguage(phone ?? const []); setAppLanguage(lang); return Locale(lang); }, 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), ); } }