google preperation 1

This commit is contained in:
2026-10-26 20:48:16 +01:00
parent 9a65ff7ad4
commit 3b50cb0fe9
47 changed files with 4969 additions and 4580 deletions
+329
View File
@@ -0,0 +1,329 @@
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 '../utils/target_colors.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 {
AppSettings._();
static final AppSettings instance = AppSettings._();
static const String defaultTarget = 'assets/target.png';
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': '🇸🇮'},
];
static const Map<String, Color> bulletColors = {
'Blue': Colors.blue,
'Green': Colors.green,
'Yellow': Colors.yellow,
'Purple': Colors.purple,
'Cyan': Colors.cyan,
'Teal': Colors.teal,
'Indigo': Colors.indigo,
'Pink': Colors.pink,
'Lime': Colors.lime,
'Mint': Colors.greenAccent,
'Orange': Colors.orange,
'Violet': Colors.deepPurpleAccent,
'Amber': Colors.amber,
'Brown': Colors.brown,
'Grey': Colors.grey,
};
static final List<String> targets = [
defaultTarget,
for (int i = 1; i <= 35; i++)
if (i != 13) 'assets/targets/Target$i.jpg', // 13 was removed
];
late SharedPreferences _prefs;
String _language = 'English';
bool _followSystemLanguage = false;
String _bulletColorName = 'Blue';
String _selectedTarget = defaultTarget;
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;
bool get followSystemLanguage => _followSystemLanguage;
// Phone language (or Android 13+ per-app language) mapped to our two languages
static String get systemLanguage =>
WidgetsBinding.instance.platformDispatcher.locale.languageCode == 'sl' ? 'Slovenian' : 'English';
String get bulletColorName => _bulletColorName;
Color get bulletColor => bulletColors[_bulletColorName] ?? Colors.blue;
String get selectedTarget => _selectedTarget;
Color get backgroundColor => TargetColors.getBackgroundColor(_selectedTarget);
bool get isLightBackground => backgroundColor.computeLuminance() > 0.4;
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);
String targetName(String path) {
if (path == defaultTarget) return t('Default Target');
return t(path.replaceAll('assets/targets/', '').replaceAll('.jpg', ''));
}
Future<void> load() async {
_prefs = await SharedPreferences.getInstance();
// New installs follow the phone; an explicit earlier choice stays as it is
final saved = _prefs.getString('language');
_followSystemLanguage = _prefs.getBool('languageFollowsSystem') ?? saved == null;
_language = _followSystemLanguage ? systemLanguage : saved!;
await _prefs.setString('language', _language); // other screens read this key
WidgetsBinding.instance.platformDispatcher.onLocaleChanged = _onSystemLocaleChanged;
final color = _prefs.getString('bulletColor') ?? 'Blue';
_bulletColorName = bulletColors.containsKey(color) ? color : 'Blue';
_selectedTarget = _prefs.getString('selectedTarget') ?? defaultTarget;
if (!targets.contains(_selectedTarget)) {
// Target no longer shipped: fall back so screens reading prefs don't load a missing image
_selectedTarget = defaultTarget;
await _prefs.setString('selectedTarget', defaultTarget);
}
_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;
_followSystemLanguage = false;
notifyListeners();
await _prefs.setString('language', value);
await _prefs.setBool('languageFollowsSystem', false);
}
Future<void> useSystemLanguage() async {
_followSystemLanguage = true;
_language = systemLanguage;
notifyListeners();
await _prefs.setString('language', _language);
await _prefs.setBool('languageFollowsSystem', true);
}
void _onSystemLocaleChanged() {
if (_followSystemLanguage && systemLanguage != _language) useSystemLanguage();
}
Future<void> setBulletColor(String name) async {
_bulletColorName = name;
notifyListeners();
await _prefs.setString('bulletColor', name);
}
Future<void> setTarget(String path) async {
_selectedTarget = path;
notifyListeners();
await _prefs.setString('selectedTarget', path);
}
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();
}
}
+49
View File
@@ -0,0 +1,49 @@
import 'dart:convert';
import 'package:cryptography/cryptography.dart';
/// Encrypts/decrypts the club data (contacts) with the club code as the key,
/// so the data can ship inside the public app but is unreadable without the code.
///
/// No Flutter imports: also used by tool/encrypt_club_data.dart.
/// File format (assets/club.enc): JSON {v, salt, nonce, cipher, mac}, base64 values.
class ClubCrypto {
static const int _iterations = 100000;
static final _aes = AesGcm.with256bits();
/// Codes are compared ignoring case and surrounding spaces.
static String normalize(String code) => code.trim().toLowerCase();
static Future<SecretKey> _deriveKey(String code, List<int> salt) {
return Pbkdf2(macAlgorithm: Hmac.sha256(), iterations: _iterations, bits: 256)
.deriveKeyFromPassword(password: normalize(code), nonce: salt);
}
static Future<String> encrypt(String plaintext, String code) async {
final salt = SecretKeyData.random(length: 16).bytes;
final key = await _deriveKey(code, salt);
final box = await _aes.encrypt(utf8.encode(plaintext), secretKey: key);
return jsonEncode({
'v': 1,
'salt': base64Encode(salt),
'nonce': base64Encode(box.nonce),
'cipher': base64Encode(box.cipherText),
'mac': base64Encode(box.mac.bytes),
});
}
/// Returns the plaintext, or null if the code is wrong.
static Future<String?> decrypt(String encrypted, String code) async {
final data = jsonDecode(encrypted) as Map<String, dynamic>;
final key = await _deriveKey(code, base64Decode(data['salt']));
final box = SecretBox(
base64Decode(data['cipher']),
nonce: base64Decode(data['nonce']),
mac: Mac(base64Decode(data['mac'])),
);
try {
return utf8.decode(await _aes.decrypt(box, secretKey: key));
} on SecretBoxAuthenticationError {
return null;
}
}
}
+5 -22
View File
@@ -3,6 +3,7 @@ import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/app_settings.dart';
import '../services/google_calendar_service.dart';
class NotificationService {
@@ -92,6 +93,10 @@ class NotificationService {
/// Fetches the calendar and reschedules all reminders. Call on app start
/// and whenever notification settings change.
Future<void> rescheduleFromCalendar() async {
if (!AppSettings.instance.clubUnlocked) {
await cancelAll(); // reminders are a club-member feature
return;
}
final service = GoogleCalendarService();
try {
final now = DateTime.now();
@@ -172,28 +177,6 @@ class NotificationService {
} catch (_) {}
}
Future<void> scheduleTestNotification() async {
try {
await initialize();
final prefs = await SharedPreferences.getInstance();
final isSlovenian = (prefs.getString('language') ?? 'English') == 'Slovenian';
await _plugin.show(
9999,
isSlovenian ? 'Testno obvestilo' : 'Test Notification',
isSlovenian ? 'Obvestila delujejo!' : 'Notifications are working!',
_notifDetails,
);
final in10s = DateTime.now().add(const Duration(seconds: 10));
await _scheduleNotification(
id: 9998,
title: isSlovenian ? 'Načrtovano testno obvestilo' : 'Scheduled Test',
body: isSlovenian ? 'Načrtovana obvestila delujejo!' : 'Scheduled notifications are working!',
scheduledDate: in10s,
mode: await _scheduleMode(),
);
} catch (_) {}
}
Future<void> _scheduleNotification({
required int id,
required String title,
+217
View File
@@ -0,0 +1,217 @@
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// One saved target (a JSON file written by the preview screen).
class TargetRecord {
final File file;
final DateTime shotAt;
final int score;
final int shots;
const TargetRecord(
{required this.file,
required this.shotAt,
required this.score,
required this.shots});
}
/// A folder of targets: one training or tournament.
class Session {
final String name;
final bool isTournament;
final DateTime date;
final List<TargetRecord> targets; // oldest first
const Session(
{required this.name,
required this.isTournament,
required this.date,
required this.targets});
int get totalScore => targets.fold(0, (sum, t) => sum + t.score);
int get shots => targets.fold(0, (sum, t) => sum + t.shots);
double? get averagePerShot => shots == 0 ? null : totalScore / shots;
List<File> get files => [for (final t in targets) t.file];
/// The same session limited to targets with [shots] bullets (null = all).
Session onlyShots(int? shots) => shots == null
? this
: Session(name: name, isTournament: isTournament, date: date, targets: [
for (final t in targets)
if (t.shots == shots) t,
]);
}
/// Aggregates over any set of sessions (trainings or tournaments of one format).
class ShooterStats {
final int sessions;
final int targets;
final int shots;
final TargetRecord? best;
final double? averageTarget;
final double? averagePerShot;
const ShooterStats._({
required this.sessions,
required this.targets,
required this.shots,
required this.best,
required this.averageTarget,
required this.averagePerShot,
});
factory ShooterStats.of(List<Session> sessions) {
final all = [for (final s in sessions) ...s.targets];
final shots = all.fold(0, (sum, t) => sum + t.shots);
final total = all.fold(0, (sum, t) => sum + t.score);
final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score));
final mean = all.isEmpty ? null : total / all.length;
return ShooterStats._(
sessions: sessions.length,
targets: all.length,
shots: shots,
best: ranked.isEmpty ? null : ranked.first,
averageTarget: mean,
averagePerShot: shots == 0 ? null : total / shots,
);
}
}
/// Reads and edits the saved targets under <documents>/saved_images/<session>/.
class TargetRepository {
static Future<Directory> _root() async {
final dir = Directory(
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
if (!await dir.exists()) await dir.create(recursive: true);
return dir;
}
/// Sessions, newest first. With [year], only that year's target files are read.
static Future<List<Session>> loadSessions({int? year}) async {
final sessions = <Session>[];
for (final folder in await _folders()) {
if (year != null && folder.date.year != year) continue;
final targets = <TargetRecord>[];
for (final file in folder.targetFiles) {
final record = await _readTarget(file);
if (record != null) targets.add(record);
}
targets.sort((a, b) => a.shotAt.compareTo(b.shotAt));
sessions.add(Session(
name: folder.name,
isTournament: folder.isTournament,
date: folder.date,
targets: targets,
));
}
sessions.sort((a, b) => b.date.compareTo(a.date));
return sessions;
}
/// Years that have at least one session, newest first. Reads only metadata.
static Future<List<int>> years() async {
final years = {for (final f in await _folders()) f.date.year}.toList();
return years..sort((a, b) => b.compareTo(a));
}
// Cheap pass over the folders: metadata + file names, no target files read
static Future<List<_FolderInfo>> _folders() async {
final root = await _root();
final result = <_FolderInfo>[];
for (final folder in root.listSync().whereType<Directory>()) {
final meta = await _readMetadata(folder);
final files = [
for (final f in folder.listSync().whereType<File>())
if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f,
];
final fileTimes = files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
result.add(_FolderInfo(
name: folder.path.split('/').last,
isTournament: meta['isTournament'] == true,
date: DateTime.tryParse(meta['createdAt'] ?? '') ??
(fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed),
targetFiles: files,
));
}
return result;
}
static Future<Map<String, dynamic>> _readMetadata(Directory folder) async {
final file = File('${folder.path}/metadata.json');
if (!await file.exists()) return {};
try {
return jsonDecode(await file.readAsString()) as Map<String, dynamic>;
} catch (_) {
return {};
}
}
static Future<TargetRecord?> _readTarget(File file) async {
try {
final data =
jsonDecode(await file.readAsString()) as Map<String, dynamic>;
final score = data['totalScore'];
return TargetRecord(
file: file,
shotAt: _timeFromFileName(file) ?? file.statSync().modified,
score: score is int ? score : 0,
// Older saves have no bulletCount: fall back to the detected bullets
shots: data['bulletCount'] as int? ??
(data['bullets'] as List?)?.length ??
0,
);
} catch (_) {
return null;
}
}
// File names look like target_2026-10-26_17-5-3.json (see preview_screen _performSave)
static DateTime? _timeFromFileName(File file) {
final match = RegExp(r'target_(\d+)-(\d+)-(\d+)_(\d+)-(\d+)-(\d+)\.json$')
.firstMatch(file.path);
if (match == null) return null;
final p = [for (int i = 1; i <= 6; i++) int.parse(match.group(i)!)];
return DateTime(p[0], p[1], p[2], p[3], p[4], p[5]);
}
/// Renames a session and/or changes its type. Returns false if the new name is taken.
static Future<bool> updateSession(Session session,
{required String name, required bool isTournament}) async {
final root = await _root();
var folder = Directory('${root.path}/${session.name}');
if (name != session.name) {
final target = Directory('${root.path}/$name');
if (await target.exists()) return false;
folder = await folder.rename(target.path);
}
final metaFile = File('${folder.path}/metadata.json');
final meta = await _readMetadata(folder);
await metaFile.writeAsString(jsonEncode({
'isTournament': isTournament,
'createdAt': meta['createdAt'] ?? session.date.toIso8601String(),
}));
return true;
}
static Future<void> deleteSession(Session session) async {
final folder = Directory('${(await _root()).path}/${session.name}');
if (await folder.exists()) await folder.delete(recursive: true);
}
static Future<void> deleteTarget(TargetRecord target) async {
if (await target.file.exists()) await target.file.delete();
}
}
class _FolderInfo {
final String name;
final bool isTournament;
final DateTime date;
final List<File> targetFiles;
const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles});
}
+29
View File
@@ -0,0 +1,29 @@
import 'dart:io';
import 'package:flutter/services.dart';
/// Routes the app's traffic over Wi-Fi while camera screens are open, so the
/// cameras stay reachable when the range Wi-Fi has no internet and Android
/// would otherwise prefer mobile data. Other apps are not affected.
class WifiBinding {
static const _channel = MethodChannel('si.sdkkovinar.app/network');
static int _users = 0;
/// Call from initState; await before connecting to a camera.
static Future<void> acquire() async {
_users++;
if (_users > 1 || !Platform.isAndroid) return;
try {
await _channel.invokeMethod('bindToWifi');
} catch (_) {}
}
/// Call from dispose.
static Future<void> release() async {
if (_users == 0) return;
_users--;
if (_users > 0 || !Platform.isAndroid) return;
try {
await _channel.invokeMethod('unbind');
} catch (_) {}
}
}