Files
mileograph_flutter/lib/components/pages/settings.dart
Pete Gregory cea483ae0b
Some checks failed
Release / android-build (push) Blocked by required conditions
Release / meta (push) Successful in 10s
Release / linux-build (push) Successful in 6m39s
Release / release-dev (push) Has been cancelled
Release / release-master (push) Has been cancelled
Add ability to select distance unit
2026-01-01 15:28:11 +00:00

387 lines
13 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:mileograph_flutter/services/endpoint_service.dart';
import 'package:mileograph_flutter/services/data_service.dart';
import 'package:provider/provider.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
late final TextEditingController _endpointController;
bool _saving = false;
bool _changingPassword = false;
final _passwordFormKey = GlobalKey<FormState>();
late final TextEditingController _currentPasswordController;
late final TextEditingController _newPasswordController;
late final TextEditingController _confirmPasswordController;
@override
void initState() {
super.initState();
final endpoint = context.read<EndpointService>().baseUrl;
_endpointController = TextEditingController(text: endpoint);
_currentPasswordController = TextEditingController();
_newPasswordController = TextEditingController();
_confirmPasswordController = TextEditingController();
}
@override
void dispose() {
_currentPasswordController.dispose();
_newPasswordController.dispose();
_confirmPasswordController.dispose();
_endpointController.dispose();
super.dispose();
}
Future<String?> _probeVersion(String url) async {
try {
var uri = Uri.parse(url.trim());
if (uri.scheme.isEmpty) {
uri = Uri.parse('https://$url');
}
// Probe the provided API endpoint as-is.
final target = uri;
final res = await http.get(target).timeout(const Duration(seconds: 10));
debugPrint(
'Endpoint probe ${target.toString()} -> ${res.statusCode} ${res.body}',
);
if (res.statusCode < 200 || res.statusCode >= 300) return null;
final body = res.body.trim();
debugPrint('Endpoint probe body: $body');
// Try JSON first
String? version;
try {
final parsed = jsonDecode(body);
debugPrint('Endpoint probe parsed: $parsed');
if (parsed is Map && parsed['version'] is String) {
version = parsed['version'] as String;
} else if (parsed is String) {
final candidate = parsed.trim().replaceAll('"', '');
if (RegExp(r'^\d+\.\d+\.\d+$').hasMatch(candidate)) {
version = candidate;
}
}
} catch (_) {
// fall back to raw body parsing
}
version ??= body.split(RegExp(r'\s+')).firstWhere(
(part) => RegExp(r'^\d+\.\d+\.\d+$').hasMatch(part),
orElse: () => '',
);
if (version.isEmpty) return null;
final isValid = RegExp(r'^\d+\.\d+\.\d+$').hasMatch(version);
return isValid ? version : null;
} catch (_) {
return null;
}
}
Future<void> _save() async {
final endpointService = context.read<EndpointService>();
final dataService = context.read<DataService>();
final messenger = ScaffoldMessenger.of(context);
final value = _endpointController.text.trim();
if (value.isEmpty) {
messenger.showSnackBar(
const SnackBar(content: Text('Please enter an endpoint URL.')),
);
return;
}
setState(() => _saving = true);
try {
final version = await _probeVersion(value);
if (version == null) {
if (mounted) {
messenger.showSnackBar(
const SnackBar(
content: Text('Endpoint test failed: no valid version returned.'),
),
);
}
return;
}
await endpointService.setBaseUrl(value);
if (mounted) {
messenger.showSnackBar(
SnackBar(content: Text('Endpoint set to "$value" ($version)')),
);
await Future.wait([
dataService.fetchHomepageStats(),
dataService.fetchOnThisDay(),
dataService.fetchTrips(),
dataService.fetchHadTraction(),
dataService.fetchLatestLocoChanges(),
dataService.fetchLegs(),
]);
}
} catch (e) {
if (mounted) {
messenger.showSnackBar(
SnackBar(content: Text('Failed to save endpoint: $e')),
);
}
} finally {
if (mounted) {
setState(() => _saving = false);
}
}
}
Future<void> _changePassword() async {
final messenger = ScaffoldMessenger.of(context);
final formState = _passwordFormKey.currentState;
if (formState == null || !formState.validate()) return;
FocusScope.of(context).unfocus();
setState(() => _changingPassword = true);
try {
final api = context.read<ApiService>();
await api.post('/user/password/change', {
'old_password': _currentPasswordController.text,
'new_password': _newPasswordController.text,
});
if (!mounted) return;
messenger.showSnackBar(
const SnackBar(content: Text('Password updated successfully.')),
);
formState.reset();
_currentPasswordController.clear();
_newPasswordController.clear();
_confirmPasswordController.clear();
} catch (e) {
if (mounted) {
messenger.showSnackBar(
SnackBar(content: Text('Failed to change password: $e')),
);
}
} finally {
if (mounted) {
setState(() => _changingPassword = false);
}
}
}
@override
Widget build(BuildContext context) {
final endpointService = context.watch<EndpointService>();
final distanceUnitService = context.watch<DistanceUnitService>();
final loggedIn = context.select<AuthService, bool>(
(auth) => auth.isLoggedIn,
);
if (!endpointService.isLoaded || !distanceUnitService.isLoaded) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
final navigator = Navigator.of(context);
if (navigator.canPop()) {
navigator.pop();
} else {
context.go('/');
}
},
),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Distance units',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Choose how distances are displayed across the app.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
SegmentedButton<DistanceUnit>(
segments: DistanceUnit.values
.map(
(unit) => ButtonSegment<DistanceUnit>(
value: unit,
label: Text(unit.label),
),
)
.toList(),
selected: {distanceUnitService.unit},
onSelectionChanged: (selection) {
final next = selection.first;
distanceUnitService.setUnit(next);
},
),
const SizedBox(height: 24),
Text(
'API endpoint',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Set the base URL for the Mileograph API. Leave blank to use the default.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 16),
TextField(
controller: _endpointController,
decoration: const InputDecoration(
labelText: 'Endpoint URL',
hintText: 'https://mileograph.co.uk/api/v1',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
Row(
children: [
FilledButton.icon(
onPressed: _saving ? null : _save,
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save),
label: const Text('Save endpoint'),
),
const SizedBox(width: 12),
TextButton(
onPressed: _saving
? null
: () {
_endpointController.text =
EndpointService.defaultBaseUrl;
},
child: const Text('Reset to default'),
),
],
),
const SizedBox(height: 12),
Text(
'Current: ${endpointService.baseUrl}',
style: Theme.of(context).textTheme.labelSmall,
),
if (loggedIn) ...[
const SizedBox(height: 32),
Text(
'Account',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Change your password for this account.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
Form(
key: _passwordFormKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _currentPasswordController,
decoration: const InputDecoration(
labelText: 'Current password',
border: OutlineInputBorder(),
),
obscureText: true,
enableSuggestions: false,
autocorrect: false,
autofillHints: const [AutofillHints.password],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your current password.';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _newPasswordController,
decoration: const InputDecoration(
labelText: 'New password',
border: OutlineInputBorder(),
),
obscureText: true,
enableSuggestions: false,
autocorrect: false,
autofillHints: const [AutofillHints.newPassword],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a new password.';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _confirmPasswordController,
decoration: const InputDecoration(
labelText: 'Confirm new password',
border: OutlineInputBorder(),
),
obscureText: true,
enableSuggestions: false,
autocorrect: false,
autofillHints: const [AutofillHints.newPassword],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please confirm the new password.';
}
if (value != _newPasswordController.text) {
return 'New passwords do not match.';
}
return null;
},
),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _changingPassword ? null : _changePassword,
icon: _changingPassword
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.lock_reset),
label: Text(
_changingPassword ? 'Updating...' : 'Change password',
),
),
],
),
),
],
],
),
),
);
}
}