| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386 |
- import 'dart:async';
- import 'package:flutter/material.dart';
- import 'package:http/http.dart' as http;
- import '../data/api_client.dart';
- import '../data/settings_store.dart';
- import '../design.dart';
- import 'home_shell.dart';
- import 'privacy_policy_screen.dart';
- class ConnectionScreen extends StatefulWidget {
- const ConnectionScreen({super.key, required this.settings, this.httpClient});
- final SettingsStore settings;
- final http.Client? httpClient;
- @override
- State<ConnectionScreen> createState() => _ConnectionScreenState();
- }
- class _ConnectionScreenState extends State<ConnectionScreen> {
- final _baseUrl = TextEditingController();
- final _apiKey = TextEditingController();
- late final http.Client _client = widget.httpClient ?? http.Client();
- Timer? _probeTimer;
- int _probeToken = 0;
- bool _busy = false;
- bool _probing = false;
- bool _showApiKey = false;
- bool _statusUnavailable = false;
- String? _error;
- String? _reachabilityError;
- ApiStatus? _serverStatus;
- @override
- void dispose() {
- _probeTimer?.cancel();
- _baseUrl.dispose();
- _apiKey.dispose();
- if (widget.httpClient == null) _client.close();
- super.dispose();
- }
- void _onAddressChanged(String value) {
- _probeTimer?.cancel();
- final token = ++_probeToken;
- final canProbe = serverUrlCandidates(value).isNotEmpty;
- setState(() {
- _probing = canProbe;
- _serverStatus = null;
- _statusUnavailable = false;
- _reachabilityError = null;
- _error = null;
- });
- if (!canProbe) return;
- _probeTimer = Timer(const Duration(milliseconds: 600), () {
- _checkAddress(value, token);
- });
- }
- Future<({String baseUrl, ApiStatus? status})> _probeAddress(
- String address,
- ) async {
- final candidates = serverUrlCandidates(address);
- if (candidates.isEmpty) {
- throw ApiException('Enter a server address, optionally with a port.');
- }
- ApiException? lastError;
- for (final candidate in candidates) {
- try {
- final status = await RackPeekApi(
- baseUrl: candidate,
- apiKey: '',
- client: _client,
- ).getStatus();
- return (baseUrl: candidate, status: status);
- } on ApiException catch (e) {
- if (e.statusCode == 404) {
- return (baseUrl: candidate, status: null);
- }
- lastError = e;
- }
- }
- throw lastError ?? ApiException('Could not reach a RackPeek server.');
- }
- Future<void> _checkAddress(String address, int token) async {
- try {
- final result = await _probeAddress(address);
- if (!mounted || token != _probeToken) return;
- setState(() {
- _serverStatus = result.status;
- _statusUnavailable = result.status == null;
- _reachabilityError = null;
- _probing = false;
- });
- } on ApiException catch (e) {
- if (!mounted || token != _probeToken) return;
- setState(() {
- _reachabilityError = e.message;
- _serverStatus = null;
- _statusUnavailable = false;
- _probing = false;
- });
- }
- }
- Future<void> _connect() async {
- final address = _baseUrl.text.trim();
- final apiKey = _apiKey.text.trim();
- if (serverUrlCandidates(address).isEmpty) {
- setState(
- () => _error = 'Enter a server address, optionally with a port.',
- );
- return;
- }
- if (apiKey.isEmpty) {
- setState(() => _error = 'Enter the API key (RPK_API_KEY on the server).');
- return;
- }
- _probeTimer?.cancel();
- final token = ++_probeToken;
- setState(() {
- _busy = true;
- _probing = true;
- _error = null;
- _reachabilityError = null;
- });
- try {
- final result = await _probeAddress(address);
- if (!mounted || token != _probeToken) return;
- setState(() {
- _serverStatus = result.status;
- _statusUnavailable = result.status == null;
- _probing = false;
- });
- final api = RackPeekApi(
- baseUrl: result.baseUrl,
- apiKey: apiKey,
- client: _client,
- );
- await api.getSummary();
- final shouldContinue = await _resolveLocalChanges(api, result.baseUrl);
- if (shouldContinue != true) return;
- await widget.settings.save(result.baseUrl, apiKey);
- if (!mounted) return;
- Navigator.of(context).pushAndRemoveUntil(
- MaterialPageRoute(
- builder: (_) => HomeShell(
- settings: widget.settings,
- baseUrl: result.baseUrl,
- apiKey: apiKey,
- httpClient: widget.httpClient,
- ),
- ),
- (route) => false,
- );
- } on ApiException catch (e) {
- if (!mounted) return;
- setState(() {
- _error = e.message;
- _probing = false;
- });
- } finally {
- if (mounted) setState(() => _busy = false);
- }
- }
- Future<bool?> _resolveLocalChanges(RackPeekApi api, String baseUrl) async {
- final state = await widget.settings.loadOfflineState();
- final pending = state?['pendingChanges'];
- final hasPending = pending is List && pending.isNotEmpty;
- var upload = false;
- if (hasPending) {
- if (!mounted) return false;
- final choice = await showDialog<bool>(
- context: context,
- barrierDismissible: false,
- builder: (dialogContext) => AlertDialog(
- title: const Text('Local changes found'),
- content: Text(
- '${pending.length} change(s) are saved on this phone. '
- 'Upload them to $baseUrl, or discard them and use the server inventory?',
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(dialogContext, null),
- child: const Text('Cancel'),
- ),
- TextButton(
- onPressed: () => Navigator.pop(dialogContext, false),
- child: const Text('Discard local changes'),
- ),
- FilledButton(
- onPressed: () => Navigator.pop(dialogContext, true),
- child: const Text('Upload to server'),
- ),
- ],
- ),
- );
- if (choice == null) return null;
- upload = choice;
- if (upload) {
- final rawDocument = state?['document'];
- final version = rawDocument is Map
- ? rawDocument['version'] as int? ?? 5
- : 5;
- for (final change in pending.whereType<Map>()) {
- await api.upsert({
- 'version': version,
- 'resources': [Map<String, dynamic>.from(change)],
- });
- }
- }
- }
- final serverDocument = await api.getDocument();
- await widget.settings.saveOfflineState({
- 'document': serverDocument.toJson(),
- 'pendingChanges': <Map<String, dynamic>>[],
- });
- return true;
- }
- Widget _reachabilityIndicator() {
- if (_probing) {
- return const Row(
- children: [
- SizedBox(
- width: 16,
- height: 16,
- child: CircularProgressIndicator(strokeWidth: 2),
- ),
- SizedBox(width: 10),
- Expanded(child: Text('Checking server…')),
- ],
- );
- }
- if (_serverStatus case final status?) {
- return Row(
- children: [
- const Icon(Icons.check_circle, color: ScribeColors.success, size: 18),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- 'Server reachable · API v${status.apiVersion} · ${status.appVersion}',
- style: const TextStyle(color: ScribeColors.success),
- ),
- ),
- ],
- );
- }
- if (_statusUnavailable) {
- return const Row(
- children: [
- Icon(Icons.info_outline, color: ScribeColors.secondaryText, size: 18),
- SizedBox(width: 8),
- Expanded(child: Text('Server reachable · API version unavailable')),
- ],
- );
- }
- if (_reachabilityError case final message?) {
- return Row(
- children: [
- const Icon(Icons.error_outline, color: ScribeColors.danger, size: 18),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- message,
- style: const TextStyle(color: ScribeColors.danger),
- ),
- ),
- ],
- );
- }
- return const Text(
- 'HTTPS is tried first; HTTP is used if TLS is unavailable.',
- style: ScribeType.metadata,
- );
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- body: ScribeSheet(
- children: [
- const SizedBox(height: 32),
- const Center(child: Wordmark()),
- const Text(
- 'Your infrastructure, in your pocket. Connect to a RackPeek server '
- 'or skip to build and manage a local inventory.',
- textAlign: TextAlign.center,
- style: ScribeType.body,
- ),
- SurfacePanel(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- const SectionLabel('Server'),
- const SizedBox(height: ScribeSpacing.relatedGap),
- TextField(
- controller: _baseUrl,
- enabled: !_busy,
- keyboardType: TextInputType.url,
- autocorrect: false,
- onChanged: _onAddressChanged,
- decoration: const InputDecoration(
- hintText: '192.168.1.10:8080 or server.example.com',
- labelText: 'Server address',
- ),
- ),
- const SizedBox(height: ScribeSpacing.relatedGap),
- _reachabilityIndicator(),
- const SizedBox(height: ScribeSpacing.majorSectionGap),
- const SectionLabel('API key'),
- const SizedBox(height: ScribeSpacing.relatedGap),
- TextField(
- controller: _apiKey,
- enabled: !_busy,
- keyboardType: TextInputType.visiblePassword,
- obscureText: !_showApiKey,
- autocorrect: false,
- enableSuggestions: false,
- decoration: InputDecoration(
- labelText: 'API key',
- helperText: 'Stored securely on this device.',
- suffixIcon: IconButton(
- tooltip: _showApiKey ? 'Hide API key' : 'Show API key',
- onPressed: () =>
- setState(() => _showApiKey = !_showApiKey),
- icon: Icon(
- _showApiKey ? Icons.visibility_off : Icons.visibility,
- ),
- ),
- ),
- ),
- const SizedBox(height: ScribeSpacing.majorSectionGap),
- ScribeAction(
- label: 'Connect',
- busy: _busy,
- onPressed: _connect,
- ),
- const SizedBox(height: ScribeSpacing.relatedGap),
- ScribeAction(
- label: 'Skip and use offline',
- secondary: true,
- busy: _busy,
- onPressed: _useOffline,
- ),
- ],
- ),
- ),
- if (_error != null) InlineNotice(message: _error!, isError: true),
- Center(
- child: TextButton(
- onPressed: () => Navigator.of(context).push(
- MaterialPageRoute(builder: (_) => const PrivacyPolicyScreen()),
- ),
- child: const Text('Privacy policy'),
- ),
- ),
- ],
- ),
- );
- }
- Future<void> _useOffline() async {
- await widget.settings.useLocalMode();
- if (!mounted) return;
- Navigator.of(context).pushReplacement(
- MaterialPageRoute(builder: (_) => HomeShell(settings: widget.settings)),
- );
- }
- }
|