437 lines
16 KiB
Dart
437 lines
16 KiB
Dart
import 'dart:convert';
|
|
import 'dart:isolate';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../models/camera_setup.dart';
|
|
import '../models/contact.dart';
|
|
import 'club_crypto.dart';
|
|
import '../models/holiday_theme.dart';
|
|
import '../models/target_style.dart';
|
|
import '../theme/app_theme.dart';
|
|
import '../utils/translations.dart';
|
|
|
|
/// Single source of truth for user settings. Loaded once in main(); widgets
|
|
/// rebuild via ListenableBuilder(listenable: AppSettings.instance, ...).
|
|
///
|
|
/// Writes the same SharedPreferences keys the rest of the app already reads,
|
|
/// so screens can migrate to this class one at a time.
|
|
class AppSettings extends ChangeNotifier with WidgetsBindingObserver {
|
|
AppSettings._();
|
|
static final AppSettings instance = AppSettings._();
|
|
|
|
// Shots per target, same limit for camera and stream capture
|
|
static const int minBullets = 1;
|
|
static const int maxBullets = 5;
|
|
static const List<int> reminderHourOptions = [1, 2, 3, 6, 12, 24, 48];
|
|
|
|
static const List<Map<String, String>> languages = [
|
|
{'name': 'English', 'flag': '🇬🇧'},
|
|
{'name': 'Slovenian', 'flag': '🇸🇮'},
|
|
{'name': 'German', 'flag': '🇩🇪'},
|
|
];
|
|
static const String defaultLanguage = 'Slovenian';
|
|
|
|
/// Hit colours, each tuned for the dark and the light theme. The chosen
|
|
/// one is the accent of the whole interface.
|
|
static const Map<String, (Color dark, Color light)> bulletColors = {
|
|
'Blue': (Color(0xFF4B8EF5), Color(0xFF2D6BD8)),
|
|
'Green': (Color(0xFF3CC764), Color(0xFF1E9A4C)),
|
|
'Yellow': (Color(0xFFF2C12E), Color(0xFFC08E00)),
|
|
'Purple': (Color(0xFFB45EE3), Color(0xFF8E3FBF)),
|
|
'Cyan': (Color(0xFF22C7E0), Color(0xFF12B4CE)),
|
|
'Teal': (Color(0xFF17B3A3), Color(0xFF0E9384)),
|
|
'Indigo': (Color(0xFF6E6CF2), Color(0xFF4F46E5)),
|
|
'Pink': (Color(0xFFF0457A), Color(0xFFD63366)),
|
|
'Lime': (Color(0xFFC9DC3C), Color(0xFF85A00E)),
|
|
'Mint': (Color(0xFF5EE6B0), Color(0xFF1FAE7A)),
|
|
'Orange': (Color(0xFFFF8A1F), Color(0xFFE06F00)),
|
|
'Violet': (Color(0xFF8E62F7), Color(0xFF7C3AED)),
|
|
'Amber': (Color(0xFFFFB020), Color(0xFFD18A00)),
|
|
'Brown': (Color(0xFFB07A55), Color(0xFF8A5536)),
|
|
'Grey': (Color(0xFFA3AAB2), Color(0xFF6F757C)),
|
|
};
|
|
static const String defaultBulletColor = 'Cyan';
|
|
|
|
static const List<String> themeModes = ['system', 'light', 'dark'];
|
|
|
|
late SharedPreferences _prefs;
|
|
|
|
String _language = defaultLanguage;
|
|
String _bulletColorName = defaultBulletColor;
|
|
String _themeMode = 'dark';
|
|
TargetStyle _target = TargetStyle.fallback;
|
|
Palette? _palette;
|
|
int _reminderHours = 1;
|
|
bool _notifyDezuranje = true;
|
|
bool _notifySestanek = true;
|
|
bool _notifyTekma = true;
|
|
CameraSetup _cameras = const CameraSetup();
|
|
List<Contact>? _clubContacts; // null until the club code is entered
|
|
|
|
String get language => _language;
|
|
|
|
/// intl locale for dates (month and day names) in [language].
|
|
static String dateLocaleFor(String language) => switch (language) {
|
|
'Slovenian' => 'sl_SI',
|
|
'German' => 'de_DE',
|
|
_ => 'en_US',
|
|
};
|
|
String get dateLocale => dateLocaleFor(_language);
|
|
String get bulletColorName => _bulletColorName;
|
|
|
|
/// The hit colour in the current theme; also the interface accent.
|
|
Color get bulletColor => palette.accent;
|
|
|
|
// --- Holidays (a hidden easter egg, no setting) ---
|
|
// During a holiday's window the app shows that holiday's background and
|
|
// target (locked) and its hit colour, until the user picks a colour of their
|
|
// own for this holiday. Afterwards their own settings are back.
|
|
|
|
/// Debug builds only: pretend today is this day, to preview a holiday.
|
|
DateTime? debugToday;
|
|
|
|
DateTime get today => debugToday ?? DateTime.now();
|
|
|
|
HolidayTheme? get holiday => HolidayTheme.on(today);
|
|
|
|
/// True while a holiday decides the target.
|
|
bool get targetLocked => holiday != null;
|
|
|
|
// "<holiday id>-<first day>" of the holiday whose colour the user replaced
|
|
String? _holidayColorFor;
|
|
|
|
String _holidayKey(HolidayTheme h) {
|
|
final (start, _) = h.window(today);
|
|
return '${h.id}-${start.year}${start.month.toString().padLeft(2, '0')}${start.day.toString().padLeft(2, '0')}';
|
|
}
|
|
|
|
/// The holiday colour is in use (the user has not picked another one).
|
|
bool get holidayColorActive {
|
|
final h = holiday;
|
|
return h != null && _holidayColorFor != _holidayKey(h);
|
|
}
|
|
|
|
/// Back to the holiday's own colour (after picking another one).
|
|
Future<void> useHolidayColor() async {
|
|
_holidayColorFor = null;
|
|
notifyListeners();
|
|
await _prefs.remove('holidayColorFor');
|
|
}
|
|
|
|
/// The holiday's screen background (the everyday one is painted, see AppBackground).
|
|
String get background => holiday?.background(isDark) ?? '';
|
|
|
|
// A new day may start or end a holiday
|
|
@override
|
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
|
if (state == AppLifecycleState.resumed) notifyListeners();
|
|
}
|
|
|
|
/// Swatch of [name] in the current theme.
|
|
Color colorFor(String name) {
|
|
final pair = bulletColors[name] ?? bulletColors[defaultBulletColor]!;
|
|
return isDark ? pair.$1 : pair.$2;
|
|
}
|
|
|
|
String get themeMode => _themeMode;
|
|
|
|
int _forceDark = 0;
|
|
|
|
/// Screens that must stay dark whatever the theme (the photo camera) call
|
|
/// this while they are open, and [releaseDark] when they close.
|
|
void holdDark() {
|
|
_forceDark++;
|
|
if (_forceDark == 1) notifyListeners();
|
|
}
|
|
|
|
void releaseDark() {
|
|
if (_forceDark == 0) return;
|
|
_forceDark--;
|
|
if (_forceDark == 0) notifyListeners();
|
|
}
|
|
|
|
bool get isDark => _forceDark > 0 || switch (_themeMode) {
|
|
'light' => false,
|
|
'system' => WidgetsBinding.instance.platformDispatcher.platformBrightness == Brightness.dark,
|
|
_ => true,
|
|
};
|
|
|
|
Palette get palette {
|
|
final accent = holidayColorActive ? holiday!.color : colorFor(_bulletColorName);
|
|
final p = _palette;
|
|
if (p != null && p.isDark == isDark && p.accent == accent) return p;
|
|
return _palette = isDark ? Palette.dark(accent) : Palette.light(accent);
|
|
}
|
|
|
|
/// The target shown: the holiday's while one is on, otherwise the user's.
|
|
TargetStyle get target {
|
|
final h = holiday;
|
|
return h == null ? _target : TargetStyle.byId(h.targetId);
|
|
}
|
|
int get reminderHours => _reminderHours;
|
|
bool get notifyDezuranje => _notifyDezuranje;
|
|
bool get notifySestanek => _notifySestanek;
|
|
bool get notifyTekma => _notifyTekma;
|
|
CameraSetup get cameras => _cameras;
|
|
|
|
/// Calendar, reminders and contacts are for club members only.
|
|
bool get clubUnlocked => _clubContacts != null;
|
|
List<Contact> get clubContacts => _clubContacts ?? const [];
|
|
|
|
String t(String key) => AppTranslations.translate(key, _language);
|
|
|
|
Future<void> load() async {
|
|
_prefs = await SharedPreferences.getInstance();
|
|
// New installs start in Slovenian. Whoever had "automatic" keeps the language
|
|
// it last resolved to (saved under the same key).
|
|
final saved = _prefs.getString('language');
|
|
_language = languages.any((l) => l['name'] == saved) ? saved! : defaultLanguage;
|
|
await _prefs.setString('language', _language); // other screens read this key
|
|
await _prefs.remove('languageFollowsSystem');
|
|
|
|
final color = _prefs.getString('bulletColor') ?? defaultBulletColor;
|
|
_bulletColorName = bulletColors.containsKey(color) ? color : defaultBulletColor;
|
|
_holidayColorFor = _prefs.getString('holidayColorFor');
|
|
final mode = _prefs.getString('themeMode');
|
|
_themeMode = themeModes.contains(mode) ? mode! : 'dark';
|
|
WidgetsBinding.instance.addObserver(this);
|
|
|
|
// v3 targets keep the numbers of the old skins (assets/targets/Target<n>.jpg)
|
|
var targetId = _prefs.getInt('targetStyle');
|
|
if (targetId == null) {
|
|
final old = RegExp(r'Target(\d+)\.jpg$').firstMatch(_prefs.getString('selectedTarget') ?? '');
|
|
targetId = old == null ? 0 : int.parse(old.group(1)!);
|
|
await _prefs.setInt('targetStyle', TargetStyle.byId(targetId).id);
|
|
}
|
|
_target = TargetStyle.byId(targetId);
|
|
_reminderHours = _prefs.getInt('notificationHours_single') ?? 1;
|
|
_notifyDezuranje = _prefs.getBool('notifyDezuranje') ?? true;
|
|
_notifySestanek = _prefs.getBool('notifySestanek') ?? true;
|
|
_notifyTekma = _prefs.getBool('notifyTekma') ?? true;
|
|
|
|
final clubData = _prefs.getString('clubData');
|
|
if (clubData != null) {
|
|
_clubContacts = _parseContacts(clubData);
|
|
_refreshClubData(); // picks up contact changes shipped in an app update
|
|
}
|
|
|
|
final setup = _prefs.getString('cameraSetup');
|
|
if (setup != null) {
|
|
_cameras = CameraSetup.fromJson(jsonDecode(setup) as Map<String, dynamic>);
|
|
} else {
|
|
// Before locations existed: the six single IPs become location "Kovinar"
|
|
final old = {
|
|
for (int p = 1; p <= CameraSetup.maxPositions; p++)
|
|
if ((_prefs.getString('cameraIP_$p') ?? '').isNotEmpty) p: {'Kovinar': _prefs.getString('cameraIP_$p')!},
|
|
};
|
|
if (old.isNotEmpty) {
|
|
_cameras = CameraSetup(locations: const ['Kovinar'], ips: old, activeLocation: 'Kovinar');
|
|
await _saveCameras();
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> setLanguage(String value) async {
|
|
_language = value;
|
|
notifyListeners();
|
|
await _prefs.setString('language', value);
|
|
}
|
|
|
|
Future<void> setBulletColor(String name) async {
|
|
_bulletColorName = name;
|
|
// Picked during a holiday: this colour replaces the holiday's until it ends
|
|
final h = holiday;
|
|
if (h != null) {
|
|
_holidayColorFor = _holidayKey(h);
|
|
await _prefs.setString('holidayColorFor', _holidayColorFor!);
|
|
}
|
|
notifyListeners();
|
|
await _prefs.setString('bulletColor', name);
|
|
}
|
|
|
|
Future<void> setTarget(TargetStyle style) async {
|
|
if (targetLocked) return; // the holiday decides
|
|
_target = style;
|
|
notifyListeners();
|
|
await _prefs.setInt('targetStyle', style.id);
|
|
}
|
|
|
|
/// Debug: show the look of [day] (null = today).
|
|
void previewDay(DateTime? day) {
|
|
debugToday = day;
|
|
notifyListeners();
|
|
}
|
|
|
|
Future<void> setThemeMode(String mode) async {
|
|
_themeMode = mode;
|
|
notifyListeners();
|
|
await _prefs.setString('themeMode', mode);
|
|
}
|
|
|
|
// Theme "Sistem" follows the phone
|
|
@override
|
|
void didChangePlatformBrightness() {
|
|
if (_themeMode == 'system') notifyListeners();
|
|
}
|
|
|
|
Future<void> setReminderHours(int hours) async {
|
|
_reminderHours = hours;
|
|
notifyListeners();
|
|
await _prefs.setInt('notificationHours_single', hours);
|
|
await _prefs.setStringList('notificationHours', [hours.toString()]);
|
|
}
|
|
|
|
Future<void> setNotifyDezuranje(bool v) => _setNotify('notifyDezuranje', v, () => _notifyDezuranje = v);
|
|
Future<void> setNotifySestanek(bool v) => _setNotify('notifySestanek', v, () => _notifySestanek = v);
|
|
Future<void> setNotifyTekma(bool v) => _setNotify('notifyTekma', v, () => _notifyTekma = v);
|
|
|
|
Future<void> _setNotify(String key, bool value, VoidCallback apply) async {
|
|
apply();
|
|
notifyListeners();
|
|
await _prefs.setBool(key, value);
|
|
}
|
|
|
|
Future<void> _setCameras(CameraSetup next) async {
|
|
_cameras = next;
|
|
notifyListeners();
|
|
await _saveCameras();
|
|
}
|
|
|
|
// Also fills the old cameraIP_1…6 keys (last chosen location) for screens
|
|
// that still read them, like the spectator view.
|
|
Future<void> _saveCameras() async {
|
|
await _prefs.setString('cameraSetup', jsonEncode(_cameras.toJson()));
|
|
for (int p = 1; p <= CameraSetup.maxPositions; p++) {
|
|
final at = p <= _cameras.positions ? _cameras.camerasAt(p) : <String, String>{};
|
|
final ip = at[_cameras.activeLocation] ?? (at.isEmpty ? '' : at.values.first);
|
|
await _prefs.setString('cameraIP_$p', ip);
|
|
}
|
|
}
|
|
|
|
Future<bool> addLocation(String name) async {
|
|
if (name.isEmpty || _cameras.locations.contains(name)) return false;
|
|
await _setCameras(_cameras.copyWith(locations: [..._cameras.locations, name]));
|
|
return true;
|
|
}
|
|
|
|
Future<bool> renameLocation(String from, String to) async {
|
|
if (to.isEmpty || (to != from && _cameras.locations.contains(to))) return false;
|
|
final ips = _cameras.ipsCopy();
|
|
for (final m in ips.values) {
|
|
if (m.containsKey(from)) m[to] = m.remove(from)!;
|
|
}
|
|
await _setCameras(CameraSetup(
|
|
locations: [for (final l in _cameras.locations) l == from ? to : l],
|
|
positions: _cameras.positions,
|
|
ips: ips,
|
|
activeLocation: _cameras.activeLocation == from ? to : _cameras.activeLocation,
|
|
clubLocation: _cameras.clubLocation == from ? to : _cameras.clubLocation,
|
|
));
|
|
return true;
|
|
}
|
|
|
|
Future<void> removeLocation(String name) async {
|
|
final ips = _cameras.ipsCopy();
|
|
for (final m in ips.values) {
|
|
m.remove(name);
|
|
}
|
|
await _setCameras(CameraSetup(
|
|
locations: [for (final l in _cameras.locations) if (l != name) l],
|
|
positions: _cameras.positions,
|
|
ips: ips,
|
|
activeLocation: _cameras.activeLocation == name ? null : _cameras.activeLocation,
|
|
clubLocation: _cameras.clubLocation == name ? null : _cameras.clubLocation,
|
|
));
|
|
}
|
|
|
|
Future<void> setPositionCount(int count) =>
|
|
_setCameras(_cameras.copyWith(positions: count.clamp(1, CameraSetup.maxPositions)));
|
|
|
|
Future<void> setCameraIp(int position, String location, String ip) {
|
|
final ips = _cameras.ipsCopy();
|
|
(ips[position] ??= {})[location] = ip.trim();
|
|
return _setCameras(_cameras.copyWith(ips: ips));
|
|
}
|
|
|
|
/// Points every position of [location] at one host with consecutive ports (9081, 9082, ...).
|
|
Future<void> setLocationHost(String location, String host) {
|
|
final ips = _cameras.ipsCopy();
|
|
for (int p = 1; p <= _cameras.positions; p++) {
|
|
(ips[p] ??= {})[location] = '$host:${CameraSetup.firstPort + p - 1}';
|
|
}
|
|
return _setCameras(_cameras.copyWith(ips: ips));
|
|
}
|
|
|
|
Future<void> setActiveLocation(String location) => _setCameras(_cameras.copyWith(activeLocation: location));
|
|
|
|
// Club data may carry the club's cameras: {"cameras": {"location": "Kovinar", "ips": [...]}}
|
|
Future<void> _applyClubCameras(String plaintext) async {
|
|
final data = (jsonDecode(plaintext) as Map<String, dynamic>)['cameras'] as Map<String, dynamic>?;
|
|
if (data == null) return;
|
|
final location = data['location'] as String;
|
|
final clubIps = [for (final ip in data['ips'] as List) ip as String];
|
|
final ips = _cameras.ipsCopy();
|
|
for (int i = 0; i < clubIps.length && i < CameraSetup.maxPositions; i++) {
|
|
(ips[i + 1] ??= {})[location] = clubIps[i];
|
|
}
|
|
await _setCameras(_cameras.copyWith(
|
|
locations: _cameras.locations.contains(location) ? null : [location, ..._cameras.locations],
|
|
positions: clubIps.length.clamp(_cameras.positions, CameraSetup.maxPositions),
|
|
ips: ips,
|
|
activeLocation: _cameras.activeLocation ?? location,
|
|
clubLocation: location,
|
|
));
|
|
}
|
|
|
|
/// Decrypts the bundled club data with [code]. Returns false if the code is wrong.
|
|
Future<bool> unlockClub(String code) async {
|
|
final encrypted = await _loadClubAsset();
|
|
if (encrypted == null) return false; // asset missing: run tool/encrypt_club_data.dart
|
|
|
|
// Key derivation is deliberately slow; keep it off the UI thread
|
|
final plaintext = await Isolate.run(() => ClubCrypto.decrypt(encrypted, code));
|
|
if (plaintext == null) return false;
|
|
|
|
_clubContacts = _parseContacts(plaintext);
|
|
notifyListeners();
|
|
await _applyClubCameras(plaintext);
|
|
await _prefs.setString('clubData', plaintext);
|
|
await _prefs.setString('clubCode', code);
|
|
await _prefs.setString('clubDataSource', encrypted);
|
|
return true;
|
|
}
|
|
|
|
Future<void> lockClub() async {
|
|
_clubContacts = null;
|
|
notifyListeners();
|
|
final clubLocation = _cameras.clubLocation;
|
|
if (clubLocation != null) await removeLocation(clubLocation);
|
|
await _prefs.remove('clubData');
|
|
await _prefs.remove('clubCode');
|
|
await _prefs.remove('clubDataSource');
|
|
}
|
|
|
|
/// If the bundled club.enc changed since unlocking (new app version), decrypt
|
|
/// it again with the saved code. A changed club code locks the phone again.
|
|
Future<void> _refreshClubData() async {
|
|
final encrypted = await _loadClubAsset();
|
|
final code = _prefs.getString('clubCode');
|
|
if (encrypted == null || encrypted == _prefs.getString('clubDataSource')) return;
|
|
if (code == null || !await unlockClub(code)) await lockClub();
|
|
}
|
|
|
|
static Future<String?> _loadClubAsset() async {
|
|
try {
|
|
return await rootBundle.loadString('assets/club.enc');
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
static List<Contact> _parseContacts(String json) {
|
|
final list = (jsonDecode(json) as Map<String, dynamic>)['contacts'] as List;
|
|
return list.map((c) => Contact.fromJson(c as Map<String, dynamic>)).toList();
|
|
}
|
|
}
|