import '../ui/adaptive/platform.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import '../core/session/server_session.dart'; import '../core/servers/server_catalog.dart'; import '../core/servers/server_catalog_store.dart'; import '../core/servers/server_probe.dart'; import '../core/transport/pipelines_client.dart'; import '../features/onboarding/onboarding_flow.dart'; import '../features/settings/server_connections.dart'; import '../features/settings/saved_servers_section.dart'; import '../features/settings/settings_store.dart'; import '../ui/theme/app_theme.dart'; import 'pipelines_app.dart'; import 'server_endpoint.dart'; /// The phone app's root: onboarding until a server and its password are /// known, then the app. A saved session the server later refuses brings the /// password step back; an unreachable server just reconnects in the app. class PipelinesRoot extends StatefulWidget { const PipelinesRoot({ super.key, required this.server, this.buildDefault = '', this.signedIn = false, this.check = ServerSession.check, this.settingsStore = const SharedPreferencesSettingsStore(), this.catalogStore = const SharedPreferencesServerCatalogStore(), this.web = kIsWeb, this.clientFactory, }); final ServerEndpoint server; /// The server this build was made for; it pre-fills onboarding. final String buildDefault; /// A session is kept on this device. final bool signedIn; final ServerCheck check; final SettingsStore settingsStore; final ServerCatalogStore catalogStore; final bool web; final PipelinesClient Function()? clientFactory; @override State createState() => _PipelinesRootState(); } class _PipelinesRootState extends State { late ServerEndpoint _server = widget.server; late bool _onboarding = widget.server.uri == null || !widget.signedIn; bool _refused = false; int _generation = 0; bool _booting = true; int _activation = 0; PipelinesClient? _client; SavedServer? _activeServer; late final ServerConnections _servers = ServerConnections( store: widget.catalogStore, onSelected: _selectServer, ); @override void initState() { super.initState(); _loadServers(); } Future _loadServers() async { await _servers.load(legacyEndpoint: widget.server.uri?.toString() ?? ''); if (!mounted) return; if (widget.web) { if (widget.server.uri != null) { _servers.alignBrowserOrigin(widget.server.uri!); } setState(() { _booting = false; _onboarding = false; _client = widget.clientFactory?.call(); }); return; } final persisted = _servers.catalog.active == null || await _servers.persist(); if (!mounted) return; if (!persisted) { ServerSession.clearSelection(); setState(() { _booting = false; _onboarding = true; }); return; } await _activate(_servers.catalog.active, initial: true); } Future _selectServer(SavedServer? server) async { if (widget.web) { if (server == null) return; final endpoint = Uri.parse(server.endpoints.first); if (endpoint == _server.uri) { _servers.alignBrowserOrigin(endpoint); return; } final page = endpoint.replace( scheme: endpoint.scheme == 'wss' ? 'https' : 'http', path: '/', query: null, fragment: null, ); if (!await launchUrl(page, webOnlyWindowName: '_self')) { if (_server.uri != null) _servers.alignBrowserOrigin(_server.uri!); throw StateError('Could not open the selected server.'); } return; } if (server != null && server.id == _activeServer?.id && listEquals(server.endpoints, _activeServer?.endpoints)) { _activeServer = server; return; } await _activate(server); } Future _activate(SavedServer? server, {bool initial = false}) async { final token = ++_activation; if (!initial) { setState(() => _booting = true); // Dispose the old app/socket before changing the credential namespace. await WidgetsBinding.instance.endOfFrame; } if (!mounted || token != _activation) return; if (server == null) { ServerSession.clearSelection(); } else { await ServerSession.activateServer( id: server.id, endpoints: server.endpoints.map(Uri.parse), migrateLegacy: server.id == 'legacy-server', ); } if (!mounted || token != _activation) return; _activeServer = server; setState(() { _server = ServerEndpoint.resolve( base: Uri.base, web: false, configured: server?.endpoints.first ?? '', ); _onboarding = server == null || (ServerSession.cookie == null && !(initial && widget.signedIn && server.id == 'legacy-server')); _refused = false; _generation++; _booting = false; _client = _onboarding ? null : widget.clientFactory?.call(); }); if (!_onboarding && _server.uri != null) { _verify(_server.uri!); } } /// A kept session the server now refuses asks for the password again. Future _verify(Uri endpoint) async { final token = _activation; final result = await probeServerAddresses( [ endpoint, ...?_activeServer?.endpoints .map(Uri.parse) .where((uri) => uri != endpoint), ], check: widget.check, isCurrent: () => mounted && token == _activation, ); if (!mounted || token != _activation || result.state != SessionState.signedOut) { return; } setState(() { _refused = true; _onboarding = true; _server = ServerEndpoint.resolve( base: Uri.base, web: false, configured: result.endpoint.toString(), ); }); } void _done(Uri endpoint) { _activeServer = _servers.catalog.active; setState(() { _server = ServerEndpoint.resolve( base: Uri.base, web: false, configured: endpoint.toString(), ); _onboarding = false; _refused = false; _generation++; _client = widget.clientFactory?.call(); }); } Future _saveOnboardingServer(String url) async { final token = _activation; final active = _servers.catalog.active; SavedServer? target; for (final server in _servers.catalog.servers) { if (server.endpoints.contains(url)) target = server; } target ??= SavedServer.validated( id: 'server-${DateTime.now().microsecondsSinceEpoch}', name: active == null ? 'My server' : 'New server', endpoints: [url], ); if (!await _servers.save(target, activate: false) || !await _servers.select(target.id, activate: false)) { throw StateError(_servers.error ?? 'Could not save the server.'); } if (!mounted || token != _activation) { throw StateError('The selected server changed.'); } await ServerSession.activateServer( id: target.id, endpoints: target.endpoints.map(Uri.parse), migrateLegacy: target.id == 'legacy-server', ); await widget.settingsStore.saveServerUrl(url); } @override void dispose() { _activation++; _servers.dispose(); super.dispose(); } bool get _cupertino => prefersCupertino(); @override Widget build(BuildContext context) { if (_booting) { // A temporary App/Navigator would replace the browser's deep-link URL // before the real Router reads it. Loading must not own navigation. return MediaQuery.fromView( view: View.of(context), child: Directionality( textDirection: TextDirection.ltr, child: _cupertino ? const CupertinoTheme( data: appCupertinoTheme, child: Center(child: CupertinoActivityIndicator()), ) : Theme( data: appLightTheme(), child: const Center(child: CircularProgressIndicator()), ), ), ); } if (!_onboarding) { return PipelinesApp( key: ValueKey(_generation), server: _server, client: _client, knownServer: true, serverAddresses: widget.web ? null : _servers.catalog.active?.endpoints.map(Uri.parse).toList(), serverId: _servers.catalog.active?.id, servers: _servers, legacyPendingEndpoints: [?_servers.catalog.active?.legacyEndpoint], resetRoute: !widget.web && _generation > 1, ); } final flow = OnboardingFlow( initialServer: _server.uri?.toString() ?? widget.buildDefault, startAtPassword: _refused, saveServer: _saveOnboardingServer, onDone: _done, savedServers: SavedServersSection(connections: _servers), serverAddresses: _servers.catalog.active?.endpoints.map(Uri.parse).toList() ?? const [], ); return _cupertino ? CupertinoApp( title: 'Pipelines', theme: appCupertinoTheme, debugShowCheckedModeBanner: false, home: flow, ) : MaterialApp( title: 'Pipelines', theme: appLightTheme(), darkTheme: appDarkTheme(), debugShowCheckedModeBanner: false, home: flow, ); } }