From a66109885583690154c9e2ee9e1aec8add2ea992 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Tue, 3 Mar 2026 11:41:47 +0100 Subject: [PATCH 01/59] Implement live activity token rotation and server synchronization for push notifications --- refilc/ios/Runner/AppDelegate.swift | 240 ++++++++++-------- refilc/ios/Runner/public_vars.swift | 1 + refilc/ios/livecard/LiveActivityManager.swift | 164 ++++++++---- .../lib/api/providers/live_card_provider.dart | 35 ++- .../liveactivity/platform_channel.dart | 43 +++- .../liveactivity/server_sync_provider.dart | 134 ++++++++++ 6 files changed, 461 insertions(+), 156 deletions(-) create mode 100644 refilc/lib/api/providers/liveactivity/server_sync_provider.dart diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index d7697333..73e28abe 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -2,112 +2,152 @@ import UIKit import background_fetch import ActivityKit import Flutter +import Security @main @objc class AppDelegate: FlutterAppDelegate { - private var methodChannel: FlutterMethodChannel? + private var methodChannel: FlutterMethodChannel? + private var tokenRotationObserver: NSObjectProtocol? - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - guard let controller = window?.rootViewController as? FlutterViewController else { - fatalError("rootViewController is not type FlutterViewController") - } - methodChannel = FlutterMethodChannel(name: "app.firka/liveactivity", - binaryMessenger: controller as! FlutterBinaryMessenger) - methodChannel?.setMethodCallHandler({ - [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in - guard call.method == "createLiveActivity" || call.method == "endLiveActivity" || call.method == "updateLiveActivity" else { - result(FlutterMethodNotImplemented) - return - } - self?.handleMethodCall(call, result: result) - }) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } - - override func applicationWillTerminate(_ application: UIApplication) { - if #available(iOS 16.2, *) { - LiveActivityManager.stop() - } - } - - private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - if call.method == "createLiveActivity" { - if let args = call.arguments as? [String: Any] { - lessonDataDictionary = args - globalLessonData = LessonData(from: lessonDataDictionary) - print("swift: megkapott flutter adatok:",lessonDataDictionary) - print("Live Activity bekapcsolva az eszközön: ",checkLiveActivityFeatureAvailable()) - if(checkLiveActivityFeatureAvailable()) { - createLiveActivity(with: lessonDataDictionary) - result(checkLiveActivityFeatureAvailable()) - } else { - result(nil) - } - - } else { - result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid iOS arguments received", details: nil)) - } - } else if call.method == "updateLiveActivity" { - if let args = call.arguments as? [String: Any] { - lessonDataDictionary = args - globalLessonData = LessonData(from: lessonDataDictionary) - updateLiveActivity(with: lessonDataDictionary) - result(nil) - } else { - result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid iOS arguments received", details: nil)) + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + guard let controller = window?.rootViewController as? FlutterViewController else { + fatalError("rootViewController is not type FlutterViewController") } - } else if call.method == "endLiveActivity" { - endLiveActivity() - result(nil) + methodChannel = FlutterMethodChannel( + name: "app.firka/liveactivity", + binaryMessenger: controller as! FlutterBinaryMessenger + ) + methodChannel?.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in + guard call.method == "createLiveActivity" + || call.method == "endLiveActivity" + || call.method == "updateLiveActivity" + else { + result(FlutterMethodNotImplemented) + return + } + self?.handleMethodCall(call, result: result) + }) + + // Token rotation figyelése: ha az APNs új tokent ad, értesítjük Flutter-t + tokenRotationObserver = NotificationCenter.default.addObserver( + forName: NSNotification.Name("LiveActivityTokenUpdated"), + object: nil, + queue: .main + ) { [weak self] notification in + if let newToken = notification.object as? String { + let deviceId = self?.getOrCreateDeviceId() ?? "" + let bundleId = Bundle.main.bundleIdentifier ?? "" + self?.methodChannel?.invokeMethod("liveActivityTokenUpdated", arguments: [ + "pushToken": newToken, + "deviceId": deviceId, + "bundleId": bundleId, + ]) + } + } + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) } - } - - private func createLiveActivity(with activityData: [String: Any]) -> String? { - var lessonData = LessonData(from: activityData) - print("Live Activity létrehozása...") - if #available(iOS 16.2, *) { - LiveActivityManager.create() - } - return nil - } - private func updateLiveActivity(with activityData: [String: Any]) { - let lessonData = LessonData(from: activityData) - print("swift: megkapott flutter adatok:",lessonDataDictionary) - print("Live Activity frissítés...") - if #available(iOS 16.2, *) { - LiveActivityManager.update() - } - } + override func applicationWillTerminate(_ application: UIApplication) { + if #available(iOS 16.2, *) { + LiveActivityManager.stop() + } + if let observer = tokenRotationObserver { + NotificationCenter.default.removeObserver(observer) + } + } - - private func endLiveActivity() { - print("Live Activity befejezése...") - if #available(iOS 16.2, *) { - LiveActivityManager.stop() - } - } - - private func checkIfLiveActivityExists() -> Bool { - if let activityID = activityID { - if #available(iOS 16.2, *) { - return LiveActivityManager.isRunning(activityID) - } - } - return false - } - - private func checkLiveActivityFeatureAvailable() -> Bool { - if #available(iOS 16.2, *) { - guard ActivityAuthorizationInfo().areActivitiesEnabled else { - return false - } - return true - } - return false - } + private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + if call.method == "createLiveActivity" { + guard let args = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid iOS arguments received", details: nil)) + return + } + lessonDataDictionary = args + globalLessonData = LessonData(from: lessonDataDictionary) + print("swift: megkapott flutter adatok:", lessonDataDictionary) + print("Live Activity bekapcsolva az eszközön:", checkLiveActivityFeatureAvailable()) + + guard checkLiveActivityFeatureAvailable() else { + result(nil) + return + } + + if #available(iOS 16.2, *) { + LiveActivityManager.create { [weak self] pushToken in + guard let self = self, let token = pushToken else { + result(nil) + return + } + let deviceId = self.getOrCreateDeviceId() + let bundleId = Bundle.main.bundleIdentifier ?? "" + result([ + "pushToken": token, + "deviceId": deviceId, + "bundleId": bundleId, + ]) + } + } else { + result(nil) + } + + } else if call.method == "updateLiveActivity" { + guard let args = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid iOS arguments received", details: nil)) + return + } + lessonDataDictionary = args + globalLessonData = LessonData(from: lessonDataDictionary) + if #available(iOS 16.2, *) { + LiveActivityManager.update() + } + result(nil) + + } else if call.method == "endLiveActivity" { + if #available(iOS 16.2, *) { + LiveActivityManager.stop() + } + result(nil) + } + } + + // MARK: - Keychain device ID + + private func getOrCreateDeviceId() -> String { + let keychainKey = "refilc.live.device_id" + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrAccount as String: keychainKey, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne, + ] + var item: CFTypeRef? + if SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, + let data = item as? Data, + let existingId = String(data: data, encoding: .utf8) { + return existingId + } + // Nem létezik – generálunk egyet + let newId = UUID().uuidString + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrAccount as String: keychainKey, + kSecValueData as String: newId.data(using: .utf8)!, + ] + SecItemAdd(addQuery as CFDictionary, nil) + return newId + } + + // MARK: - Helpers + + private func checkLiveActivityFeatureAvailable() -> Bool { + if #available(iOS 16.2, *) { + return ActivityAuthorizationInfo().areActivitiesEnabled + } + return false + } } diff --git a/refilc/ios/Runner/public_vars.swift b/refilc/ios/Runner/public_vars.swift index f084d22d..722cc4a5 100644 --- a/refilc/ios/Runner/public_vars.swift +++ b/refilc/ios/Runner/public_vars.swift @@ -10,3 +10,4 @@ import Foundation var lessonDataDictionary: [String: Any] = [:] var globalLessonData = LessonData(from: lessonDataDictionary) var activityID: String? = "" +var activityPushToken: String? = nil diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 25f9eabf..61667fb9 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -17,7 +17,7 @@ public struct LiveActivitiesAppAttributes: ActivityAttributes, Identifiable { var nextSubject: String var nextRoom: String } - + public var id = UUID() } @@ -26,67 +26,141 @@ final class LiveActivityManager { static let shared = LiveActivityManager() var currentActivity: Activity? - class func create() { - - Task { + /// Létrehozza a Live Activity-t pushType: .token-nel, majd visszaadja az APNs push tokent. + class func create(completion: @escaping (String?) -> Void) { + Task { + do { + let contentState = LiveActivitiesAppAttributes.ContentState( + color: globalLessonData.color, + icon: globalLessonData.icon, + index: globalLessonData.index, + title: globalLessonData.title, + subtitle: globalLessonData.subtitle, + description: globalLessonData.description, + startDate: globalLessonData.startDate, + endDate: globalLessonData.endDate, + date: globalLessonData.date, + nextSubject: globalLessonData.nextSubject, + nextRoom: globalLessonData.nextRoom + ) + + let activityContent = ActivityContent( + state: contentState, + staleDate: globalLessonData.endDate, + relevanceScore: 0 + ) + + let activity = try Activity.request( + attributes: LiveActivitiesAppAttributes(), + content: activityContent, + pushType: .token + ) + + activityID = activity.id + print("Live Activity létrehozva. Azonosító: \(activity.id)") + + // Az APNs token aszinkron érkezik – megvárjuk az elsőt + for await tokenData in activity.pushTokenUpdates { + let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() + activityPushToken = tokenHex + print("Live Activity push token: \(tokenHex)") + completion(tokenHex) + // Token rotation figyelése a háttérben + Task { await monitorTokenRotation(activity: activity) } + break + } + } catch { + print("Hiba történt a Live Activity létrehozásakor: \(error)") + completion(nil) + } + } + } + + /// Token rotation figyelése: ha az APNs új tokent ad ki, értesítjük a Flutter oldalt. + private class func monitorTokenRotation(activity: Activity) async { + var isFirst = true + for await tokenData in activity.pushTokenUpdates { + if isFirst { isFirst = false; continue } // Az első tokent már kezeltük + let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() + activityPushToken = tokenHex + print("Live Activity push token frissítve (rotation): \(tokenHex)") + NotificationCenter.default.post( + name: NSNotification.Name("LiveActivityTokenUpdated"), + object: tokenHex + ) + } + } + + class func update() { + Task { + for activity in Activity.activities { do { - let contentState = LiveActivitiesAppAttributes.ContentState(color: globalLessonData.color, icon: globalLessonData.icon, index: globalLessonData.index, title: globalLessonData.title, subtitle: globalLessonData.subtitle, description: globalLessonData.description, startDate: globalLessonData.startDate, endDate: globalLessonData.endDate, date: globalLessonData.date, nextSubject: globalLessonData.nextSubject, nextRoom: globalLessonData.nextRoom) - - let activityContent = ActivityContent(state: contentState, staleDate: globalLessonData.endDate, relevanceScore: 0) - - let activity = try Activity.request( - attributes: LiveActivitiesAppAttributes(), - content: activityContent, - pushType: nil + let contentState = LiveActivitiesAppAttributes.ContentState( + color: globalLessonData.color, + icon: globalLessonData.icon, + index: globalLessonData.index, + title: globalLessonData.title, + subtitle: globalLessonData.subtitle, + description: globalLessonData.description, + startDate: globalLessonData.startDate, + endDate: globalLessonData.endDate, + date: globalLessonData.date, + nextSubject: globalLessonData.nextSubject, + nextRoom: globalLessonData.nextRoom ) - + + let activityContent = ActivityContent( + state: contentState, + staleDate: globalLessonData.endDate, + relevanceScore: 0 + ) + + await activity.update(activityContent) activityID = activity.id - print("Live Activity létrehozva. Azonosító: \(activity.id)") + print("Live Activity frissítve. Azonosító: \(activity.id)") } catch { - print("Hiba történt a Live Activity létrehozásakor: \(error)") + print("Hiba történt a Live Activity frissítésekor: \(error)") } } - } - - class func update() { - Task { - for activity in Activity.activities { - do { - let contentState = LiveActivitiesAppAttributes.ContentState(color: globalLessonData.color, icon: globalLessonData.icon, index: globalLessonData.index, title: globalLessonData.title, subtitle: globalLessonData.subtitle, description: globalLessonData.description, startDate: globalLessonData.startDate, endDate: globalLessonData.endDate, date: globalLessonData.date, nextSubject: globalLessonData.nextSubject, nextRoom: globalLessonData.nextRoom) - - let activityContent = ActivityContent(state: contentState, staleDate: globalLessonData.endDate, relevanceScore: 0) - - await activity.update(activityContent) - activityID = activity.id - print("Live Activity frissítve. Azonosító: \(activity.id)") - } catch { - print("Hiba történt a Live Activity frissítésekor: \(error)") - } - } - } } - - + } + class func stop() { - if (activityID != "") { + if activityID != "" { Task { - for activity in Activity.activities{ - let contentState = LiveActivitiesAppAttributes.ContentState(color: globalLessonData.color, icon: globalLessonData.icon, index: globalLessonData.index, title: globalLessonData.title, subtitle: globalLessonData.subtitle, description: globalLessonData.description, startDate: globalLessonData.startDate, endDate: globalLessonData.endDate, date: globalLessonData.date, nextSubject: globalLessonData.nextSubject, nextRoom: globalLessonData.nextRoom) - - await activity.end(ActivityContent(state: contentState, staleDate: Date.distantFuture),dismissalPolicy: .immediate) + for activity in Activity.activities { + let contentState = LiveActivitiesAppAttributes.ContentState( + color: globalLessonData.color, + icon: globalLessonData.icon, + index: globalLessonData.index, + title: globalLessonData.title, + subtitle: globalLessonData.subtitle, + description: globalLessonData.description, + startDate: globalLessonData.startDate, + endDate: globalLessonData.endDate, + date: globalLessonData.date, + nextSubject: globalLessonData.nextSubject, + nextRoom: globalLessonData.nextRoom + ) + + await activity.end( + ActivityContent(state: contentState, staleDate: Date.distantFuture), + dismissalPolicy: .immediate + ) } activityID = nil + activityPushToken = nil print("Live Activity sikeresen leállítva") } } } class func isRunning(_ activityID: String) -> Bool { - for activity in Activity.activities { - if activity.id == activityID { - return true - } + for activity in Activity.activities { + if activity.id == activityID { + return true } - return false } + return false + } } diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 8b50a74e..a8829dd5 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:refilc/api/providers/liveactivity/platform_channel.dart'; +import 'package:refilc/api/providers/liveactivity/server_sync_provider.dart'; import 'package:refilc/helpers/subject.dart'; import 'package:refilc/models/settings.dart'; import 'package:refilc/ui/flutter_colorpicker/utils.dart'; @@ -45,6 +46,7 @@ class LiveCardProvider extends ChangeNotifier { late Timer _timer; late final TimetableProvider _timetable; late final SettingsProvider _settings; + final ServerSyncProvider _serverSync = ServerSyncProvider(); late Duration _delay; @@ -59,6 +61,16 @@ class LiveCardProvider extends ChangeNotifier { _delay = settings.bellDelayEnabled ? Duration(seconds: settings.bellDelay) : Duration.zero; + + // Token rotation figyelése: ha iOS új APNs tokent ad ki, szinkronizáljuk a szerverrel + PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) { + _serverSync.refreshToken( + pushToken: pushToken, + bundleId: bundleId, + liveActivityColor: '#${settings.liveActivityColor.toHexString().substring(2)}', + ); + }; + update(); } @@ -325,15 +337,15 @@ class LiveCardProvider extends ChangeNotifier { currentState == LiveCardState.night)) { debugPrint( "Az első óra előtt állunk, kevesebb mint egy órával. Létrehozás..."); - PlatformChannel.createLiveActivity(toMap()); hasActivityStarted = true; + _createAndSync(); } else if (!hasActivityStarted && ((currentState == LiveCardState.duringLesson && currentLesson != null) || currentState == LiveCardState.duringBreak)) { debugPrint("Óra van, vagy szünet, de nincs LiveActivity. létrehozás..."); - PlatformChannel.createLiveActivity(toMap()); hasActivityStarted = true; + _createAndSync(); } //UPDATE @@ -385,6 +397,25 @@ class LiveCardProvider extends ChangeNotifier { notifyListeners(); } + Future _createAndSync() async { + final result = await PlatformChannel.createLiveActivity(toMap()); + if (result != null) { + final pushToken = result['pushToken'] ?? ''; + final deviceId = result['deviceId'] ?? ''; + final bundleId = result['bundleId'] ?? ''; + if (pushToken.isNotEmpty && deviceId.isNotEmpty) { + await _serverSync.registerAndSync( + deviceId: deviceId, + pushToken: pushToken, + bundleId: bundleId, + liveActivityColor: + '#${_settings.liveActivityColor.toHexString().substring(2)}', + todayLessons: _today(_timetable), + ); + } + } + } + bool get show => currentState != LiveCardState.empty; Duration get delay => _delay; diff --git a/refilc/lib/api/providers/liveactivity/platform_channel.dart b/refilc/lib/api/providers/liveactivity/platform_channel.dart index c6f7ba2f..24ef1901 100644 --- a/refilc/lib/api/providers/liveactivity/platform_channel.dart +++ b/refilc/lib/api/providers/liveactivity/platform_channel.dart @@ -6,16 +6,41 @@ import 'package:flutter/services.dart'; class PlatformChannel { static const MethodChannel _channel = MethodChannel('app.firka/liveactivity'); - /// Létrehozza a Live Activity-t és visszaadja az APNs push tokent (ha elérhető). - static Future createLiveActivity( + /// Callback token rotation esetén (iOS APNs új tokent ad ki). + /// A szerver szinkronizálásért felelős kód regisztrálhat ide. + static void Function(String pushToken, String deviceId, String bundleId)? onTokenUpdated; + + static void _setupTokenRotationListener() { + _channel.setMethodCallHandler((call) async { + if (call.method == 'liveActivityTokenUpdated') { + final args = call.arguments as Map?; + if (args != null && onTokenUpdated != null) { + onTokenUpdated!( + args['pushToken'] as String? ?? '', + args['deviceId'] as String? ?? '', + args['bundleId'] as String? ?? '', + ); + } + } + }); + } + + /// Létrehozza a Live Activity-t és visszaadja az APNs push tokent, + /// a device ID-t (Keychain UUID) és a bundle ID-t. + static Future?> createLiveActivity( Map activityData) async { if (Platform.isIOS) { + _setupTokenRotationListener(); try { - debugPrint("creating..."); - final String? pushToken = await _channel.invokeMethod( + debugPrint("creating live activity..."); + final result = await _channel.invokeMethod( 'createLiveActivity', activityData); - debugPrint("Live Activity push token: $pushToken"); - return pushToken; + if (result == null) return null; + return { + 'pushToken': result['pushToken'] as String? ?? '', + 'deviceId': result['deviceId'] as String? ?? '', + 'bundleId': result['bundleId'] as String? ?? '', + }; } on PlatformException catch (e) { debugPrint("Hiba történt a Live Activity létrehozásakor: ${e.message}"); } @@ -27,7 +52,7 @@ class PlatformChannel { Map activityData) async { if (Platform.isIOS) { try { - debugPrint("updating..."); + debugPrint("updating live activity..."); await _channel.invokeMethod('updateLiveActivity', activityData); } on PlatformException catch (e) { debugPrint("Hiba történt a Live Activity frissítésekor: ${e.message}"); @@ -38,11 +63,11 @@ class PlatformChannel { static Future endLiveActivity() async { if (Platform.isIOS) { try { - debugPrint("finishing..."); + debugPrint("ending live activity..."); await _channel.invokeMethod('endLiveActivity'); } on PlatformException catch (e) { debugPrint("Hiba történt a Live Activity befejezésekor: ${e.message}"); } } } -} \ No newline at end of file +} diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart new file mode 100644 index 00000000..83440a96 --- /dev/null +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -0,0 +1,134 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:refilc/helpers/subject.dart'; +import 'package:refilc/utils/format.dart'; +import 'package:refilc_kreta_api/models/lesson.dart'; + +class ServerSyncProvider { + static const String _baseUrl = 'https://live.firka.app'; + + String? _deviceId; + + /// App indításkor hívandó: regisztrálja a device-t és feltölti a mai órarendet. + Future registerAndSync({ + required String deviceId, + required String pushToken, + required String bundleId, + required String liveActivityColor, + required List todayLessons, + }) async { + _deviceId = deviceId; + + await _register( + deviceId: deviceId, + pushToken: pushToken, + bundleId: bundleId, + liveActivityColor: liveActivityColor, + ); + + final validLessons = _filterLessons(todayLessons); + if (validLessons.isNotEmpty) { + await _uploadSchedule(deviceId: deviceId, lessons: validLessons); + } + } + + /// Token rotation esetén frissíti a tokent a szerveren. + Future refreshToken({ + required String pushToken, + required String bundleId, + required String liveActivityColor, + }) async { + if (_deviceId == null) return; + await _register( + deviceId: _deviceId!, + pushToken: pushToken, + bundleId: bundleId, + liveActivityColor: liveActivityColor, + ); + } + + Future _register({ + required String deviceId, + required String pushToken, + required String bundleId, + required String liveActivityColor, + }) async { + try { + final client = HttpClient(); + final uri = Uri.parse('$_baseUrl/register'); + final request = await client.postUrl(uri); + request.headers.contentType = ContentType.json; + request.write(jsonEncode({ + 'device_id': deviceId, + 'apns_token': pushToken, + 'bundle_id': bundleId, + 'settings': { + 'live_activity_color': liveActivityColor, + }, + })); + final response = + await request.close().timeout(const Duration(seconds: 10)); + if (response.statusCode != 200 && response.statusCode != 201) { + debugPrint('ServerSync register hiba: ${response.statusCode}'); + } else { + debugPrint('ServerSync: device regisztrálva'); + } + client.close(); + } catch (e) { + debugPrint('ServerSync register kivétel: $e'); + } + } + + Future _uploadSchedule({ + required String deviceId, + required List lessons, + }) async { + try { + final now = DateTime.now(); + final dateStr = + '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}'; + + final lessonsJson = lessons + .map((l) => { + 'index': l.lessonIndex.toString(), + 'subject': l.subject.renamedTo ?? + ShortSubject.resolve(subject: l.subject).capital(), + 'icon': SubjectIcon.resolveName(subject: l.subject), + 'room': l.room.replaceAll('_', ' '), + 'description': l.description, + 'start': l.start.millisecondsSinceEpoch, + 'end': l.end.millisecondsSinceEpoch, + }) + .toList(); + + final client = HttpClient(); + final uri = Uri.parse('$_baseUrl/schedule'); + final request = await client.postUrl(uri); + request.headers.contentType = ContentType.json; + request.write(jsonEncode({ + 'device_id': deviceId, + 'date': dateStr, + 'lessons': lessonsJson, + })); + final response = + await request.close().timeout(const Duration(seconds: 10)); + if (response.statusCode != 200 && response.statusCode != 201) { + debugPrint('ServerSync schedule hiba: ${response.statusCode}'); + } else { + debugPrint('ServerSync: ${lessons.length} óra feltöltve ($dateStr)'); + } + client.close(); + } catch (e) { + debugPrint('ServerSync schedule kivétel: $e'); + } + } + + List _filterLessons(List lessons) { + return lessons + .where((l) => + l.status?.name != 'Elmaradt' && l.subject.id != '' && !l.isEmpty) + .toList() + ..sort((a, b) => a.start.compareTo(b.start)); + } +} From 556a49646d510274aa0ec3398be25e7119801ba0 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Tue, 3 Mar 2026 12:14:27 +0100 Subject: [PATCH 02/59] Update base URL in ServerSyncProvider to point to the correct server --- .../lib/api/providers/liveactivity/server_sync_provider.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index 83440a96..a641ac01 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -6,11 +6,10 @@ import 'package:refilc/utils/format.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; class ServerSyncProvider { - static const String _baseUrl = 'https://live.firka.app'; + static const String _baseUrl = 'https://node.devbeni.lol:1506'; String? _deviceId; - /// App indításkor hívandó: regisztrálja a device-t és feltölti a mai órarendet. Future registerAndSync({ required String deviceId, required String pushToken, From 7c329b0ae6217c0ae999ddd752df473bf0c05c31 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Thu, 5 Mar 2026 08:55:28 +0100 Subject: [PATCH 03/59] Add demo mode support and demo data for various providers --- refilc_kreta_api/lib/demo/demo_data.dart | 381 ++++++++++++++++++ .../lib/providers/absence_provider.dart | 7 + .../lib/providers/event_provider.dart | 2 + .../lib/providers/exam_provider.dart | 7 + .../lib/providers/grade_provider.dart | 10 +- .../lib/providers/homework_provider.dart | 7 + .../lib/providers/message_provider.dart | 15 +- .../lib/providers/note_provider.dart | 2 + .../lib/providers/timetable_provider.dart | 8 + .../lib/screens/login/login_screen.dart | 19 + .../lib/screens/login/login_screen.i18n.dart | 3 + 11 files changed, 456 insertions(+), 5 deletions(-) create mode 100644 refilc_kreta_api/lib/demo/demo_data.dart diff --git a/refilc_kreta_api/lib/demo/demo_data.dart b/refilc_kreta_api/lib/demo/demo_data.dart new file mode 100644 index 00000000..7e050d3a --- /dev/null +++ b/refilc_kreta_api/lib/demo/demo_data.dart @@ -0,0 +1,381 @@ +import 'package:refilc/models/user.dart'; +import 'package:refilc_kreta_api/models/absence.dart'; +import 'package:refilc_kreta_api/models/category.dart'; +import 'package:refilc_kreta_api/models/exam.dart'; +import 'package:refilc_kreta_api/models/grade.dart'; +import 'package:refilc_kreta_api/models/homework.dart'; +import 'package:refilc_kreta_api/models/lesson.dart'; +import 'package:refilc_kreta_api/models/message.dart'; +import 'package:refilc_kreta_api/models/recipient.dart'; +import 'package:refilc_kreta_api/models/subject.dart'; +import 'package:refilc_kreta_api/models/teacher.dart'; +import 'package:refilc_kreta_api/models/week.dart'; + +class DemoData { + static final _subjectMath = GradeSubject( + id: 'demo-subject-math', + category: Category(id: 'matematika', name: 'matematika'), + name: 'Matematika', + ); + static final _subjectHun = GradeSubject( + id: 'demo-subject-hun', + category: Category(id: 'magyar_nyelv_es_irodalom', name: 'magyar_nyelv_es_irodalom'), + name: 'Magyar nyelv és irodalom', + ); + static final _subjectHist = GradeSubject( + id: 'demo-subject-hist', + category: Category(id: 'tortenelem_es_allampolgari_ismeretek', name: 'tortenelem_es_allampolgari_ismeretek'), + name: 'Történelem', + ); + static final _subjectEng = GradeSubject( + id: 'demo-subject-eng', + category: Category(id: 'angol_nyelv', name: 'angol_nyelv'), + name: 'Angol nyelv', + ); + static final _subjectPhy = GradeSubject( + id: 'demo-subject-phy', + category: Category(id: 'fizika', name: 'fizika'), + name: 'Fizika', + ); + static final _subjectBio = GradeSubject( + id: 'demo-subject-bio', + category: Category(id: 'biologia_egeszsegtan', name: 'biologia_egeszsegtan'), + name: 'Biológia', + ); + static final _subjectChem = GradeSubject( + id: 'demo-subject-chem', + category: Category(id: 'kemia', name: 'kemia'), + name: 'Kémia', + ); + static final _subjectPE = GradeSubject( + id: 'demo-subject-pe', + category: Category(id: 'testnevelés_és_sport', name: 'testnevelés_és_sport'), + name: 'Testnevelés', + ); + static final _subjectIT = GradeSubject( + id: 'demo-subject-it', + category: Category(id: 'informatika', name: 'informatika'), + name: 'Informatika', + ); + + static final _teacherNagy = Teacher.fromString('Nagy Katalin'); + static final _teacherSzabo = Teacher.fromString('Szabó Péter'); + static final _teacherKovacs = Teacher.fromString('Kovács Mária'); + static final _teacherToth = Teacher.fromString('Tóth László'); + static final _teacherVarga = Teacher.fromString('Varga Erzsébet'); + static final _teacherFekete = Teacher.fromString('Fekete Gábor'); + + static final _modeOral = Category(id: '1,SzobaliVizsga', name: 'Szóbeli vizsga', description: 'Szóbeli vizsga'); + static final _modeWritten = Category(id: '2,IrasbaliVizsga', name: 'Írásbeli vizsga', description: 'Írásbeli vizsga'); + static final _modePractical = Category(id: '3,Gyakorlati', name: 'Gyakorlati', description: 'Gyakorlati'); + + static List get grades { + final now = DateTime.now(); + return [ + _makeGrade('demo-g-1', 5, 'Jeles', 'Ötös', 100, _subjectMath, _teacherNagy, 'Függvények', now.subtract(const Duration(days: 3)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-2', 4, 'Jó', 'Négyes', 100, _subjectMath, _teacherNagy, 'Egyenletek', now.subtract(const Duration(days: 14)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-3', 5, 'Jeles', 'Ötös', 100, _subjectHun, _teacherKovacs, 'Arany János költészete', now.subtract(const Duration(days: 5)), _modeOral, GradeType.midYear), + _makeGrade('demo-g-4', 4, 'Jó', 'Négyes', 100, _subjectHun, _teacherKovacs, 'Fogalmazás', now.subtract(const Duration(days: 20)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-5', 5, 'Jeles', 'Ötös', 100, _subjectEng, _teacherSzabo, 'Grammar test', now.subtract(const Duration(days: 7)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-6', 5, 'Jeles', 'Ötös', 100, _subjectEng, _teacherSzabo, 'Speaking', now.subtract(const Duration(days: 18)), _modeOral, GradeType.midYear), + _makeGrade('demo-g-7', 4, 'Jó', 'Négyes', 100, _subjectHist, _teacherToth, 'Az első világháború', now.subtract(const Duration(days: 10)), _modeOral, GradeType.midYear), + _makeGrade('demo-g-8', 3, 'Közepes', 'Hármas', 100, _subjectHist, _teacherToth, 'Témazáró', now.subtract(const Duration(days: 25)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-9', 5, 'Jeles', 'Ötös', 100, _subjectPhy, _teacherVarga, 'Mechanika', now.subtract(const Duration(days: 8)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-10', 4, 'Jó', 'Négyes', 100, _subjectBio, _teacherFekete, 'Sejtbiológia', now.subtract(const Duration(days: 12)), _modeOral, GradeType.midYear), + _makeGrade('demo-g-11', 5, 'Jeles', 'Ötös', 100, _subjectChem, _teacherVarga, 'Kémiai kötések', now.subtract(const Duration(days: 6)), _modeWritten, GradeType.midYear), + _makeGrade('demo-g-12', 5, 'Jeles', 'Ötös', 100, _subjectIT, _teacherSzabo, 'Programozás alapjai', now.subtract(const Duration(days: 4)), _modePractical, GradeType.midYear), + _makeGrade('demo-g-13', 4, 'Jó', 'Négyes', 100, _subjectMath, _teacherNagy, 'Statisztika', now.subtract(const Duration(days: 30)), _modeWritten, GradeType.halfYear), + _makeGrade('demo-g-14', 5, 'Jeles', 'Ötös', 100, _subjectHun, _teacherKovacs, 'Félévzáró', now.subtract(const Duration(days: 60)), _modeWritten, GradeType.halfYear), + _makeGrade('demo-g-15', 4, 'Jó', 'Négyes', 100, _subjectEng, _teacherSzabo, 'Mid-year exam', now.subtract(const Duration(days: 60)), _modeWritten, GradeType.halfYear), + ]; + } + + static Grade _makeGrade( + String id, + int value, + String valueName, + String shortName, + int weight, + GradeSubject subject, + Teacher teacher, + String description, + DateTime date, + Category mode, + GradeType type, + ) { + return Grade( + id: id, + date: date, + value: GradeValue(value, valueName, shortName, weight), + teacher: teacher, + description: description, + type: type, + groupId: 'demo-group', + subject: subject, + mode: mode, + writeDate: date, + seenDate: date, + form: '', + json: { + 'SzamErtek': value, + 'SzovegesErtek': valueName, + 'SzovegesErtekelesRovidNev': shortName, + 'SulySzazalekErteke': weight, + 'ErtekFajta': null, + }, + ); + } + + static Map> get timetable { + final week = Week.current(); + return {week: _lessonsForWeek(week)}; + } + + static List _lessonsForWeek(Week week) { + final monday = week.start; + List lessons = []; + + // Monday + lessons.addAll(_dayLessons(monday, [ + _LessonDef('Matematika', _subjectMath, _teacherNagy, '101', '9A'), + _LessonDef('Magyar nyelv és irodalom', _subjectHun, _teacherKovacs, '203', '9A'), + _LessonDef('Történelem', _subjectHist, _teacherToth, '105', '9A'), + _LessonDef('Angol nyelv', _subjectEng, _teacherSzabo, '102', '9A'), + _LessonDef('Testnevelés', _subjectPE, _teacherFekete, 'Tornaterem', '9A'), + ])); + + // Tuesday + lessons.addAll(_dayLessons(monday.add(const Duration(days: 1)), [ + _LessonDef('Fizika', _subjectPhy, _teacherVarga, '204', '9A'), + _LessonDef('Biológia', _subjectBio, _teacherFekete, '205', '9A'), + _LessonDef('Matematika', _subjectMath, _teacherNagy, '101', '9A'), + _LessonDef('Informatika', _subjectIT, _teacherSzabo, 'Számítóterem', '9A'), + ])); + + // Wednesday + lessons.addAll(_dayLessons(monday.add(const Duration(days: 2)), [ + _LessonDef('Magyar nyelv és irodalom', _subjectHun, _teacherKovacs, '203', '9A'), + _LessonDef('Kémia', _subjectChem, _teacherVarga, '206', '9A'), + _LessonDef('Angol nyelv', _subjectEng, _teacherSzabo, '102', '9A'), + _LessonDef('Történelem', _subjectHist, _teacherToth, '105', '9A'), + _LessonDef('Testnevelés', _subjectPE, _teacherFekete, 'Tornaterem', '9A'), + ])); + + // Thursday + lessons.addAll(_dayLessons(monday.add(const Duration(days: 3)), [ + _LessonDef('Matematika', _subjectMath, _teacherNagy, '101', '9A'), + _LessonDef('Biológia', _subjectBio, _teacherFekete, '205', '9A'), + _LessonDef('Fizika', _subjectPhy, _teacherVarga, '204', '9A'), + _LessonDef('Informatika', _subjectIT, _teacherSzabo, 'Számítóterem', '9A'), + ])); + + // Friday + lessons.addAll(_dayLessons(monday.add(const Duration(days: 4)), [ + _LessonDef('Magyar nyelv és irodalom', _subjectHun, _teacherKovacs, '203', '9A'), + _LessonDef('Kémia', _subjectChem, _teacherVarga, '206', '9A'), + _LessonDef('Matematika', _subjectMath, _teacherNagy, '101', '9A'), + _LessonDef('Angol nyelv', _subjectEng, _teacherSzabo, '102', '9A'), + ])); + + return lessons; + } + + static List _dayLessons(DateTime day, List<_LessonDef> defs) { + final List result = []; + // School starts at 8:00, each lesson is 45 min, 15 min break + DateTime time = DateTime(day.year, day.month, day.day, 8, 0); + for (int i = 0; i < defs.length; i++) { + final def = defs[i]; + final start = time; + final end = time.add(const Duration(minutes: 45)); + result.add(Lesson( + id: 'demo-lesson-${day.weekday}-$i', + date: day, + subject: def.subject, + lessonIndex: '${i + 1}', + teacher: def.teacher, + start: start, + end: end, + homeworkId: '', + description: '', + room: def.room, + groupName: def.group, + name: def.name, + )); + time = end.add(const Duration(minutes: 15)); + } + return result; + } + + static List get absences { + final now = DateTime.now(); + return [ + _makeAbsence('demo-abs-1', _subjectMath, _teacherNagy, now.subtract(const Duration(days: 15)), Justification.excused), + _makeAbsence('demo-abs-2', _subjectMath, _teacherNagy, now.subtract(const Duration(days: 15)), Justification.excused), + _makeAbsence('demo-abs-3', _subjectHun, _teacherKovacs, now.subtract(const Duration(days: 15)), Justification.excused), + _makeAbsence('demo-abs-4', _subjectEng, _teacherSzabo, now.subtract(const Duration(days: 8)), Justification.pending), + _makeAbsence('demo-abs-5', _subjectHist, _teacherToth, now.subtract(const Duration(days: 8)), Justification.pending), + _makeAbsence('demo-abs-6', _subjectPhy, _teacherVarga, now.subtract(const Duration(days: 2)), Justification.unexcused), + ]; + } + + static Absence _makeAbsence( + String id, + GradeSubject subject, + Teacher teacher, + DateTime date, + Justification state, + ) { + final start = DateTime(date.year, date.month, date.day, 8, 0); + final end = start.add(const Duration(minutes: 45)); + return Absence( + id: id, + date: date, + delay: 0, + submitDate: date, + teacher: teacher, + state: state, + subject: subject, + lessonStart: start, + lessonEnd: end, + group: 'demo-group', + ); + } + + static List get exams { + final now = DateTime.now(); + return [ + Exam( + id: 'demo-exam-1', + date: now.subtract(const Duration(days: 3)), + writeDate: now.add(const Duration(days: 7)), + subject: _subjectMath, + teacher: _teacherNagy, + description: 'Trigonometria témazáró', + group: 'demo-group', + ), + Exam( + id: 'demo-exam-2', + date: now.subtract(const Duration(days: 5)), + writeDate: now.add(const Duration(days: 12)), + subject: _subjectHun, + teacher: _teacherKovacs, + description: 'Petőfi Sándor életmű dolgozat', + group: 'demo-group', + ), + Exam( + id: 'demo-exam-3', + date: now.subtract(const Duration(days: 1)), + writeDate: now.add(const Duration(days: 5)), + subject: _subjectPhy, + teacher: _teacherVarga, + description: 'Elektromosságtan', + group: 'demo-group', + ), + ]; + } + + static List get homework { + final now = DateTime.now(); + return [ + Homework( + id: 'demo-hw-1', + date: now.subtract(const Duration(days: 2)), + lessonDate: now.subtract(const Duration(days: 2)), + deadline: now.add(const Duration(days: 5)), + byTeacher: true, + homeworkEnabled: true, + teacher: _teacherNagy, + content: 'Oldjátok meg a tankönyv 84-85. oldalán lévő feladatokat (1-15).', + subject: _subjectMath, + group: 'demo-group', + attachments: [], + ), + Homework( + id: 'demo-hw-2', + date: now.subtract(const Duration(days: 4)), + lessonDate: now.subtract(const Duration(days: 4)), + deadline: now.add(const Duration(days: 3)), + byTeacher: true, + homeworkEnabled: true, + teacher: _teacherKovacs, + content: 'Írjatok egy 1-2 oldalas elemzést Petőfi Sándor "Szeptember végén" c. verséről.', + subject: _subjectHun, + group: 'demo-group', + attachments: [], + ), + Homework( + id: 'demo-hw-3', + date: now.subtract(const Duration(days: 1)), + lessonDate: now.subtract(const Duration(days: 1)), + deadline: now.add(const Duration(days: 6)), + byTeacher: true, + homeworkEnabled: true, + teacher: _teacherSzabo, + content: 'Complete exercises 3-7 on page 42 of the workbook.', + subject: _subjectEng, + group: 'demo-group', + attachments: [], + ), + ]; + } + + static List get messages { + final now = DateTime.now(); + return [ + Message( + id: 10001, + messageId: 10001, + seen: true, + deleted: false, + date: now.subtract(const Duration(days: 1)), + author: 'Nagy Katalin', + content: 'Kedves Szülők!\n\nTájékoztatjuk Önöket, hogy jövő héten pótdolgozatot írunk matematikából. Kérem, segítsenek gyermeküknek a felkészülésben.\n\nÜdvözlettel,\nNagy Katalin', + subject: 'Pótdolgozat - Matematika', + type: MessageType.inbox, + recipients: [Recipient(id: 1, name: 'Demo Diák', kretaId: 1)], + attachments: [], + isSeen: true, + ), + Message( + id: 10002, + messageId: 10002, + seen: false, + deleted: false, + date: now.subtract(const Duration(days: 3)), + author: 'Kovács Mária', + content: 'Kedves Diákok!\n\nEmlékeztetem Önöket, hogy a fogalmazást péntekig be kell adni. Kérem, ne felejtsék el!\n\nÜdvözlettel,\nKovács Mária', + subject: 'Fogalmazás határideje', + type: MessageType.inbox, + recipients: [Recipient(id: 1, name: 'Demo Diák', kretaId: 1)], + attachments: [], + isSeen: false, + ), + Message( + id: 10003, + messageId: 10003, + seen: true, + deleted: false, + date: now.subtract(const Duration(days: 7)), + author: 'Tóth László', + content: 'Kedves Szülők!\n\nAz osztálykirándulás időpontja: március 20. Kérem, hogy a beleegyező nyilatkozatot hozzák vissza aláírva.\n\nÜdvözlettel,\nTóth László\nosztályfőnök', + subject: 'Osztálykirándulás', + type: MessageType.inbox, + recipients: [Recipient(id: 1, name: 'Demo Diák', kretaId: 1)], + attachments: [], + isSeen: true, + ), + ]; + } + + static bool isDemo(String? userId) => userId == demoUserId; +} + +class _LessonDef { + final String name; + final GradeSubject subject; + final Teacher teacher; + final String room; + final String group; + const _LessonDef(this.name, this.subject, this.teacher, this.room, this.group); +} diff --git a/refilc_kreta_api/lib/providers/absence_provider.dart b/refilc_kreta_api/lib/providers/absence_provider.dart index fcf4d044..05544c21 100644 --- a/refilc_kreta_api/lib/providers/absence_provider.dart +++ b/refilc_kreta_api/lib/providers/absence_provider.dart @@ -5,6 +5,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/absence.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -81,6 +82,12 @@ class AbsenceProvider with ChangeNotifier { Future fetch() async { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Absences for User null"; + + if (DemoData.isDemo(user.id)) { + await store(DemoData.absences); + return; + } + String iss = user.instituteCode; List? absencesJson = await Provider.of(_context, listen: false) diff --git a/refilc_kreta_api/lib/providers/event_provider.dart b/refilc_kreta_api/lib/providers/event_provider.dart index 63836be2..c361150e 100644 --- a/refilc_kreta_api/lib/providers/event_provider.dart +++ b/refilc_kreta_api/lib/providers/event_provider.dart @@ -3,6 +3,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/event.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -40,6 +41,7 @@ class EventProvider with ChangeNotifier { Future fetch() async { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Events for User null"; + if (DemoData.isDemo(user.id)) return; String iss = user.instituteCode; List? eventsJson = await Provider.of(_context, listen: false) diff --git a/refilc_kreta_api/lib/providers/exam_provider.dart b/refilc_kreta_api/lib/providers/exam_provider.dart index 65d8f43c..5c3c58fc 100644 --- a/refilc_kreta_api/lib/providers/exam_provider.dart +++ b/refilc_kreta_api/lib/providers/exam_provider.dart @@ -3,6 +3,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/exam.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -68,6 +69,12 @@ class ExamProvider with ChangeNotifier { Future fetch() async { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Exams for User null"; + + if (DemoData.isDemo(user.id)) { + await store(DemoData.exams); + return; + } + String iss = user.instituteCode; List? examsJson = await Provider.of(_context, listen: false) diff --git a/refilc_kreta_api/lib/providers/grade_provider.dart b/refilc_kreta_api/lib/providers/grade_provider.dart index e35f46ab..01da001b 100644 --- a/refilc_kreta_api/lib/providers/grade_provider.dart +++ b/refilc_kreta_api/lib/providers/grade_provider.dart @@ -5,6 +5,7 @@ import 'package:refilc/models/settings.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/grade.dart'; import 'package:refilc_kreta_api/models/group_average.dart'; import 'package:refilc_kreta_api/providers/grade_provider.i18n.dart'; @@ -164,11 +165,14 @@ Future unseenAll() async { // Fetches Grades from the Kreta API then stores them in the database Future fetch() async { - // test cucc - // unseenAll(); - User? user = _user.user; if (user == null) throw "Cannot fetch Grades for User null"; + + if (DemoData.isDemo(user.id)) { + await store(DemoData.grades); + return; + } + String iss = user.instituteCode; List? gradesJson = await _kreta.getAPI(KretaAPI.grades(iss)); diff --git a/refilc_kreta_api/lib/providers/homework_provider.dart b/refilc_kreta_api/lib/providers/homework_provider.dart index 182692dc..7a135f44 100644 --- a/refilc_kreta_api/lib/providers/homework_provider.dart +++ b/refilc_kreta_api/lib/providers/homework_provider.dart @@ -4,6 +4,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/homework.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -75,6 +76,12 @@ class HomeworkProvider with ChangeNotifier { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Homework for User null"; + if (DemoData.isDemo(user.id)) { + _homework = DemoData.homework; + notifyListeners(); + return; + } + String iss = user.instituteCode; List? homeworkJson = []; diff --git a/refilc_kreta_api/lib/providers/message_provider.dart b/refilc_kreta_api/lib/providers/message_provider.dart index cf592cba..87b5fe5b 100644 --- a/refilc_kreta_api/lib/providers/message_provider.dart +++ b/refilc_kreta_api/lib/providers/message_provider.dart @@ -7,6 +7,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/message.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -53,13 +54,21 @@ class MessageProvider with ChangeNotifier { Future fetch({MessageType type = MessageType.inbox}) async { // Check Message Type if (type == MessageType.draft) return; - String messageType = - ["beerkezett", "elkuldott", "torolt"].elementAt(type.index); // Check User User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Messages for User null"; + if (DemoData.isDemo(user.id)) { + if (type == MessageType.inbox) { + await store(DemoData.messages, type); + } + return; + } + + String messageType = + ["beerkezett", "elkuldott", "torolt"].elementAt(type.index); + // Get messages List? messagesJson = await Provider.of(_context, listen: false) .getAPI(KretaAPI.messages(messageType)); @@ -127,6 +136,8 @@ class MessageProvider with ChangeNotifier { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Messages for User null"; + if (DemoData.isDemo(user.id)) return; + // get categories List? availableCategoriesJson = await Provider.of(_context, listen: false) diff --git a/refilc_kreta_api/lib/providers/note_provider.dart b/refilc_kreta_api/lib/providers/note_provider.dart index 42a232b2..11954671 100644 --- a/refilc_kreta_api/lib/providers/note_provider.dart +++ b/refilc_kreta_api/lib/providers/note_provider.dart @@ -3,6 +3,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/note.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -39,6 +40,7 @@ class NoteProvider with ChangeNotifier { Future fetch() async { User? user = Provider.of(_context, listen: false).user; if (user == null) throw "Cannot fetch Notes for User null"; + if (DemoData.isDemo(user.id)) return; String iss = user.instituteCode; List? notesJson = await Provider.of(_context, listen: false) diff --git a/refilc_kreta_api/lib/providers/timetable_provider.dart b/refilc_kreta_api/lib/providers/timetable_provider.dart index 932acbab..4363fae7 100644 --- a/refilc_kreta_api/lib/providers/timetable_provider.dart +++ b/refilc_kreta_api/lib/providers/timetable_provider.dart @@ -3,6 +3,7 @@ import 'package:refilc/api/providers/database_provider.dart'; import 'package:refilc/models/user.dart'; import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/client.dart'; +import 'package:refilc_kreta_api/demo/demo_data.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; import 'package:refilc_kreta_api/models/week.dart'; import 'package:flutter/foundation.dart'; @@ -73,6 +74,13 @@ class TimetableProvider with ChangeNotifier { if (week == null) return; User? user = _user.user; if (user == null) throw "Cannot fetch Lessons for User null"; + + if (DemoData.isDemo(user.id)) { + lessons = DemoData.timetable; + notifyListeners(); + return; + } + String iss = user.instituteCode; List? lessonsJson; diff --git a/refilc_mobile_ui/lib/screens/login/login_screen.dart b/refilc_mobile_ui/lib/screens/login/login_screen.dart index c40204d4..94336a44 100644 --- a/refilc_mobile_ui/lib/screens/login/login_screen.dart +++ b/refilc_mobile_ui/lib/screens/login/login_screen.dart @@ -383,6 +383,25 @@ class LoginScreenState extends State { ), ), const SizedBox(height: 19), + GestureDetector( + onTap: () { + final userProvider = Provider.of(context, listen: false); + final demoUser = User.demo(); + userProvider.addUser(demoUser); + userProvider.setUser(demoUser.id); + setSystemChrome(context); + Navigator.of(context).pushReplacementNamed('login_to_navigation'); + }, + child: Text( + 'demo_login'.i18n, + style: TextStyle( + color: AppColors.of(context).loginSecondary, + fontWeight: FontWeight.w500, + fontSize: 14.0, + ), + ), + ), + const SizedBox(height: 12), // privacy policy GestureDetector( onTap: () => PrivacyView.show(context), diff --git a/refilc_mobile_ui/lib/screens/login/login_screen.i18n.dart b/refilc_mobile_ui/lib/screens/login/login_screen.i18n.dart index da6b0e38..4363b692 100644 --- a/refilc_mobile_ui/lib/screens/login/login_screen.i18n.dart +++ b/refilc_mobile_ui/lib/screens/login/login_screen.i18n.dart @@ -34,6 +34,7 @@ extension Localization on String { "welcome_text_4": "You can also organise your notes by lesson in the built-in notebook, so you can find everything in one app.", "login_w_kreta_acc": "Log in with your e-KRÉTA account", + "demo_login": "Try demo mode", }, "hu_hu": { "username": "Felhasználónév", @@ -66,6 +67,7 @@ extension Localization on String { "welcome_text_4": "A beépített jegyzetfüzetbe órák szerint is rendezheted a jegyzeteidet, így mindent megtalálsz egy appban.", "login_w_kreta_acc": "Bejelentkezés e-KRÉTA fiókkal", + "demo_login": "Demo mód kipróbálása", }, "de_de": { "username": "Benutzername", @@ -98,6 +100,7 @@ extension Localization on String { "welcome_text_4": "You can also organise your notes by lesson in the built-in notebook, so you can find everything in one app.", "login_w_kreta_acc": "Mit e-KRÉTA-Konto anmelden", + "demo_login": "Demo-Modus ausprobieren", }, }; From 6c5279205b6ff304cf33c43a4a400574a7693443 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Thu, 5 Mar 2026 10:24:23 +0100 Subject: [PATCH 04/59] Remove MinimumOSVersion key from AppFrameworkInfo.plist --- refilc/ios/Flutter/AppFrameworkInfo.plist | 2 -- 1 file changed, 2 deletions(-) diff --git a/refilc/ios/Flutter/AppFrameworkInfo.plist b/refilc/ios/Flutter/AppFrameworkInfo.plist index 1dc6cf76..391a902b 100644 --- a/refilc/ios/Flutter/AppFrameworkInfo.plist +++ b/refilc/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 13.0 From dc5a5723fc589b775839484314c5d2230758440a Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Thu, 5 Mar 2026 10:32:12 +0100 Subject: [PATCH 05/59] Add demo group averages to DemoData and update GradeProvider to store them --- refilc_kreta_api/lib/demo/demo_data.dart | 13 +++++++++++++ refilc_kreta_api/lib/providers/grade_provider.dart | 1 + 2 files changed, 14 insertions(+) diff --git a/refilc_kreta_api/lib/demo/demo_data.dart b/refilc_kreta_api/lib/demo/demo_data.dart index 7e050d3a..aa298ed7 100644 --- a/refilc_kreta_api/lib/demo/demo_data.dart +++ b/refilc_kreta_api/lib/demo/demo_data.dart @@ -3,6 +3,7 @@ import 'package:refilc_kreta_api/models/absence.dart'; import 'package:refilc_kreta_api/models/category.dart'; import 'package:refilc_kreta_api/models/exam.dart'; import 'package:refilc_kreta_api/models/grade.dart'; +import 'package:refilc_kreta_api/models/group_average.dart'; import 'package:refilc_kreta_api/models/homework.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; import 'package:refilc_kreta_api/models/message.dart'; @@ -368,6 +369,18 @@ class DemoData { ]; } + static List get groupAverages => [ + GroupAverage(uid: 'demo-avg-math', average: 4.2, subject: _subjectMath), + GroupAverage(uid: 'demo-avg-hun', average: 3.8, subject: _subjectHun), + GroupAverage(uid: 'demo-avg-hist', average: 3.9, subject: _subjectHist), + GroupAverage(uid: 'demo-avg-eng', average: 4.5, subject: _subjectEng), + GroupAverage(uid: 'demo-avg-phy', average: 3.6, subject: _subjectPhy), + GroupAverage(uid: 'demo-avg-bio', average: 4.1, subject: _subjectBio), + GroupAverage(uid: 'demo-avg-chem', average: 3.7, subject: _subjectChem), + GroupAverage(uid: 'demo-avg-pe', average: 4.8, subject: _subjectPE), + GroupAverage(uid: 'demo-avg-it', average: 4.3, subject: _subjectIT), + ]; + static bool isDemo(String? userId) => userId == demoUserId; } diff --git a/refilc_kreta_api/lib/providers/grade_provider.dart b/refilc_kreta_api/lib/providers/grade_provider.dart index 01da001b..bd911625 100644 --- a/refilc_kreta_api/lib/providers/grade_provider.dart +++ b/refilc_kreta_api/lib/providers/grade_provider.dart @@ -170,6 +170,7 @@ Future unseenAll() async { if (DemoData.isDemo(user.id)) { await store(DemoData.grades); + await storeGroupAvg(DemoData.groupAverages); return; } From 53623d84dfaef0de8793e50a3a45968d9d65f1a1 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Thu, 5 Mar 2026 10:35:43 +0100 Subject: [PATCH 06/59] Set Swift version and flags for DKImagePickerController in Podfile post-install --- refilc/ios/Podfile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/refilc/ios/Podfile b/refilc/ios/Podfile index 8f025e07..02155af8 100644 --- a/refilc/ios/Podfile +++ b/refilc/ios/Podfile @@ -41,6 +41,10 @@ post_install do |installer| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET' + if target.name == 'DKImagePickerController' + config.build_settings['SWIFT_VERSION'] = '5.0' + config.build_settings['OTHER_SWIFT_FLAGS'] = '$(inherited) -Xfrontend -disable-reflection-metadata' + end end end From 5c9248c3eb796a96eaf20247049ca3ed9d632220 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 09:20:24 +0100 Subject: [PATCH 07/59] Fix progress bar width calculation in StatusBar widget --- refilc_mobile_ui/lib/screens/navigation/status_bar.dart | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/navigation/status_bar.dart b/refilc_mobile_ui/lib/screens/navigation/status_bar.dart index cead16c6..d8e256e9 100644 --- a/refilc_mobile_ui/lib/screens/navigation/status_bar.dart +++ b/refilc_mobile_ui/lib/screens/navigation/status_bar.dart @@ -55,9 +55,8 @@ class StatusBarState extends State { height: currentStatus != null ? 4.0 : 0, duration: const Duration(milliseconds: 250), curve: Curves.easeInOut, - width: MediaQuery.of(context).size.width * - statusProvider.progress - - 36.0, + width: (MediaQuery.of(context).size.width - 36.0) * + statusProvider.progress, decoration: BoxDecoration( color: Theme.of(context) .colorScheme From 1adc7b0a15d64e6bac9170faceb2f99984434969 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 09:21:36 +0100 Subject: [PATCH 08/59] Refactor width calculation for AnimatedContainer in StatusBar widget --- refilc_mobile_ui/lib/pages/grades/grade_subject_view.dart | 4 ++-- refilc_mobile_ui/lib/screens/navigation/status_bar.dart | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/refilc_mobile_ui/lib/pages/grades/grade_subject_view.dart b/refilc_mobile_ui/lib/pages/grades/grade_subject_view.dart index b9ed4258..35c3281d 100644 --- a/refilc_mobile_ui/lib/pages/grades/grade_subject_view.dart +++ b/refilc_mobile_ui/lib/pages/grades/grade_subject_view.dart @@ -305,6 +305,8 @@ class _GradeSubjectViewState extends State if (DateTime.now().day > 5) { _timetableController.next(context); } + + fetchGoalPlans(); } void fetchGoalPlans() async { @@ -370,8 +372,6 @@ class _GradeSubjectViewState extends State buildTiles(ghostGrades); } - fetchGoalPlans(); - return Scaffold( key: _scaffoldKey, floatingActionButtonLocation: ExpandableFab.location, diff --git a/refilc_mobile_ui/lib/screens/navigation/status_bar.dart b/refilc_mobile_ui/lib/screens/navigation/status_bar.dart index d8e256e9..10fb27e7 100644 --- a/refilc_mobile_ui/lib/screens/navigation/status_bar.dart +++ b/refilc_mobile_ui/lib/screens/navigation/status_bar.dart @@ -86,9 +86,8 @@ class StatusBarState extends State { child: AnimatedContainer( duration: const Duration(milliseconds: 250), curve: Curves.easeInOut, - width: MediaQuery.of(context).size.width * - statusProvider.progress - - 36.0, + width: (MediaQuery.of(context).size.width - 36.0) * + statusProvider.progress, alignment: Alignment.centerRight, child: Container( decoration: BoxDecoration( From 4ec24aa69f2c4ef37b58c2b58bf6ec42faddfcc5 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 09:24:41 +0100 Subject: [PATCH 09/59] Update base URL in ServerSyncProvider to point to legacy server --- refilc/lib/api/providers/liveactivity/server_sync_provider.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index a641ac01..0963777e 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -6,7 +6,7 @@ import 'package:refilc/utils/format.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; class ServerSyncProvider { - static const String _baseUrl = 'https://node.devbeni.lol:1506'; + static const String _baseUrl = 'https://legacy-la.devbeni.lol'; String? _deviceId; From 280d3561cfdec2584d4761891ee81887c0ea188c Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 10:12:16 +0100 Subject: [PATCH 10/59] Refactor ServerSyncProvider usage in LiveCardProvider and add unregister method --- .../lib/api/providers/live_card_provider.dart | 8 ++++--- .../liveactivity/server_sync_provider.dart | 21 +++++++++++++++++++ refilc/lib/api/providers/sync.dart | 1 + refilc/lib/helpers/live_activity_helper.dart | 1 + 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index a8829dd5..b16b7c81 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -46,7 +46,7 @@ class LiveCardProvider extends ChangeNotifier { late Timer _timer; late final TimetableProvider _timetable; late final SettingsProvider _settings; - final ServerSyncProvider _serverSync = ServerSyncProvider(); + static final ServerSyncProvider serverSync = ServerSyncProvider(); late Duration _delay; @@ -64,7 +64,7 @@ class LiveCardProvider extends ChangeNotifier { // Token rotation figyelése: ha iOS új APNs tokent ad ki, szinkronizáljuk a szerverrel PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) { - _serverSync.refreshToken( + serverSync.refreshToken( pushToken: pushToken, bundleId: bundleId, liveActivityColor: '#${settings.liveActivityColor.toHexString().substring(2)}', @@ -383,6 +383,7 @@ class LiveCardProvider extends ChangeNotifier { nextLesson!.start.difference(now).inMinutes > 60) { debugPrint("Több, mint 1 óra van az első óráig. Befejezés..."); PlatformChannel.endLiveActivity(); + serverSync.unregister(); hasActivityStarted = false; } else if (hasActivityStarted && !hasDayEnd && @@ -390,6 +391,7 @@ class LiveCardProvider extends ChangeNotifier { now.isAfter(prevLesson!.end)) { debugPrint("Az utolsó óra véget ért. Befejezés..."); PlatformChannel.endLiveActivity(); + serverSync.unregister(); hasDayEnd = true; hasActivityStarted = false; } @@ -404,7 +406,7 @@ class LiveCardProvider extends ChangeNotifier { final deviceId = result['deviceId'] ?? ''; final bundleId = result['bundleId'] ?? ''; if (pushToken.isNotEmpty && deviceId.isNotEmpty) { - await _serverSync.registerAndSync( + await serverSync.registerAndSync( deviceId: deviceId, pushToken: pushToken, bundleId: bundleId, diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index 0963777e..a1274b08 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -123,6 +123,27 @@ class ServerSyncProvider { } } + Future unregister() async { + if (_deviceId == null) return; + try { + final client = HttpClient(); + final uri = Uri.parse('$_baseUrl/unregister'); + final request = await client.postUrl(uri); + request.headers.contentType = ContentType.json; + request.write(jsonEncode({'device_id': _deviceId})); + final response = + await request.close().timeout(const Duration(seconds: 10)); + if (response.statusCode == 200) { + debugPrint('ServerSync: schedule törölve (unregister)'); + } else { + debugPrint('ServerSync unregister hiba: ${response.statusCode}'); + } + client.close(); + } catch (e) { + debugPrint('ServerSync unregister kivétel: $e'); + } + } + List _filterLessons(List lessons) { return lessons .where((l) => diff --git a/refilc/lib/api/providers/sync.dart b/refilc/lib/api/providers/sync.dart index 9857ebf0..eb310a9a 100644 --- a/refilc/lib/api/providers/sync.dart +++ b/refilc/lib/api/providers/sync.dart @@ -153,6 +153,7 @@ Future syncAll(BuildContext context) async { if (Platform.isIOS && LiveCardProvider.hasActivityStarted == true) { PlatformChannel.endLiveActivity(); + LiveCardProvider.serverSync.unregister(); LiveCardProvider.hasActivityStarted = false; } diff --git a/refilc/lib/helpers/live_activity_helper.dart b/refilc/lib/helpers/live_activity_helper.dart index 69a26bce..983a9af5 100644 --- a/refilc/lib/helpers/live_activity_helper.dart +++ b/refilc/lib/helpers/live_activity_helper.dart @@ -10,6 +10,7 @@ class LiveActivityHelper { await PlatformChannel.updateLiveActivity(LiveCardProvider.LAData); } else { await PlatformChannel.endLiveActivity(); + LiveCardProvider.serverSync.unregister(); } } } \ No newline at end of file From 340d9d1d8e9393dbb15fd0f17f5000a31c709c09 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 10:21:40 +0100 Subject: [PATCH 11/59] Implement Live Activity dismissal handling and server unregistration --- refilc/ios/Runner/AppDelegate.swift | 9 +++++++++ refilc/ios/livecard/LiveActivityManager.swift | 19 +++++++++++++++++++ .../lib/api/providers/live_card_provider.dart | 7 +++++++ .../liveactivity/platform_channel.dart | 11 ++++++++--- 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index 73e28abe..e4b62cd3 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -32,6 +32,15 @@ import Security self?.handleMethodCall(call, result: result) }) + // Activity dismiss figyelése: ha a user swipe-olja, értesítjük Flutter-t + NotificationCenter.default.addObserver( + forName: NSNotification.Name("LiveActivityDismissed"), + object: nil, + queue: .main + ) { [weak self] _ in + self?.methodChannel?.invokeMethod("liveActivityDismissed", arguments: nil) + } + // Token rotation figyelése: ha az APNs új tokent ad, értesítjük Flutter-t tokenRotationObserver = NotificationCenter.default.addObserver( forName: NSNotification.Name("LiveActivityTokenUpdated"), diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 61667fb9..5227cd34 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -59,6 +59,9 @@ final class LiveActivityManager { activityID = activity.id print("Live Activity létrehozva. Azonosító: \(activity.id)") + // Dismiss/end figyelése háttérben + Task { await monitorActivityState(activity: activity) } + // Az APNs token aszinkron érkezik – megvárjuk az elsőt for await tokenData in activity.pushTokenUpdates { let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() @@ -76,6 +79,22 @@ final class LiveActivityManager { } } + /// Activity state figyelése: ha a user dismiss-eli vagy véget ér, értesítjük a Flutter-t. + private class func monitorActivityState(activity: Activity) async { + for await state in activity.activityStateUpdates { + if state == .dismissed || state == .ended { + print("Live Activity dismissed/ended by user or system") + activityID = nil + activityPushToken = nil + NotificationCenter.default.post( + name: NSNotification.Name("LiveActivityDismissed"), + object: nil + ) + break + } + } + } + /// Token rotation figyelése: ha az APNs új tokent ad ki, értesítjük a Flutter oldalt. private class func monitorTokenRotation(activity: Activity) async { var isFirst = true diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index b16b7c81..7a2c6123 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -71,6 +71,13 @@ class LiveCardProvider extends ChangeNotifier { ); }; + // Ha a user dismiss-eli a Live Activity-t (swipe), értesítjük a szervert + PlatformChannel.onActivityDismissed = () { + debugPrint("Live Activity dismissed - unregistering from server"); + serverSync.unregister(); + hasActivityStarted = false; + }; + update(); } diff --git a/refilc/lib/api/providers/liveactivity/platform_channel.dart b/refilc/lib/api/providers/liveactivity/platform_channel.dart index 24ef1901..78f8545f 100644 --- a/refilc/lib/api/providers/liveactivity/platform_channel.dart +++ b/refilc/lib/api/providers/liveactivity/platform_channel.dart @@ -7,10 +7,12 @@ class PlatformChannel { static const MethodChannel _channel = MethodChannel('app.firka/liveactivity'); /// Callback token rotation esetén (iOS APNs új tokent ad ki). - /// A szerver szinkronizálásért felelős kód regisztrálhat ide. static void Function(String pushToken, String deviceId, String bundleId)? onTokenUpdated; - static void _setupTokenRotationListener() { + /// Callback ha a user dismiss-eli a Live Activity-t (swipe left). + static void Function()? onActivityDismissed; + + static void _setupMethodCallListener() { _channel.setMethodCallHandler((call) async { if (call.method == 'liveActivityTokenUpdated') { final args = call.arguments as Map?; @@ -21,6 +23,9 @@ class PlatformChannel { args['bundleId'] as String? ?? '', ); } + } else if (call.method == 'liveActivityDismissed') { + debugPrint("Live Activity dismissed by user"); + onActivityDismissed?.call(); } }); } @@ -30,7 +35,7 @@ class PlatformChannel { static Future?> createLiveActivity( Map activityData) async { if (Platform.isIOS) { - _setupTokenRotationListener(); + _setupMethodCallListener(); try { debugPrint("creating live activity..."); final result = await _channel.invokeMethod( From 70a1c99ea7d31c69554c1fe6d630a1376e32ee77 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 10:33:42 +0100 Subject: [PATCH 12/59] Refactor HTTP requests in ServerSyncProvider to use http package --- .../liveactivity/server_sync_provider.dart | 67 ++++++++----------- 1 file changed, 29 insertions(+), 38 deletions(-) diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index a1274b08..f5e616c6 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -1,6 +1,6 @@ import 'dart:convert'; -import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; import 'package:refilc/helpers/subject.dart'; import 'package:refilc/utils/format.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; @@ -54,26 +54,23 @@ class ServerSyncProvider { required String liveActivityColor, }) async { try { - final client = HttpClient(); - final uri = Uri.parse('$_baseUrl/register'); - final request = await client.postUrl(uri); - request.headers.contentType = ContentType.json; - request.write(jsonEncode({ - 'device_id': deviceId, - 'apns_token': pushToken, - 'bundle_id': bundleId, - 'settings': { - 'live_activity_color': liveActivityColor, - }, - })); - final response = - await request.close().timeout(const Duration(seconds: 10)); + final response = await http.post( + Uri.parse('$_baseUrl/register'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({ + 'device_id': deviceId, + 'apns_token': pushToken, + 'bundle_id': bundleId, + 'settings': { + 'live_activity_color': liveActivityColor, + }, + }), + ).timeout(const Duration(seconds: 10)); if (response.statusCode != 200 && response.statusCode != 201) { - debugPrint('ServerSync register hiba: ${response.statusCode}'); + debugPrint('ServerSync register hiba: ${response.statusCode} ${response.body}'); } else { debugPrint('ServerSync: device regisztrálva'); } - client.close(); } catch (e) { debugPrint('ServerSync register kivétel: $e'); } @@ -101,23 +98,20 @@ class ServerSyncProvider { }) .toList(); - final client = HttpClient(); - final uri = Uri.parse('$_baseUrl/schedule'); - final request = await client.postUrl(uri); - request.headers.contentType = ContentType.json; - request.write(jsonEncode({ - 'device_id': deviceId, - 'date': dateStr, - 'lessons': lessonsJson, - })); - final response = - await request.close().timeout(const Duration(seconds: 10)); + final response = await http.post( + Uri.parse('$_baseUrl/schedule'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({ + 'device_id': deviceId, + 'date': dateStr, + 'lessons': lessonsJson, + }), + ).timeout(const Duration(seconds: 10)); if (response.statusCode != 200 && response.statusCode != 201) { - debugPrint('ServerSync schedule hiba: ${response.statusCode}'); + debugPrint('ServerSync schedule hiba: ${response.statusCode} ${response.body}'); } else { debugPrint('ServerSync: ${lessons.length} óra feltöltve ($dateStr)'); } - client.close(); } catch (e) { debugPrint('ServerSync schedule kivétel: $e'); } @@ -126,19 +120,16 @@ class ServerSyncProvider { Future unregister() async { if (_deviceId == null) return; try { - final client = HttpClient(); - final uri = Uri.parse('$_baseUrl/unregister'); - final request = await client.postUrl(uri); - request.headers.contentType = ContentType.json; - request.write(jsonEncode({'device_id': _deviceId})); - final response = - await request.close().timeout(const Duration(seconds: 10)); + final response = await http.post( + Uri.parse('$_baseUrl/unregister'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'device_id': _deviceId}), + ).timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { debugPrint('ServerSync: schedule törölve (unregister)'); } else { debugPrint('ServerSync unregister hiba: ${response.statusCode}'); } - client.close(); } catch (e) { debugPrint('ServerSync unregister kivétel: $e'); } From b8ae1c7c6938fb1de3a6ae0f3cc1f305e7b8ecc8 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 10:58:50 +0100 Subject: [PATCH 13/59] Remove demo login text from LoginScreen widget --- refilc_mobile_ui/lib/screens/login/login_screen.dart | 8 -------- 1 file changed, 8 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/login_screen.dart b/refilc_mobile_ui/lib/screens/login/login_screen.dart index 94336a44..6c95e732 100644 --- a/refilc_mobile_ui/lib/screens/login/login_screen.dart +++ b/refilc_mobile_ui/lib/screens/login/login_screen.dart @@ -392,14 +392,6 @@ class LoginScreenState extends State { setSystemChrome(context); Navigator.of(context).pushReplacementNamed('login_to_navigation'); }, - child: Text( - 'demo_login'.i18n, - style: TextStyle( - color: AppColors.of(context).loginSecondary, - fontWeight: FontWeight.w500, - fontSize: 14.0, - ), - ), ), const SizedBox(height: 12), // privacy policy From d8ae92e0f7bed092867b1342763d31af8fae0763 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 11:09:15 +0100 Subject: [PATCH 14/59] Update aps-environment to production in entitlements files --- refilc/ios/Runner/Runner.entitlements | 2 +- refilc/ios/livecard/livecard.entitlements | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/refilc/ios/Runner/Runner.entitlements b/refilc/ios/Runner/Runner.entitlements index 52268ce5..cfc0af95 100644 --- a/refilc/ios/Runner/Runner.entitlements +++ b/refilc/ios/Runner/Runner.entitlements @@ -3,7 +3,7 @@ aps-environment - development + production com.apple.security.application-groups group.firkaa.legacy diff --git a/refilc/ios/livecard/livecard.entitlements b/refilc/ios/livecard/livecard.entitlements index 52268ce5..cfc0af95 100644 --- a/refilc/ios/livecard/livecard.entitlements +++ b/refilc/ios/livecard/livecard.entitlements @@ -3,7 +3,7 @@ aps-environment - development + production com.apple.security.application-groups group.firkaa.legacy From e857f1007304f9528eb793bccd991390c1fe748f Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 11:12:07 +0100 Subject: [PATCH 15/59] Add user dismissal handling and clean up previous activities in LiveActivityManager --- refilc/ios/livecard/LiveActivityManager.swift | 5 ++ refilc/ios/livecard/livecard.swift | 78 +++++++++---------- .../lib/api/providers/live_card_provider.dart | 5 ++ 3 files changed, 46 insertions(+), 42 deletions(-) diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 5227cd34..eed6d8e1 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -29,6 +29,11 @@ final class LiveActivityManager { /// Létrehozza a Live Activity-t pushType: .token-nel, majd visszaadja az APNs push tokent. class func create(completion: @escaping (String?) -> Void) { Task { + // Előző activity-k eltakarítása, hogy ne legyen dupla + for activity in Activity.activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + do { let contentState = LiveActivitiesAppAttributes.ContentState( color: globalLessonData.color, diff --git a/refilc/ios/livecard/livecard.swift b/refilc/ios/livecard/livecard.swift index 55f431e8..799c623a 100644 --- a/refilc/ios/livecard/livecard.swift +++ b/refilc/ios/livecard/livecard.swift @@ -52,71 +52,65 @@ struct LockScreenLiveActivityView: View { let context: ActivityViewContext var body: some View { - HStack(alignment: .center) { + HStack(alignment: .center, spacing: 0) { // Ikon Image(systemName: context.state.icon) .resizable() .aspectRatio(contentMode: .fit) - .frame(width: CGFloat(30), height: CGFloat(30)) - .padding(.leading, CGFloat(24)) + .frame(width: 28, height: 28) + .padding(.leading, 16) - VStack(alignment: .center) { + VStack(alignment: .leading, spacing: 3) { // Jelenlegi óra - VStack { - if(context.state.title.contains("Az első órádig")) { + if context.state.title.contains("Az első órádig") { Text(context.state.title) - .font(.system(size: 15)) - .bold() - .multilineTextAlignment(.center) - } else if(context.state.title == "Szünet") { + .font(.system(size: 14, weight: .semibold)) + .lineLimit(2) + } else if context.state.title == "Szünet" { Text(context.state.title) - .font(.body) - .bold() - .padding(.trailing, 90) - } else { - MultilineTextView(text: "\(context.state.index) \(context.state.title) - \(context.state.subtitle)", limit: 25) - .font(.body) - .bold() - .multilineTextAlignment(.center) - } + .font(.system(size: 15, weight: .bold)) + } else { + Text("\(context.state.index) \(context.state.title) - \(context.state.subtitle)") + .font(.system(size: 15, weight: .bold)) + .lineLimit(2) } // Leírás - if (context.state.description != "") { - Text(context.state.description) - .font(.subheadline) + if !context.state.description.isEmpty { + Text(context.state.description) + .font(.system(size: 13)) + .lineLimit(2) + .foregroundStyle(.secondary) } // Következő óra - if(context.state.nextSubject != "" && context.state.nextRoom != "") { - HStack { - Image(systemName: "arrow.right") - .resizable() - .aspectRatio(contentMode: .fit) - .frame(width: CGFloat(8), height: CGFloat(8)) + if !context.state.nextSubject.isEmpty && !context.state.nextRoom.isEmpty { + HStack(spacing: 4) { + Image(systemName: "arrow.right") + .font(.system(size: 8, weight: .semibold)) + .foregroundStyle(.secondary) + Text("\(context.state.nextSubject) - \(context.state.nextRoom)") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } + } else { + Text("Ez az utolsó óra! Kitartást!") + .font(.system(size: 13)) .foregroundStyle(.secondary) - Text("\(context.state.nextSubject) - \(context.state.nextRoom)") - .font(.caption) } - .multilineTextAlignment(.center) - } else { - Spacer(minLength: 5) - Text("Ez az utolsó óra! Kitartást!") - .font(.system(size: 15)) - } - } - .padding(15) + .padding(.horizontal, 12) + .padding(.vertical, 14) - Spacer() + Spacer(minLength: 4) // Visszaszámláló Text(timerInterval: context.state.date, countsDown: true) - .multilineTextAlignment(.center) - .frame(width: 85) + .multilineTextAlignment(.trailing) + .frame(width: 75) .font(.title2) .monospacedDigit() - .padding(.trailing) + .padding(.trailing, 16) } // .activityBackgroundTint( // context.state.color != "#676767" diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 7a2c6123..3fee8ffc 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -34,6 +34,7 @@ class LiveCardProvider extends ChangeNotifier { // new variables static bool hasActivityStarted = false; static bool hasDayEnd = false; + static bool hasUserDismissed = false; static DateTime? storeFirstRunDate; static bool hasActivitySettingsChanged = false; // ignore: non_constant_identifier_names @@ -76,6 +77,7 @@ class LiveCardProvider extends ChangeNotifier { debugPrint("Live Activity dismissed - unregistering from server"); serverSync.unregister(); hasActivityStarted = false; + hasUserDismissed = true; }; update(); @@ -337,6 +339,7 @@ class LiveCardProvider extends ChangeNotifier { //CREATE if (!hasActivityStarted && + !hasUserDismissed && nextLesson != null && nextLesson!.start.difference(now).inMinutes <= 60 && (currentState == LiveCardState.morning || @@ -347,6 +350,7 @@ class LiveCardProvider extends ChangeNotifier { hasActivityStarted = true; _createAndSync(); } else if (!hasActivityStarted && + !hasUserDismissed && ((currentState == LiveCardState.duringLesson && currentLesson != null) || currentState == LiveCardState.duringBreak)) { @@ -401,6 +405,7 @@ class LiveCardProvider extends ChangeNotifier { serverSync.unregister(); hasDayEnd = true; hasActivityStarted = false; + hasUserDismissed = false; } LAData = toMap(); notifyListeners(); From fe33bb2db0c09ca7f035c9d331d1b3adb8c30cfe Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 11:14:07 +0100 Subject: [PATCH 16/59] Enhance Live Activity dismissal handling by passing deviceId and updating server unregistration logic --- refilc/ios/Runner/AppDelegate.swift | 5 ++++- refilc/ios/livecard/LiveActivityManager.swift | 2 ++ refilc/lib/api/providers/live_card_provider.dart | 4 ++-- .../api/providers/liveactivity/platform_channel.dart | 8 +++++--- .../providers/liveactivity/server_sync_provider.dart | 10 ++++++++-- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index e4b62cd3..5f4a9067 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -38,7 +38,10 @@ import Security object: nil, queue: .main ) { [weak self] _ in - self?.methodChannel?.invokeMethod("liveActivityDismissed", arguments: nil) + let deviceId = self?.getOrCreateDeviceId() ?? "" + self?.methodChannel?.invokeMethod("liveActivityDismissed", arguments: [ + "deviceId": deviceId, + ]) } // Token rotation figyelése: ha az APNs új tokent ad, értesítjük Flutter-t diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index eed6d8e1..0cd0f463 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -95,6 +95,8 @@ final class LiveActivityManager { name: NSNotification.Name("LiveActivityDismissed"), object: nil ) + // Activity formálisan is leállítjuk ha még fut + await activity.end(nil, dismissalPolicy: .immediate) break } } diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 3fee8ffc..d53bdebc 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -73,9 +73,9 @@ class LiveCardProvider extends ChangeNotifier { }; // Ha a user dismiss-eli a Live Activity-t (swipe), értesítjük a szervert - PlatformChannel.onActivityDismissed = () { + PlatformChannel.onActivityDismissed = (deviceId) { debugPrint("Live Activity dismissed - unregistering from server"); - serverSync.unregister(); + serverSync.forceUnregister(deviceId); hasActivityStarted = false; hasUserDismissed = true; }; diff --git a/refilc/lib/api/providers/liveactivity/platform_channel.dart b/refilc/lib/api/providers/liveactivity/platform_channel.dart index 78f8545f..04b85773 100644 --- a/refilc/lib/api/providers/liveactivity/platform_channel.dart +++ b/refilc/lib/api/providers/liveactivity/platform_channel.dart @@ -10,7 +10,7 @@ class PlatformChannel { static void Function(String pushToken, String deviceId, String bundleId)? onTokenUpdated; /// Callback ha a user dismiss-eli a Live Activity-t (swipe left). - static void Function()? onActivityDismissed; + static void Function(String deviceId)? onActivityDismissed; static void _setupMethodCallListener() { _channel.setMethodCallHandler((call) async { @@ -24,8 +24,10 @@ class PlatformChannel { ); } } else if (call.method == 'liveActivityDismissed') { - debugPrint("Live Activity dismissed by user"); - onActivityDismissed?.call(); + final args = call.arguments as Map?; + final deviceId = args?['deviceId'] as String? ?? ''; + debugPrint("Live Activity dismissed by user (device: $deviceId)"); + onActivityDismissed?.call(deviceId); } }); } diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index f5e616c6..bccaa42c 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -119,20 +119,26 @@ class ServerSyncProvider { Future unregister() async { if (_deviceId == null) return; + await forceUnregister(_deviceId!); + } + + /// Unregister egy adott deviceId-vel, akkor is ha a _deviceId nincs beállítva (pl. app restart után). + Future forceUnregister(String deviceId) async { try { final response = await http.post( Uri.parse('$_baseUrl/unregister'), headers: {'Content-Type': 'application/json'}, - body: jsonEncode({'device_id': _deviceId}), + body: jsonEncode({'device_id': deviceId}), ).timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { - debugPrint('ServerSync: schedule törölve (unregister)'); + debugPrint('ServerSync: device + schedule törölve (unregister)'); } else { debugPrint('ServerSync unregister hiba: ${response.statusCode}'); } } catch (e) { debugPrint('ServerSync unregister kivétel: $e'); } + _deviceId = null; } List _filterLessons(List lessons) { From 55035b535cd8ac00bee9a4f90ab929a25925bd43 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 12:28:38 +0100 Subject: [PATCH 17/59] Refactor Live Activity creation to return success status and handle push token updates asynchronously --- refilc/ios/Runner/AppDelegate.swift | 8 +--- refilc/ios/livecard/LiveActivityManager.swift | 47 +++++++++---------- .../lib/api/providers/live_card_provider.dart | 28 +++++------ .../liveactivity/platform_channel.dart | 6 +-- 4 files changed, 39 insertions(+), 50 deletions(-) diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index 5f4a9067..997e0114 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -90,15 +90,11 @@ import Security } if #available(iOS 16.2, *) { - LiveActivityManager.create { [weak self] pushToken in - guard let self = self, let token = pushToken else { - result(nil) - return - } + LiveActivityManager.create { success in let deviceId = self.getOrCreateDeviceId() let bundleId = Bundle.main.bundleIdentifier ?? "" result([ - "pushToken": token, + "success": success, "deviceId": deviceId, "bundleId": bundleId, ]) diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 0cd0f463..5719a373 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -26,8 +26,10 @@ final class LiveActivityManager { static let shared = LiveActivityManager() var currentActivity: Activity? - /// Létrehozza a Live Activity-t pushType: .token-nel, majd visszaadja az APNs push tokent. - class func create(completion: @escaping (String?) -> Void) { + /// Létrehozza a Live Activity-t pushType: .token-nel. + /// A completion azonnal meghívódik a létrehozás után (success/fail). + /// A push token később érkezik a pushTokenUpdates-en keresztül. + class func create(completion: @escaping (Bool) -> Void) { Task { // Előző activity-k eltakarítása, hogy ne legyen dupla for activity in Activity.activities { @@ -64,22 +66,28 @@ final class LiveActivityManager { activityID = activity.id print("Live Activity létrehozva. Azonosító: \(activity.id)") + // Azonnal visszatérünk — a LA látszik + completion(true) + // Dismiss/end figyelése háttérben Task { await monitorActivityState(activity: activity) } - // Az APNs token aszinkron érkezik – megvárjuk az elsőt - for await tokenData in activity.pushTokenUpdates { - let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() - activityPushToken = tokenHex - print("Live Activity push token: \(tokenHex)") - completion(tokenHex) - // Token rotation figyelése a háttérben - Task { await monitorTokenRotation(activity: activity) } - break + // Push token figyelése háttérben — az első és a rotation is + // a LiveActivityTokenUpdated notification-ön keresztül megy Flutter felé + Task { + for await tokenData in activity.pushTokenUpdates { + let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() + activityPushToken = tokenHex + print("Live Activity push token: \(tokenHex)") + NotificationCenter.default.post( + name: NSNotification.Name("LiveActivityTokenUpdated"), + object: tokenHex + ) + } } } catch { print("Hiba történt a Live Activity létrehozásakor: \(error)") - completion(nil) + completion(false) } } } @@ -103,19 +111,8 @@ final class LiveActivityManager { } /// Token rotation figyelése: ha az APNs új tokent ad ki, értesítjük a Flutter oldalt. - private class func monitorTokenRotation(activity: Activity) async { - var isFirst = true - for await tokenData in activity.pushTokenUpdates { - if isFirst { isFirst = false; continue } // Az első tokent már kezeltük - let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() - activityPushToken = tokenHex - print("Live Activity push token frissítve (rotation): \(tokenHex)") - NotificationCenter.default.post( - name: NSNotification.Name("LiveActivityTokenUpdated"), - object: tokenHex - ) - } - } + /// MEGJEGYZÉS: Már nem használjuk külön — a create() maga figyeli a pushTokenUpdates-t + /// és minden tokent (elsőt is, rotation-t is) a LiveActivityTokenUpdated notification-ön küld. class func update() { Task { diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index d53bdebc..d5d6f0e0 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -63,12 +63,15 @@ class LiveCardProvider extends ChangeNotifier { ? Duration(seconds: settings.bellDelay) : Duration.zero; - // Token rotation figyelése: ha iOS új APNs tokent ad ki, szinkronizáljuk a szerverrel + // Token figyelése: amikor az APNs tokent ad (első vagy rotation), regisztráljuk a szerverrel PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) { - serverSync.refreshToken( + debugPrint("Push token érkezett: $pushToken"); + serverSync.registerAndSync( + deviceId: deviceId, pushToken: pushToken, bundleId: bundleId, liveActivityColor: '#${settings.liveActivityColor.toHexString().substring(2)}', + todayLessons: _today(_timetable), ); }; @@ -413,20 +416,13 @@ class LiveCardProvider extends ChangeNotifier { Future _createAndSync() async { final result = await PlatformChannel.createLiveActivity(toMap()); - if (result != null) { - final pushToken = result['pushToken'] ?? ''; - final deviceId = result['deviceId'] ?? ''; - final bundleId = result['bundleId'] ?? ''; - if (pushToken.isNotEmpty && deviceId.isNotEmpty) { - await serverSync.registerAndSync( - deviceId: deviceId, - pushToken: pushToken, - bundleId: bundleId, - liveActivityColor: - '#${_settings.liveActivityColor.toHexString().substring(2)}', - todayLessons: _today(_timetable), - ); - } + if (result != null && result['success'] == 'true') { + debugPrint("Live Activity létrehozva, várunk a push tokenre..."); + // A regisztráció az onTokenUpdated callback-ben történik, + // amikor az APNs elküldi a push tokent. + } else { + debugPrint("Live Activity létrehozás sikertelen"); + hasActivityStarted = false; } } diff --git a/refilc/lib/api/providers/liveactivity/platform_channel.dart b/refilc/lib/api/providers/liveactivity/platform_channel.dart index 04b85773..bb2ccad5 100644 --- a/refilc/lib/api/providers/liveactivity/platform_channel.dart +++ b/refilc/lib/api/providers/liveactivity/platform_channel.dart @@ -32,8 +32,8 @@ class PlatformChannel { }); } - /// Létrehozza a Live Activity-t és visszaadja az APNs push tokent, - /// a device ID-t (Keychain UUID) és a bundle ID-t. + /// Létrehozza a Live Activity-t. Azonnal visszatér deviceId/bundleId-vel. + /// A push token később érkezik az onTokenUpdated callback-en. static Future?> createLiveActivity( Map activityData) async { if (Platform.isIOS) { @@ -44,7 +44,7 @@ class PlatformChannel { 'createLiveActivity', activityData); if (result == null) return null; return { - 'pushToken': result['pushToken'] as String? ?? '', + 'success': (result['success'] as bool? ?? false).toString(), 'deviceId': result['deviceId'] as String? ?? '', 'bundleId': result['bundleId'] as String? ?? '', }; From 68c76afddeada0be59cbaf6da32aa813a01b79bc Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 12:51:10 +0100 Subject: [PATCH 18/59] Revert version number to 5.1.2+0 in pubspec.yaml --- refilc/pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/refilc/pubspec.yaml b/refilc/pubspec.yaml index 9da411f4..53e4db29 100644 --- a/refilc/pubspec.yaml +++ b/refilc/pubspec.yaml @@ -3,7 +3,7 @@ description: "Egy nem hivatalos e-KRÉTA kliens, diákoktól diákoknak." homepage: https://refilc.hu publish_to: "none" -version: 5.1.5+290 +version: 5.1.2+0 environment: sdk: ^3.6.0 From 30d75d6a60d927ac37ecb27789c89fa6162e74e6 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 13:12:35 +0100 Subject: [PATCH 19/59] Update Flutter build name to 5.1.2 and reset build number to 0 in project.pbxproj --- refilc/ios/Runner.xcodeproj/project.pbxproj | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/refilc/ios/Runner.xcodeproj/project.pbxproj b/refilc/ios/Runner.xcodeproj/project.pbxproj index b6d9f820..0ddff0df 100644 --- a/refilc/ios/Runner.xcodeproj/project.pbxproj +++ b/refilc/ios/Runner.xcodeproj/project.pbxproj @@ -520,8 +520,8 @@ CURRENT_PROJECT_VERSION = 283; DEVELOPMENT_TEAM = R9PZGUCNJ3; ENABLE_BITCODE = NO; - FLUTTER_BUILD_NAME = 5.1.1; - FLUTTER_BUILD_NUMBER = 283; + FLUTTER_BUILD_NAME = 5.1.2; + FLUTTER_BUILD_NUMBER = 0; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "Firka Legacy"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; @@ -793,8 +793,8 @@ CURRENT_PROJECT_VERSION = 283; DEVELOPMENT_TEAM = R9PZGUCNJ3; ENABLE_BITCODE = NO; - FLUTTER_BUILD_NAME = 5.1.1; - FLUTTER_BUILD_NUMBER = 283; + FLUTTER_BUILD_NAME = 5.1.2; + FLUTTER_BUILD_NUMBER = 0; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "Firka Legacy"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; @@ -827,8 +827,8 @@ CURRENT_PROJECT_VERSION = 283; DEVELOPMENT_TEAM = R9PZGUCNJ3; ENABLE_BITCODE = NO; - FLUTTER_BUILD_NAME = 5.1.1; - FLUTTER_BUILD_NUMBER = 283; + FLUTTER_BUILD_NAME = 5.1.2; + FLUTTER_BUILD_NUMBER = 0; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "Firka Legacy"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; From 7720cbd07da8035a6009b6803e4b745c494a2201 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 14:05:49 +0100 Subject: [PATCH 20/59] Add developer settings for fake lessons and update localization - Introduced `dev_live_fake_lessons` setting in the database schema. - Updated `SettingsProvider` to manage the new `devLiveFakeLessons` property. - Enhanced `LiveCardProvider` to generate fake lessons based on the new setting. - Added UI toggle for fake lessons in the settings screen with appropriate localization. --- .../lib/api/providers/live_card_provider.dart | 63 +++++++++++++++++-- refilc/lib/database/init.dart | 1 + refilc/lib/models/settings.dart | 12 ++++ .../lib/screens/settings/settings_screen.dart | 39 +++++++++++- .../settings/settings_screen.i18n.dart | 6 ++ 5 files changed, 113 insertions(+), 8 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index d5d6f0e0..6e674858 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -8,6 +8,9 @@ import 'package:refilc/helpers/subject.dart'; import 'package:refilc/models/settings.dart'; import 'package:refilc/ui/flutter_colorpicker/utils.dart'; import 'package:refilc_kreta_api/models/lesson.dart'; +import 'package:refilc_kreta_api/models/subject.dart'; +import 'package:refilc_kreta_api/models/category.dart' as kreta; +import 'package:refilc_kreta_api/models/teacher.dart'; import 'package:refilc_kreta_api/models/week.dart'; import 'package:refilc/utils/format.dart'; import 'package:refilc_kreta_api/providers/timetable_provider.dart'; @@ -318,7 +321,8 @@ class LiveCardProvider extends ChangeNotifier { } if (now.isBefore(DateTime(now.year, DateTime.august, 31)) && - now.isAfter(DateTime(now.year, DateTime.june, 14))) { + now.isAfter(DateTime(now.year, DateTime.june, 14)) && + !(_settings.developerMode && _settings.devLiveFakeLessons)) { currentState = LiveCardState.summary; } else if (currentLesson != null) { currentState = LiveCardState.duringLesson; @@ -329,7 +333,8 @@ class LiveCardProvider extends ChangeNotifier { } else if (now.hour >= 20) { currentState = LiveCardState.night; } else if (now.hour >= 5 && now.hour <= 10) { - if (nextLesson == null || now.weekday == 6 || now.weekday == 7) { + if (nextLesson == null || ((now.weekday == 6 || now.weekday == 7) && + !(_settings.developerMode && _settings.devLiveFakeLessons))) { currentState = LiveCardState.empty; } else { currentState = LiveCardState.morning; @@ -432,7 +437,55 @@ class LiveCardProvider extends ChangeNotifier { bool _sameDate(DateTime a, DateTime b) => (a.year == b.year && a.month == b.month && a.day == b.day); - List _today(TimetableProvider p) => (p.getWeek(Week.current()) ?? []) - .where((l) => _sameDate(l.date, _now())) - .toList(); + List _today(TimetableProvider p) { + final real = (p.getWeek(Week.current()) ?? []) + .where((l) => _sameDate(l.date, _now())) + .toList(); + if (real.isNotEmpty || !_settings.developerMode || !_settings.devLiveFakeLessons) { + return real; + } + return _generateFakeLessons(); + } + + /// Generál fake órákat a jelenlegi idő köré, hogy a Live Activity tesztelhető legyen. + static List _generateFakeLessons() { + final now = _now(); + // Az első óra 10 perccel ezelőtt kezdődött (vagy ha nincs, 5 perc múlva) + final baseStart = now.subtract(const Duration(minutes: 10)); + + const subjects = [ + ('Matematika', 'fake_math', 'Egyenletek'), + ('Magyar', 'fake_hun', 'Nyelvtan'), + ('Angol', 'fake_eng', 'Writing'), + ('Fizika', 'fake_phys', 'Mechanika'), + ('Történelem', 'fake_hist', 'XX. század'), + ('Informatika', 'fake_info', 'Programozás'), + ]; + + final lessons = []; + for (int i = 0; i < 6; i++) { + final start = baseStart.add(Duration(minutes: i * 55)); + final end = start.add(const Duration(minutes: 45)); + final (name, id, desc) = subjects[i]; + lessons.add(Lesson( + id: 'fake_lesson_$i', + date: DateTime(now.year, now.month, now.day), + subject: GradeSubject( + id: id, + category: kreta.Category(id: '', name: ''), + name: name, + ), + lessonIndex: '${i + 1}', + teacher: Teacher(id: 'fake_teacher', name: 'Teszt Tanár'), + start: start, + end: end, + homeworkId: '', + description: desc, + room: '${(i + 1) * 100 + 1}', + groupName: '', + name: name, + )); + } + return lessons; + } } diff --git a/refilc/lib/database/init.dart b/refilc/lib/database/init.dart index 6e7fad2e..0f68e20e 100644 --- a/refilc/lib/database/init.dart +++ b/refilc/lib/database/init.dart @@ -14,6 +14,7 @@ const settingsDB = DatabaseStruct("settings", { "language": String, "start_page": int, "rounding": int, "theme": int, "accent_color": int, "news": int, "seen_news": String, "developer_mode": int, + "dev_live_fake_lessons": int, "update_channel": int, "config": String, "custom_accent_color": int, "custom_background_color": int, "custom_highlight_color": int, "custom_text_color": int, // new txt color diff --git a/refilc/lib/models/settings.dart b/refilc/lib/models/settings.dart index e6cf174e..f4c4e3a1 100644 --- a/refilc/lib/models/settings.dart +++ b/refilc/lib/models/settings.dart @@ -54,6 +54,7 @@ class SettingsProvider extends ChangeNotifier { // minutes: times 15 int _notificationPollInterval; bool _developerMode; + bool _devLiveFakeLessons; VibrationStrength _vibrate; bool _abWeeks; bool _swapABweeks; @@ -134,6 +135,7 @@ class SettingsProvider extends ChangeNotifier { required bool notificationsLessonsEnabled, required int notificationsBitfield, required bool developerMode, + required bool devLiveFakeLessons, required int notificationPollInterval, required VibrationStrength vibrate, required bool abWeeks, @@ -209,6 +211,7 @@ class SettingsProvider extends ChangeNotifier { _notificationsLessonsEnabled = notificationsLessonsEnabled, _notificationsBitfield = notificationsBitfield, _developerMode = developerMode, + _devLiveFakeLessons = devLiveFakeLessons, _notificationPollInterval = notificationPollInterval, _vibrate = vibrate, _abWeeks = abWeeks, @@ -303,6 +306,7 @@ class SettingsProvider extends ChangeNotifier { notificationsBitfield: map["notifications_bitfield"], notificationPollInterval: map["notification_poll_interval"], developerMode: map["developer_mode"] == 1, + devLiveFakeLessons: map["dev_live_fake_lessons"] == 1, vibrate: VibrationStrength.values[map["vibration_strength"]], abWeeks: map["ab_weeks"] == 1, swapABweeks: map["swap_ab_weeks"] == 1, @@ -381,6 +385,7 @@ class SettingsProvider extends ChangeNotifier { "notifications_lessons": _notificationsLessonsEnabled ? 1 : 0, "notifications_bitfield": _notificationsBitfield, "developer_mode": _developerMode ? 1 : 0, + "dev_live_fake_lessons": _devLiveFakeLessons ? 1 : 0, "grade_color1": _gradeColors[0].value, "grade_color2": _gradeColors[1].value, "grade_color3": _gradeColors[2].value, @@ -471,6 +476,7 @@ class SettingsProvider extends ChangeNotifier { notificationsLessonsEnabled: true, notificationsBitfield: 255, developerMode: true, + devLiveFakeLessons: false, notificationPollInterval: 1, vibrate: VibrationStrength.medium, abWeeks: false, @@ -549,6 +555,7 @@ class SettingsProvider extends ChangeNotifier { bool get notificationsLessonsEnabled => _notificationsLessonsEnabled; int get notificationsBitfield => _notificationsBitfield; bool get developerMode => _developerMode; + bool get devLiveFakeLessons => _devLiveFakeLessons; int get notificationPollInterval => _notificationPollInterval; VibrationStrength get vibrate => _vibrate; bool get abWeeks => _abWeeks; @@ -626,6 +633,7 @@ class SettingsProvider extends ChangeNotifier { bool? notificationsLessonsEnabled, int? notificationsBitfield, bool? developerMode, + bool? devLiveFakeLessons, int? notificationPollInterval, VibrationStrength? vibrate, bool? abWeeks, @@ -727,6 +735,9 @@ class SettingsProvider extends ChangeNotifier { if (developerMode != null && developerMode != _developerMode) { _developerMode = developerMode; } + if (devLiveFakeLessons != null && devLiveFakeLessons != _devLiveFakeLessons) { + _devLiveFakeLessons = devLiveFakeLessons; + } if (notificationPollInterval != null && notificationPollInterval != _notificationPollInterval) { _notificationPollInterval = notificationPollInterval; @@ -930,6 +941,7 @@ class SettingsProvider extends ChangeNotifier { notificationsBitfield: map["notifications_bitfield"], notificationPollInterval: map["notification_poll_interval"], developerMode: map["developer_mode"] == 1, + devLiveFakeLessons: map["dev_live_fake_lessons"] == 1, vibrate: VibrationStrength.values[map["vibration_strength"] ?? _vibrate.index], abWeeks: map["ab_weeks"] == 1, diff --git a/refilc_mobile_ui/lib/screens/settings/settings_screen.dart b/refilc_mobile_ui/lib/screens/settings/settings_screen.dart index 68b6f391..96d6c7de 100644 --- a/refilc_mobile_ui/lib/screens/settings/settings_screen.dart +++ b/refilc_mobile_ui/lib/screens/settings/settings_screen.dart @@ -19,7 +19,9 @@ // ignore_for_file: no_leading_underscores_for_local_identifiers, use_build_context_synchronously, deprecated_member_use import 'dart:convert'; +import 'dart:io'; +import 'package:refilc/api/providers/live_card_provider.dart'; import 'package:refilc/api/providers/update_provider.dart'; import 'package:refilc_kreta_api/providers/absence_provider.dart'; import 'package:refilc_kreta_api/providers/event_provider.dart'; @@ -1083,8 +1085,9 @@ class SettingsScreenState extends State PanelButton( borderRadius: BorderRadius.vertical( top: const Radius.circular(4.0), - bottom: Provider.of(context, listen: false) - .hasPremium + bottom: (Platform.isIOS || + Provider.of(context, listen: false) + .hasPremium) ? const Radius.circular(4.0) : const Radius.circular(12.0), ), @@ -1097,7 +1100,37 @@ class SettingsScreenState extends State onPressed: () => Clipboard.setData(ClipboardData( text: Provider.of(context, listen: false) .accessToken!)), - ) + ), + if (Platform.isIOS) + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: + const EdgeInsets.only(left: 12.0, right: 4.0), + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical( + top: Radius.circular(4.0), + bottom: Radius.circular(12.0))), + title: Text("dev_fake_lessons".i18n, + style: const TextStyle(fontWeight: FontWeight.w500)), + subtitle: Text("dev_fake_lessons_desc".i18n, + style: TextStyle( + fontSize: 12.0, + color: AppColors.of(context).text.withOpacity(0.65), + )), + onChanged: (v) { + settings.update(devLiveFakeLessons: v); + if (v) { + // Reset Live Activity state to force recreation + LiveCardProvider.hasActivityStarted = false; + LiveCardProvider.hasDayEnd = false; + LiveCardProvider.hasUserDismissed = false; + } + }, + value: settings.devLiveFakeLessons, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), ], ), diff --git a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart index 900f6a7c..9d45b3e2 100644 --- a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart +++ b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart @@ -71,6 +71,8 @@ extension SettingsLocalization on String { "devactivated": "Developer Mode successfully activated.", "devsettings": "Developer Settings", "devmode": "Developer Mode", + "dev_fake_lessons": "Fake Live Activity Lessons", + "dev_fake_lessons_desc": "Generate test lessons around current time for Live Activity testing", "copy_jwt": "Copy JWT", "welcome_msg": "Welcome Message", "default": "Dynamic", @@ -199,6 +201,8 @@ extension SettingsLocalization on String { "devactivated": "Fejlesztői mód sikeresen aktiválva.", "devsettings": "Fejlesztői Beállítások", "devmode": "Fejlesztői mód", + "dev_fake_lessons": "Fake Live Activity órák", + "dev_fake_lessons_desc": "Teszt órákat generál a jelenlegi idő köré a Live Activity teszteléshez", "copy_jwt": "JWT másolása", "welcome_msg": "Üdvözlő üzenet", "default": "Dinamikus", @@ -327,6 +331,8 @@ extension SettingsLocalization on String { "devactivated": "Entwicklermodus erfolgreich aktiviert.", "devsettings": "Entwickleroptionen", "devmode": "Entwicklermodus", + "dev_fake_lessons": "Fake Live Activity Stunden", + "dev_fake_lessons_desc": "Generiert Teststunden um die aktuelle Zeit für Live Activity Tests", "copy_jwt": "JWT kopieren", "welcome_msg": "Willkommensnachricht", "default": "Dynamisch", From 5d95e1e1d7b212e6e9ef9c1f55bf30cf9e78d321 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 6 Mar 2026 15:29:06 +0100 Subject: [PATCH 21/59] Implement developer mode for Live Activity with fake lessons and immediate updates --- .../lib/api/providers/live_card_provider.dart | 46 +++++++++++++++---- .../lib/screens/settings/settings_screen.dart | 4 +- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 6e674858..a7cb8d0e 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -366,6 +366,16 @@ class LiveCardProvider extends ChangeNotifier { hasActivityStarted = true; _createAndSync(); } + // Fake mód: mindig hozzuk létre a Live Activity-t ha nincs elindítva + else if (!hasActivityStarted && + _settings.developerMode && + _settings.devLiveFakeLessons && + today.isNotEmpty) { + debugPrint("Fake mód: Live Activity létrehozás..."); + hasActivityStarted = true; + hasUserDismissed = false; + _createAndSync(); + } //UPDATE else if (hasActivityStarted) { @@ -394,7 +404,10 @@ class LiveCardProvider extends ChangeNotifier { } //END - if ((currentState == LiveCardState.afternoon || + // Fake módban ne fejezzük be a Live Activity-t + if (_settings.developerMode && _settings.devLiveFakeLessons) { + // skip end logic in fake mode + } else if ((currentState == LiveCardState.afternoon || currentState == LiveCardState.morning || currentState == LiveCardState.night) && hasActivityStarted && @@ -423,8 +436,6 @@ class LiveCardProvider extends ChangeNotifier { final result = await PlatformChannel.createLiveActivity(toMap()); if (result != null && result['success'] == 'true') { debugPrint("Live Activity létrehozva, várunk a push tokenre..."); - // A regisztráció az onTokenUpdated callback-ben történik, - // amikor az APNs elküldi a push tokent. } else { debugPrint("Live Activity létrehozás sikertelen"); hasActivityStarted = false; @@ -441,17 +452,32 @@ class LiveCardProvider extends ChangeNotifier { final real = (p.getWeek(Week.current()) ?? []) .where((l) => _sameDate(l.date, _now())) .toList(); - if (real.isNotEmpty || !_settings.developerMode || !_settings.devLiveFakeLessons) { + if (!_settings.developerMode || !_settings.devLiveFakeLessons) { return real; } + // Fake mód: ha vannak valódi órák, a fake órákat utánuk rakjuk + // DE: ha az utolsó valódi óra már véget ért, a fake-ek a jelen idő köré kerülnek + if (real.isNotEmpty) { + final sorted = List.from(real) + ..sort((a, b) => a.end.compareTo(b.end)); + final lastEnd = sorted.last.end; + final now = _now(); + final nextIndex = sorted.length; + if (lastEnd.isBefore(now)) { + // Az órák már véget értek — fake órákat a jelen idő köré + return [...real, ..._generateFakeLessons(startIndex: nextIndex)]; + } + // Van még óra — fake órákat az utolsó után + final fakeStart = lastEnd.add(const Duration(minutes: 10)); + return [...real, ..._generateFakeLessons(baseStart: fakeStart, startIndex: nextIndex)]; + } return _generateFakeLessons(); } /// Generál fake órákat a jelenlegi idő köré, hogy a Live Activity tesztelhető legyen. - static List _generateFakeLessons() { + static List _generateFakeLessons({DateTime? baseStart, int startIndex = 0}) { final now = _now(); - // Az első óra 10 perccel ezelőtt kezdődött (vagy ha nincs, 5 perc múlva) - final baseStart = now.subtract(const Duration(minutes: 10)); + final start0 = baseStart ?? now.subtract(const Duration(minutes: 10)); const subjects = [ ('Matematika', 'fake_math', 'Egyenletek'), @@ -464,18 +490,18 @@ class LiveCardProvider extends ChangeNotifier { final lessons = []; for (int i = 0; i < 6; i++) { - final start = baseStart.add(Duration(minutes: i * 55)); + final start = start0.add(Duration(minutes: i * 55)); final end = start.add(const Duration(minutes: 45)); final (name, id, desc) = subjects[i]; lessons.add(Lesson( - id: 'fake_lesson_$i', + id: 'fake_lesson_${startIndex + i}', date: DateTime(now.year, now.month, now.day), subject: GradeSubject( id: id, category: kreta.Category(id: '', name: ''), name: name, ), - lessonIndex: '${i + 1}', + lessonIndex: '${startIndex + i + 1}', teacher: Teacher(id: 'fake_teacher', name: 'Teszt Tanár'), start: start, end: end, diff --git a/refilc_mobile_ui/lib/screens/settings/settings_screen.dart b/refilc_mobile_ui/lib/screens/settings/settings_screen.dart index 96d6c7de..1b6a91eb 100644 --- a/refilc_mobile_ui/lib/screens/settings/settings_screen.dart +++ b/refilc_mobile_ui/lib/screens/settings/settings_screen.dart @@ -1046,7 +1046,7 @@ class SettingsScreenState extends State ], ), // developer options - if (true) + if (settings.developerMode) SplittedPanel( title: Text("devsettings".i18n), cardPadding: const EdgeInsets.all(4.0), @@ -1126,6 +1126,8 @@ class SettingsScreenState extends State LiveCardProvider.hasDayEnd = false; LiveCardProvider.hasUserDismissed = false; } + // Trigger LiveCardProvider update immediately + Provider.of(context, listen: false).update(); }, value: settings.devLiveFakeLessons, activeColor: Theme.of(context).colorScheme.secondary, From aea12d20fc08afa6206b07ff0a887ac83df22e72 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sat, 7 Mar 2026 12:13:23 +0100 Subject: [PATCH 22/59] Add Live Activity feature with consent dialog and settings integration --- .../lib/api/providers/live_card_provider.dart | 17 ++++ refilc/lib/database/init.dart | 17 ++++ refilc/lib/models/settings.dart | 17 +++- .../screens/navigation/navigation_screen.dart | 10 +++ .../live_activity_consent_dialog.dart | 81 +++++++++++++++++++ .../settings/settings_screen.i18n.dart | 15 ++++ .../settings/submenu/general_screen.dart | 58 +++++++++++++ 7 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index a7cb8d0e..42cbf340 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -68,6 +68,10 @@ class LiveCardProvider extends ChangeNotifier { // Token figyelése: amikor az APNs tokent ad (első vagy rotation), regisztráljuk a szerverrel PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) { + if (!_settings.liveActivityEnabled) { + debugPrint("Push token érkezett, de Live Activity nincs engedélyezve - skip"); + return; + } debugPrint("Push token érkezett: $pushToken"); serverSync.registerAndSync( deviceId: deviceId, @@ -345,6 +349,16 @@ class LiveCardProvider extends ChangeNotifier { //LIVE ACTIVITIES + // Guard: if not enabled, stop any running activity and skip + if (!_settings.liveActivityEnabled) { + if (hasActivityStarted) { + debugPrint("Live Activity nincs engedélyezve, de fut – leállítás..."); + PlatformChannel.endLiveActivity(); + serverSync.unregister(); + hasActivityStarted = false; + } + } else { + //CREATE if (!hasActivityStarted && !hasUserDismissed && @@ -428,6 +442,9 @@ class LiveCardProvider extends ChangeNotifier { hasActivityStarted = false; hasUserDismissed = false; } + + } // end of liveActivityEnabled else block + LAData = toMap(); notifyListeners(); } diff --git a/refilc/lib/database/init.dart b/refilc/lib/database/init.dart index 0f68e20e..e51e91f4 100644 --- a/refilc/lib/database/init.dart +++ b/refilc/lib/database/init.dart @@ -1,5 +1,6 @@ // ignore_for_file: avoid_print +import 'dart:convert'; import 'dart:io'; import 'package:refilc/api/providers/database_provider.dart'; @@ -57,6 +58,7 @@ const settingsDB = DatabaseStruct("settings", { "uwu_mode": int, "new_popups": int, "unseen_new_features": String, + "live_activity_enabled": int, "cloud_sync_enabled": int, "cloud_sync_token": String, "local_updated_at": String, @@ -185,6 +187,21 @@ Future initDB(DatabaseProvider database) async { print("ERROR: migrateDB: $error"); } + // One-time migration: add 'live_activity_consent' to unseen_new_features for existing users + try { + final rows = await db.query('settings', columns: ['unseen_new_features']); + if (rows.isNotEmpty) { + final raw = rows.first['unseen_new_features'] as String? ?? '[]'; + final list = (jsonDecode(raw) as List).cast(); + if (!list.contains('live_activity_consent')) { + list.add('live_activity_consent'); + await db.update('settings', {'unseen_new_features': jsonEncode(list)}); + } + } + } catch (e) { + print("ERROR: live_activity_consent migration: $e"); + } + return db; } diff --git a/refilc/lib/models/settings.dart b/refilc/lib/models/settings.dart index f4c4e3a1..9fa05d10 100644 --- a/refilc/lib/models/settings.dart +++ b/refilc/lib/models/settings.dart @@ -110,6 +110,7 @@ class SettingsProvider extends ChangeNotifier { bool _uwuMode; bool _newPopups; List _unseenNewFeatures; + bool _liveActivityEnabled; bool _cloudSyncEnabled; String _cloudSyncToken; DateTime _updatedAt; @@ -189,6 +190,7 @@ class SettingsProvider extends ChangeNotifier { required bool uwuMode, required bool newPopups, required List unseenNewFeatures, + required bool liveActivityEnabled, required bool cloudSyncEnabled, required String cloudSyncToken, required DateTime updatedAt, @@ -265,6 +267,7 @@ class SettingsProvider extends ChangeNotifier { _uwuMode = uwuMode, _newPopups = newPopups, _unseenNewFeatures = unseenNewFeatures, + _liveActivityEnabled = liveActivityEnabled, _cloudSyncEnabled = cloudSyncEnabled, _cloudSyncToken = cloudSyncToken, _updatedAt = updatedAt, @@ -360,6 +363,7 @@ class SettingsProvider extends ChangeNotifier { uwuMode: map['uwu_mode'] == 1, newPopups: map['new_popups'] == 1, unseenNewFeatures: jsonDecode(map["unseen_new_features"]).cast(), + liveActivityEnabled: map['live_activity_enabled'] == 1, cloudSyncEnabled: map['cloud_sync_enabled'] == 1, cloudSyncToken: map['cloud_sync_token'], updatedAt: DateTime.tryParse(map['local_updated_at']) ?? DateTime.now(), @@ -443,6 +447,7 @@ class SettingsProvider extends ChangeNotifier { "uwu_mode": _uwuMode ? 1 : 0, "new_popups": _newPopups ? 1 : 0, "unseen_new_features": jsonEncode(_unseenNewFeatures), + "live_activity_enabled": _liveActivityEnabled ? 1 : 0, "cloud_sync_enabled": _cloudSyncEnabled ? 1 : 0, "cloud_sync_token": _cloudSyncToken, "local_updated_at": _updatedAt.toIso8601String(), @@ -529,7 +534,8 @@ class SettingsProvider extends ChangeNotifier { newColors: true, uwuMode: false, newPopups: false, - unseenNewFeatures: [], + unseenNewFeatures: ['live_activity_consent'], + liveActivityEnabled: false, cloudSyncEnabled: false, cloudSyncToken: '', updatedAt: DateTime.now(), @@ -608,6 +614,7 @@ class SettingsProvider extends ChangeNotifier { bool get uwuMode => _uwuMode; bool get newPopups => _newPopups; List get unseenNewFeatures => _unseenNewFeatures; + bool get liveActivityEnabled => _liveActivityEnabled; bool get cloudSyncEnabled => _cloudSyncEnabled; String get cloudSyncToken => _cloudSyncToken; DateTime get updatedAt => _updatedAt; @@ -683,6 +690,7 @@ class SettingsProvider extends ChangeNotifier { bool? uwuMode, bool? newPopups, List? unseenNewFeatures, + bool? liveActivityEnabled, bool? cloudSyncEnabled, String? cloudSyncToken, bool? qTimetableLessonNum, @@ -886,6 +894,12 @@ class SettingsProvider extends ChangeNotifier { if (unseenNewFeatures != null && unseenNewFeatures != _unseenNewFeatures) { _unseenNewFeatures = unseenNewFeatures; } + if (liveActivityEnabled != null && liveActivityEnabled != _liveActivityEnabled) { + _liveActivityEnabled = liveActivityEnabled; + if (!liveActivityEnabled && Platform.isIOS) { + LiveCardProvider.hasActivitySettingsChanged = true; + } + } if (cloudSyncEnabled != null && cloudSyncEnabled != _cloudSyncEnabled) { _cloudSyncEnabled = cloudSyncEnabled; } @@ -1005,6 +1019,7 @@ class SettingsProvider extends ChangeNotifier { newPopups: map['new_popups'] == 1, unseenNewFeatures: jsonDecode(map["unseen_new_features"] ?? "[]").cast(), + liveActivityEnabled: map['live_activity_enabled'] == 1, cloudSyncEnabled: map['cloud_sync_enabled'] == 1, cloudSyncToken: map['cloud_sync_token'], qTimetableLessonNum: map['q_timetable_lesson_num'] == 1, diff --git a/refilc_mobile_ui/lib/screens/navigation/navigation_screen.dart b/refilc_mobile_ui/lib/screens/navigation/navigation_screen.dart index 2390c50e..03952f52 100644 --- a/refilc_mobile_ui/lib/screens/navigation/navigation_screen.dart +++ b/refilc_mobile_ui/lib/screens/navigation/navigation_screen.dart @@ -18,6 +18,7 @@ import 'package:refilc_mobile_ui/screens/navigation/navigation_route_handler.dar import 'package:refilc_mobile_ui/screens/navigation/status_bar.dart'; import 'package:refilc_mobile_ui/screens/news/news_view.dart'; import 'package:refilc_mobile_ui/screens/settings/settings_screen.dart'; +import 'package:refilc_mobile_ui/screens/settings/live_activity_consent_dialog.dart'; import 'package:refilc_plus/ui/mobile/goal_planner/goal_complete_modal.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -32,6 +33,7 @@ import 'package:wtf_sliding_sheet/wtf_sliding_sheet.dart'; import 'package:background_fetch/background_fetch.dart'; import 'package:refilc_plus/providers/goal_provider.dart'; import 'package:refilc/api/providers/ad_provider.dart'; +import 'dart:io' show Platform; class NavigationScreen extends StatefulWidget { const NavigationScreen({super.key}); @@ -190,6 +192,14 @@ class NavigationScreenState extends State // initial sync syncAll(context); setupQuickActions(); + + // Show live activity consent dialog on iOS + if (Platform.isIOS && + settings.unseenNewFeatures.contains('live_activity_consent')) { + WidgetsBinding.instance.addPostFrameCallback((_) { + LiveActivityConsentDialog.show(context); + }); + } } @override diff --git a/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart new file mode 100644 index 00000000..6baf6af8 --- /dev/null +++ b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart @@ -0,0 +1,81 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:refilc/models/settings.dart'; +import 'package:refilc_mobile_ui/screens/settings/settings_screen.i18n.dart'; + +class LiveActivityConsentDialog extends StatelessWidget { + const LiveActivityConsentDialog({super.key}); + + static Future show(BuildContext context) => showDialog( + context: context, + barrierDismissible: false, + builder: (context) => const LiveActivityConsentDialog(), + ); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 100.0, horizontal: 32.0), + child: Material( + borderRadius: BorderRadius.circular(12.0), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: Text( + "live_activity_consent_title".i18n, + style: const TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.bold, + ), + ), + ), + Expanded( + child: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Text( + "live_activity_consent_body".i18n, + style: const TextStyle(fontSize: 14.0), + ), + ), + ), + const SizedBox(height: 16.0), + Row( + children: [ + Expanded( + child: TextButton( + onPressed: () => _respond(context, false), + child: Text("live_activity_decline".i18n), + ), + ), + const SizedBox(width: 8.0), + Expanded( + child: FilledButton( + onPressed: () => _respond(context, true), + child: Text("live_activity_accept".i18n), + ), + ), + ], + ), + ], + ), + ), + ), + ); + } + + void _respond(BuildContext context, bool accepted) { + final settings = Provider.of(context, listen: false); + final unseen = + List.from(settings.unseenNewFeatures); + unseen.remove('live_activity_consent'); + settings.update( + liveActivityEnabled: accepted, + unseenNewFeatures: unseen, + ); + Navigator.of(context).pop(); + } +} diff --git a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart index 9d45b3e2..1b2ee395 100644 --- a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart +++ b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart @@ -98,6 +98,11 @@ extension SettingsLocalization on String { "rename_subjects": "Rename Subjects", "rename_teachers": "Rename Teachers", "show_breaks": "Show Breaks", + "live_activity_enabled": "Live Activity", + "live_activity_consent_title": "Live Activity – Data Privacy", + "live_activity_consent_body": "The Live Activity feature sends data to our server for real-time push notification updates.\n\nData sent:\n• Device identifier\n• APNs push token\n• Your timetable\n\nPurpose:\n• Real-time Live Activity updates via push notifications\n\nData is stored on an encrypted server. You can disable this at any time in Settings > General.", + "live_activity_accept": "Allow", + "live_activity_decline": "Don't Allow", "fonts": "Fonts", "font_family": "Font Family", "calendar_sync": "Calendar Sync", @@ -228,6 +233,11 @@ extension SettingsLocalization on String { "rename_subjects": "Tantárgyak átnevezése", "rename_teachers": "Tanárok átnevezése", "show_breaks": "Szünetek megjelenítése", + "live_activity_enabled": "Live Activity", + "live_activity_consent_title": "Live Activity – Adatvédelem", + "live_activity_consent_body": "A Live Activity funkció adatokat küld a szerverünkre a valós idejű push értesítés frissítésekhez.\n\nKüldött adatok:\n• Eszközazonosító\n• APNs push token\n• Órarendjeid\n\nCél:\n• Valós idejű Live Activity frissítések push értesítéssel\n\nAz adatokat titkosított szerveren tároljuk. Bármikor kikapcsolhatod a Beállítások > Általános menüben.", + "live_activity_accept": "Engedélyezem", + "live_activity_decline": "Nem engedélyezem", "fonts": "Betűk", "font_family": "Betűtípus", "calendar_sync": "Naptár szinkronizálás", @@ -358,6 +368,11 @@ extension SettingsLocalization on String { "rename_subjects": "Fächer umbenennen", "rename_teachers": "Lehrer umbenennen", "show_breaks": "Pausen anzeigen", + "live_activity_enabled": "Live Activity", + "live_activity_consent_title": "Live Activity – Datenschutz", + "live_activity_consent_body": "Die Live Activity-Funktion sendet Daten an unseren Server für Echtzeit-Push-Benachrichtigungen.\n\nGesendete Daten:\n• Gerätekennung\n• APNs Push-Token\n• Ihr Stundenplan\n\nZweck:\n• Echtzeit Live Activity-Updates über Push-Benachrichtigungen\n\nDaten werden auf einem verschlüsselten Server gespeichert. Sie können dies jederzeit unter Einstellungen > Allgemein deaktivieren.", + "live_activity_accept": "Erlauben", + "live_activity_decline": "Nicht erlauben", "fonts": "Schriftarten", "font_family": "Schriftfamilie", "calendar_sync": "Kalender-Synchronisation", diff --git a/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart b/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart index a67547cc..076dd20a 100644 --- a/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart +++ b/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart @@ -1,3 +1,6 @@ +import 'dart:io' show Platform; +import 'package:refilc/api/providers/liveactivity/platform_channel.dart'; +import 'package:refilc/api/providers/live_card_provider.dart'; import 'package:refilc/models/settings.dart'; import 'package:refilc/theme/colors/colors.dart'; import 'package:refilc/utils/format.dart'; @@ -123,6 +126,61 @@ class GeneralSettingsScreenState extends State { ), ], ), + if (Platform.isIOS) + SplittedPanel( + padding: const EdgeInsets.only(top: 9.0), + cardPadding: const EdgeInsets.all(4.0), + isSeparated: true, + children: [ + PanelButton( + padding: const EdgeInsets.only(left: 14.0, right: 6.0), + onPressed: () { + final newVal = !settingsProvider.liveActivityEnabled; + settingsProvider.update(liveActivityEnabled: newVal); + if (!newVal) { + PlatformChannel.endLiveActivity(); + LiveCardProvider.serverSync.unregister(); + LiveCardProvider.hasActivityStarted = false; + } + setState(() {}); + }, + title: Text( + "live_activity_enabled".i18n, + style: TextStyle( + color: AppColors.of(context).text.withValues( + alpha: settingsProvider.liveActivityEnabled + ? .95 + : .25), + ), + ), + leading: Icon( + FeatherIcons.activity, + size: 22.0, + color: AppColors.of(context).text.withValues( + alpha: settingsProvider.liveActivityEnabled + ? .95 + : .25), + ), + trailing: Switch( + onChanged: (v) { + settingsProvider.update(liveActivityEnabled: v); + if (!v) { + PlatformChannel.endLiveActivity(); + LiveCardProvider.serverSync.unregister(); + LiveCardProvider.hasActivityStarted = false; + } + setState(() {}); + }, + value: settingsProvider.liveActivityEnabled, + activeColor: Theme.of(context).colorScheme.secondary, + ), + borderRadius: const BorderRadius.vertical( + top: Radius.circular(12.0), + bottom: Radius.circular(12.0), + ), + ), + ], + ), SplittedPanel( padding: const EdgeInsets.only(top: 9.0), cardPadding: const EdgeInsets.all(4.0), From 022d5c81ce19d708aed8d76b6eed6141fc609cc0 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sat, 7 Mar 2026 12:38:46 +0100 Subject: [PATCH 23/59] Refactor Live Activity consent dialog and add privacy policy screen with localization support --- .../live_activity_consent_dialog.dart | 330 +++++++++++++++--- .../live_activity_privacy_policy_screen.dart | 175 ++++++++++ .../settings/settings_screen.i18n.dart | 171 ++++++++- 3 files changed, 628 insertions(+), 48 deletions(-) create mode 100644 refilc_mobile_ui/lib/screens/settings/live_activity_privacy_policy_screen.dart diff --git a/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart index 6baf6af8..76776792 100644 --- a/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart +++ b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart @@ -1,65 +1,254 @@ import 'package:flutter/material.dart'; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; import 'package:provider/provider.dart'; import 'package:refilc/models/settings.dart'; +import 'package:refilc/theme/colors/colors.dart'; +import 'package:refilc_mobile_ui/screens/settings/live_activity_privacy_policy_screen.dart'; import 'package:refilc_mobile_ui/screens/settings/settings_screen.i18n.dart'; class LiveActivityConsentDialog extends StatelessWidget { const LiveActivityConsentDialog({super.key}); - static Future show(BuildContext context) => showDialog( - context: context, - barrierDismissible: false, + static Future show(BuildContext context) { + return Navigator.of(context, rootNavigator: true).push( + MaterialPageRoute( builder: (context) => const LiveActivityConsentDialog(), - ); + ), + ); + } @override Widget build(BuildContext context) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 100.0, horizontal: 32.0), - child: Material( - borderRadius: BorderRadius.circular(12.0), + final theme = Theme.of(context); + final colors = AppColors.of(context); + + return Scaffold( + backgroundColor: theme.scaffoldBackgroundColor, + body: SafeArea( child: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.symmetric(horizontal: 24.0), child: Column( - mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding( - padding: const EdgeInsets.only(bottom: 12.0), - child: Text( - "live_activity_consent_title".i18n, - style: const TextStyle( - fontSize: 20.0, - fontWeight: FontWeight.bold, - ), - ), - ), - Expanded( - child: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Text( - "live_activity_consent_body".i18n, - style: const TextStyle(fontSize: 14.0), - ), - ), - ), - const SizedBox(height: 16.0), + const SizedBox(height: 24.0), + // Header: bell icon + title Row( children: [ - Expanded( - child: TextButton( - onPressed: () => _respond(context, false), - child: Text("live_activity_decline".i18n), - ), + Icon( + Icons.notifications_active, + color: theme.colorScheme.secondary, + size: 36.0, ), - const SizedBox(width: 8.0), - Expanded( - child: FilledButton( - onPressed: () => _respond(context, true), - child: Text("live_activity_accept".i18n), + const SizedBox(width: 12.0), + Text( + "Live Activity", + style: TextStyle( + fontSize: 28.0, + fontWeight: FontWeight.bold, + color: colors.text, ), ), ], ), + const SizedBox(height: 8.0), + Text( + "la_consent_subtitle".i18n, + style: TextStyle( + fontSize: 15.0, + color: colors.text.withValues(alpha: 0.7), + ), + ), + + const SizedBox(height: 20.0), + + // Privacy warning card + Container( + width: double.infinity, + padding: const EdgeInsets.all(16.0), + decoration: BoxDecoration( + color: colors.orange.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(12.0), + border: Border.all( + color: colors.orange.withValues(alpha: 0.3), + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.shield_outlined, + color: colors.orange, + size: 22.0, + ), + const SizedBox(width: 12.0), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "la_privacy_policy".i18n, + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.w600, + color: colors.orange, + ), + ), + const SizedBox(height: 4.0), + Text( + "la_privacy_warning".i18n, + style: TextStyle( + fontSize: 13.0, + color: colors.orange.withValues(alpha: 0.85), + ), + ), + ], + ), + ), + ], + ), + ), + + const SizedBox(height: 24.0), + + // Intro text + Text( + "la_consent_intro".i18n, + style: TextStyle( + fontSize: 14.0, + color: colors.text.withValues(alpha: 0.8), + ), + ), + + const SizedBox(height: 24.0), + + // Info sections + Expanded( + child: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + children: [ + _InfoSection( + icon: Icons.build_outlined, + iconColor: theme.colorScheme.secondary, + title: "la_what_data".i18n, + description: "la_what_data_desc".i18n, + ), + const SizedBox(height: 20.0), + _InfoSection( + icon: Icons.lock_outline, + iconColor: theme.colorScheme.secondary, + title: "la_how_protect".i18n, + description: "la_how_protect_desc".i18n, + ), + const SizedBox(height: 20.0), + _InfoSection( + icon: Icons.access_time, + iconColor: theme.colorScheme.secondary, + title: "la_how_long".i18n, + description: "la_how_long_desc".i18n, + ), + const SizedBox(height: 16.0), + ], + ), + ), + ), + + // Buttons + Padding( + padding: const EdgeInsets.only(bottom: 16.0), + child: Column( + children: [ + // Learn more + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + const LiveActivityPrivacyPolicyScreen(), + ), + ); + }, + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14.0), + side: BorderSide( + color: colors.text.withValues(alpha: 0.2), + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12.0), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "la_learn_more".i18n, + style: TextStyle( + color: colors.text.withValues(alpha: 0.8), + fontSize: 15.0, + ), + ), + const SizedBox(width: 4.0), + Icon( + FeatherIcons.chevronRight, + size: 18.0, + color: colors.text.withValues(alpha: 0.8), + ), + ], + ), + ), + ), + const SizedBox(height: 10.0), + // Accept + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => _respond(context, true), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14.0), + backgroundColor: theme.colorScheme.secondary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12.0), + ), + ), + child: Text( + "live_activity_accept".i18n, + style: TextStyle( + color: theme.colorScheme.onSecondary, + fontSize: 16.0, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + const SizedBox(height: 8.0), + // Decline + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => _respond(context, false), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14.0), + side: BorderSide( + color: colors.text.withValues(alpha: 0.15), + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12.0), + ), + ), + child: Text( + "live_activity_decline".i18n, + style: TextStyle( + color: colors.text.withValues(alpha: 0.6), + fontSize: 15.0, + ), + ), + ), + ), + ], + ), + ), ], ), ), @@ -69,8 +258,7 @@ class LiveActivityConsentDialog extends StatelessWidget { void _respond(BuildContext context, bool accepted) { final settings = Provider.of(context, listen: false); - final unseen = - List.from(settings.unseenNewFeatures); + final unseen = List.from(settings.unseenNewFeatures); unseen.remove('live_activity_consent'); settings.update( liveActivityEnabled: accepted, @@ -79,3 +267,61 @@ class LiveActivityConsentDialog extends StatelessWidget { Navigator.of(context).pop(); } } + +class _InfoSection extends StatelessWidget { + final IconData icon; + final Color iconColor; + final String title; + final String description; + + const _InfoSection({ + required this.icon, + required this.iconColor, + required this.title, + required this.description, + }); + + @override + Widget build(BuildContext context) { + final colors = AppColors.of(context); + + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 40.0, + height: 40.0, + decoration: BoxDecoration( + color: iconColor.withValues(alpha: 0.15), + shape: BoxShape.circle, + ), + child: Icon(icon, color: iconColor, size: 20.0), + ), + const SizedBox(width: 14.0), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontSize: 15.0, + fontWeight: FontWeight.w600, + color: colors.text, + ), + ), + const SizedBox(height: 4.0), + Text( + description, + style: TextStyle( + fontSize: 13.5, + color: colors.text.withValues(alpha: 0.6), + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/refilc_mobile_ui/lib/screens/settings/live_activity_privacy_policy_screen.dart b/refilc_mobile_ui/lib/screens/settings/live_activity_privacy_policy_screen.dart new file mode 100644 index 00000000..0958a339 --- /dev/null +++ b/refilc_mobile_ui/lib/screens/settings/live_activity_privacy_policy_screen.dart @@ -0,0 +1,175 @@ +import 'package:flutter/material.dart'; +import 'package:refilc/theme/colors/colors.dart'; +import 'package:refilc_mobile_ui/screens/settings/settings_screen.i18n.dart'; + +class LiveActivityPrivacyPolicyScreen extends StatelessWidget { + const LiveActivityPrivacyPolicyScreen({super.key}); + + @override + Widget build(BuildContext context) { + final colors = AppColors.of(context); + + return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + appBar: AppBar( + surfaceTintColor: Theme.of(context).scaffoldBackgroundColor, + leading: BackButton(color: colors.text), + title: Text( + "la_pp_title".i18n, + style: TextStyle( + color: colors.text, + fontWeight: FontWeight.bold, + ), + ), + ), + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _bodyText("la_pp_intro".i18n, colors), + const SizedBox(height: 24.0), + + _sectionTitle("la_pp_what_title".i18n, colors), + const SizedBox(height: 8.0), + _bodyText("la_pp_what_intro".i18n, colors), + const SizedBox(height: 12.0), + _bulletList([ + "la_pp_d1".i18n, + "la_pp_d2".i18n, + "la_pp_d3".i18n, + "la_pp_d4".i18n, + "la_pp_d5".i18n, + "la_pp_d6".i18n, + "la_pp_d7".i18n, + ], colors), + const SizedBox(height: 16.0), + + _bodyText("la_pp_timetable_intro".i18n, colors), + const SizedBox(height: 12.0), + _bulletList([ + "la_pp_t1".i18n, + "la_pp_t2".i18n, + "la_pp_t3".i18n, + "la_pp_t4".i18n, + "la_pp_t5".i18n, + "la_pp_t6".i18n, + "la_pp_t7".i18n, + ], colors), + const SizedBox(height: 16.0), + + _bodyText("la_pp_notifications_intro".i18n, colors), + const SizedBox(height: 12.0), + _bulletList([ + "la_pp_n1".i18n, + "la_pp_n2".i18n, + "la_pp_n3".i18n, + "la_pp_n4".i18n, + "la_pp_n5".i18n, + ], colors), + const SizedBox(height: 24.0), + + _sectionTitle("la_pp_purpose_title".i18n, colors), + const SizedBox(height: 8.0), + _bodyText("la_pp_purpose_intro".i18n, colors), + const SizedBox(height: 12.0), + _bulletList([ + "la_pp_p1".i18n, + "la_pp_p2".i18n, + "la_pp_p3".i18n, + "la_pp_p4".i18n, + ], colors), + const SizedBox(height: 12.0), + _bodyText("la_pp_no_third_party".i18n, colors), + const SizedBox(height: 24.0), + + _sectionTitle("la_pp_rights_title".i18n, colors), + const SizedBox(height: 8.0), + _bodyText("la_pp_rights_intro".i18n, colors), + const SizedBox(height: 12.0), + _bulletList([ + "la_pp_r1".i18n, + "la_pp_r2".i18n, + "la_pp_r3".i18n, + "la_pp_r4".i18n, + ], colors), + const SizedBox(height: 32.0), + + Text( + "la_pp_updated".i18n, + style: TextStyle( + fontSize: 12.0, + color: colors.text.withValues(alpha: 0.4), + ), + ), + const SizedBox(height: 4.0), + Text( + "la_pp_contact".i18n, + style: TextStyle( + fontSize: 12.0, + color: colors.text.withValues(alpha: 0.4), + ), + ), + const SizedBox(height: 32.0), + ], + ), + ), + ); + } + + Widget _sectionTitle(String text, ThemeAppColors colors) { + return Text( + text, + style: TextStyle( + fontSize: 18.0, + fontWeight: FontWeight.bold, + color: colors.text, + ), + ); + } + + Widget _bodyText(String text, ThemeAppColors colors) { + return Text( + text, + style: TextStyle( + fontSize: 14.0, + color: colors.text.withValues(alpha: 0.7), + height: 1.5, + ), + ); + } + + Widget _bulletList(List items, ThemeAppColors colors) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: items + .map((item) => Padding( + padding: const EdgeInsets.only(bottom: 6.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "• ", + style: TextStyle( + fontSize: 14.0, + color: colors.text.withValues(alpha: 0.7), + ), + ), + Expanded( + child: Text( + item, + style: TextStyle( + fontSize: 14.0, + color: colors.text.withValues(alpha: 0.7), + height: 1.4, + ), + ), + ), + ], + ), + )) + .toList(), + ); + } +} diff --git a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart index 1b2ee395..c630bfbd 100644 --- a/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart +++ b/refilc_mobile_ui/lib/screens/settings/settings_screen.i18n.dart @@ -101,8 +101,61 @@ extension SettingsLocalization on String { "live_activity_enabled": "Live Activity", "live_activity_consent_title": "Live Activity – Data Privacy", "live_activity_consent_body": "The Live Activity feature sends data to our server for real-time push notification updates.\n\nData sent:\n• Device identifier\n• APNs push token\n• Your timetable\n\nPurpose:\n• Real-time Live Activity updates via push notifications\n\nData is stored on an encrypted server. You can disable this at any time in Settings > General.", - "live_activity_accept": "Allow", - "live_activity_decline": "Don't Allow", + "live_activity_accept": "Accept", + "live_activity_decline": "Decline", + // Live Activity consent screen + "la_consent_subtitle": "Display your timetable live on your device's lock screen", + "la_privacy_policy": "Privacy Policy", + "la_privacy_warning": "To use Live Activity, you must accept the privacy policy", + "la_consent_intro": "To use the Live Activity feature, we need to store and process certain data. Please read the following information carefully.", + "la_what_data": "What data do we store?", + "la_what_data_desc": "Device tokens, Live Activity tokens, timetable data", + "la_how_protect": "How do we protect your data?", + "la_how_protect_desc": "Encrypted storage, secure servers", + "la_how_long": "How long do we store the data?", + "la_how_long_desc": "Data deleted automatically when not needed", + "la_learn_more": "Learn more", + // Live Activity privacy policy detail + "la_pp_title": "Live Activity Privacy Policy", + "la_pp_intro": "To use the Live Activity feature, we need to store and process certain data. Please read the following information carefully.", + "la_pp_what_title": "What data do we store?", + "la_pp_what_intro": "To enable Live Activity, we store the following data along with your device identifier:", + "la_pp_d1": "Device identifier (UUID)", + "la_pp_d2": "Device token", + "la_pp_d3": "Live Activity push token", + "la_pp_d4": "APNs push token", + "la_pp_d5": "Device hash", + "la_pp_d6": "Language preference", + "la_pp_d7": "Bell delay offset", + "la_pp_timetable_intro": "Your timetable data (lessons table) includes:", + "la_pp_t1": "Lesson subject and time", + "la_pp_t2": "Teacher's name", + "la_pp_t3": "Room name", + "la_pp_t4": "Lesson number", + "la_pp_t5": "Lesson theme", + "la_pp_t6": "Substitution info", + "la_pp_t7": "Cancelled lesson status", + "la_pp_notifications_intro": "Scheduled notifications data (scheduled_notifications table) includes:", + "la_pp_n1": "Identifier", + "la_pp_n2": "Device identifier", + "la_pp_n3": "Scheduled time", + "la_pp_n4": "Sent status and time", + "la_pp_n5": "Creation and update times", + "la_pp_purpose_title": "Why do we use this data?", + "la_pp_purpose_intro": "We use the data exclusively for operating the Live Activity feature:", + "la_pp_p1": "Displaying live timetable on the lock screen", + "la_pp_p2": "Sending push notifications when lessons change", + "la_pp_p3": "Syncing your timetable on your device", + "la_pp_p4": "Ensuring Monday morning notifications are delivered even after the weekly database clearance", + "la_pp_no_third_party": "We do not share your data with third parties and do not use it for marketing purposes.", + "la_pp_rights_title": "Your Rights", + "la_pp_rights_intro": "Under GDPR, you have the following rights:", + "la_pp_r1": "Right to access: You can review the types of data stored in this privacy policy.", + "la_pp_r2": "Right to erasure: By disabling the Live Activity feature, all data related to the feature (device identifiers, timetable) is immediately and permanently deleted from our servers.", + "la_pp_r3": "Right to rectification: Timetable data is modified in the Kréta system by authorized persons (e.g., teachers).", + "la_pp_r4": "Right to object: You can object to data processing at any time by disabling the Live Activity feature.", + "la_pp_updated": "Privacy policy last updated: November 2025", + "la_pp_contact": "Have questions? Contact us at support@firka.app.", "fonts": "Fonts", "font_family": "Font Family", "calendar_sync": "Calendar Sync", @@ -236,8 +289,61 @@ extension SettingsLocalization on String { "live_activity_enabled": "Live Activity", "live_activity_consent_title": "Live Activity – Adatvédelem", "live_activity_consent_body": "A Live Activity funkció adatokat küld a szerverünkre a valós idejű push értesítés frissítésekhez.\n\nKüldött adatok:\n• Eszközazonosító\n• APNs push token\n• Órarendjeid\n\nCél:\n• Valós idejű Live Activity frissítések push értesítéssel\n\nAz adatokat titkosított szerveren tároljuk. Bármikor kikapcsolhatod a Beállítások > Általános menüben.", - "live_activity_accept": "Engedélyezem", - "live_activity_decline": "Nem engedélyezem", + "live_activity_accept": "Elfogadom", + "live_activity_decline": "Elutasítom", + // Live Activity consent screen + "la_consent_subtitle": "Jelenítsd meg az órarendedet élőben a zárolási képernyődön", + "la_privacy_policy": "Adatvédelmi szabályzat", + "la_privacy_warning": "A Live Activity használatához el kell fogadnod az adatvédelmi szabályzatot", + "la_consent_intro": "A Live Activity funkció használatához bizonyos adatokat kell tárolnunk és feldolgoznunk. Kérjük, olvasd el figyelmesen az alábbi tájékoztatást.", + "la_what_data": "Milyen adatokat tárolunk?", + "la_what_data_desc": "Eszköz tokenek, Live Activity tokenek, órarend adatok", + "la_how_protect": "Hogyan védjük az adataidat?", + "la_how_protect_desc": "Titkosított tárolás, biztonságos szerverek", + "la_how_long": "Meddig tároljuk az adatokat?", + "la_how_long_desc": "Az adatok automatikusan törlődnek, ha már nincs rájuk szükség", + "la_learn_more": "Részletek", + // Live Activity privacy policy detail + "la_pp_title": "Live Activity Adatvédelmi Szabályzat", + "la_pp_intro": "A Live Activity funkció használatához bizonyos adatokat kell tárolnunk és feldolgoznunk. Kérjük, olvasd el figyelmesen az alábbi tájékoztatást.", + "la_pp_what_title": "Milyen adatokat tárolunk?", + "la_pp_what_intro": "A Live Activity működéséhez az alábbi adatokat tároljuk az eszközazonosítóddal együtt:", + "la_pp_d1": "Eszközazonosító (UUID)", + "la_pp_d2": "Eszköz token", + "la_pp_d3": "Live Activity push token", + "la_pp_d4": "APNs push token", + "la_pp_d5": "Eszköz hash", + "la_pp_d6": "Nyelvi beállítás", + "la_pp_d7": "Csengő eltolódás értéke", + "la_pp_timetable_intro": "Az órarend adataid (lessons tábla) tartalmazzák:", + "la_pp_t1": "Óra tantárgya és időpontja", + "la_pp_t2": "Tanár neve", + "la_pp_t3": "Terem neve", + "la_pp_t4": "Óraszám", + "la_pp_t5": "Óra témája", + "la_pp_t6": "Helyettesítési információ", + "la_pp_t7": "Elmaradt óra státusz", + "la_pp_notifications_intro": "Ütemezett értesítések adatai (scheduled_notifications tábla) tartalmazzák:", + "la_pp_n1": "Azonosító", + "la_pp_n2": "Eszközazonosító", + "la_pp_n3": "Ütemezett időpont", + "la_pp_n4": "Küldési státusz és időpont", + "la_pp_n5": "Létrehozási és frissítési időpontok", + "la_pp_purpose_title": "Miért használjuk ezeket az adatokat?", + "la_pp_purpose_intro": "Az adatokat kizárólag a Live Activity funkció működtetéséhez használjuk:", + "la_pp_p1": "Élő órarend megjelenítése a zárolási képernyőn", + "la_pp_p2": "Push értesítések küldése óraváltozáskor", + "la_pp_p3": "Órarend szinkronizálása az eszközödön", + "la_pp_p4": "Hétfő reggeli értesítések kézbesítésének biztosítása a heti adatbázis törlés után is", + "la_pp_no_third_party": "Adataidat nem adjuk át harmadik félnek és nem használjuk marketing célokra.", + "la_pp_rights_title": "Jogaid", + "la_pp_rights_intro": "A GDPR alapján az alábbi jogok illetnek meg:", + "la_pp_r1": "Hozzáférés joga: Áttekintheted a tárolt adatok típusait ebben az adatvédelmi szabályzatban.", + "la_pp_r2": "Törlés joga: A Live Activity funkció kikapcsolásával a funkcióhoz kapcsolódó összes adat (eszközazonosítók, órarend) azonnal és véglegesen törlődik a szervereinkről.", + "la_pp_r3": "Helyesbítés joga: Az órarend adatokat a Kréta rendszerben az arra jogosult személyek (pl. tanárok) módosítják.", + "la_pp_r4": "Tiltakozás joga: Bármikor tiltakozhatsz az adatfeldolgozás ellen a Live Activity funkció kikapcsolásával.", + "la_pp_updated": "Adatvédelmi szabályzat utolsó frissítése: 2025. november", + "la_pp_contact": "Kérdésed van? Írj nekünk: support@firka.app.", "fonts": "Betűk", "font_family": "Betűtípus", "calendar_sync": "Naptár szinkronizálás", @@ -371,8 +477,61 @@ extension SettingsLocalization on String { "live_activity_enabled": "Live Activity", "live_activity_consent_title": "Live Activity – Datenschutz", "live_activity_consent_body": "Die Live Activity-Funktion sendet Daten an unseren Server für Echtzeit-Push-Benachrichtigungen.\n\nGesendete Daten:\n• Gerätekennung\n• APNs Push-Token\n• Ihr Stundenplan\n\nZweck:\n• Echtzeit Live Activity-Updates über Push-Benachrichtigungen\n\nDaten werden auf einem verschlüsselten Server gespeichert. Sie können dies jederzeit unter Einstellungen > Allgemein deaktivieren.", - "live_activity_accept": "Erlauben", - "live_activity_decline": "Nicht erlauben", + "live_activity_accept": "Akzeptieren", + "live_activity_decline": "Ablehnen", + // Live Activity consent screen + "la_consent_subtitle": "Zeigen Sie Ihren Stundenplan live auf Ihrem Sperrbildschirm an", + "la_privacy_policy": "Datenschutzrichtlinie", + "la_privacy_warning": "Um Live Activity zu nutzen, müssen Sie die Datenschutzrichtlinie akzeptieren", + "la_consent_intro": "Um die Live Activity-Funktion zu nutzen, müssen wir bestimmte Daten speichern und verarbeiten. Bitte lesen Sie die folgenden Informationen sorgfältig durch.", + "la_what_data": "Welche Daten speichern wir?", + "la_what_data_desc": "Geräte-Tokens, Live Activity-Tokens, Stundenplan-Daten", + "la_how_protect": "Wie schützen wir Ihre Daten?", + "la_how_protect_desc": "Verschlüsselte Speicherung, sichere Server", + "la_how_long": "Wie lange speichern wir die Daten?", + "la_how_long_desc": "Daten werden automatisch gelöscht, wenn sie nicht mehr benötigt werden", + "la_learn_more": "Mehr erfahren", + // Live Activity privacy policy detail + "la_pp_title": "Live Activity Datenschutzrichtlinie", + "la_pp_intro": "Um die Live Activity-Funktion zu nutzen, müssen wir bestimmte Daten speichern und verarbeiten. Bitte lesen Sie die folgenden Informationen sorgfältig durch.", + "la_pp_what_title": "Welche Daten speichern wir?", + "la_pp_what_intro": "Um Live Activity zu aktivieren, speichern wir die folgenden Daten zusammen mit Ihrer Gerätekennung:", + "la_pp_d1": "Gerätekennung (UUID)", + "la_pp_d2": "Geräte-Token", + "la_pp_d3": "Live Activity Push-Token", + "la_pp_d4": "APNs Push-Token", + "la_pp_d5": "Geräte-Hash", + "la_pp_d6": "Spracheinstellung", + "la_pp_d7": "Klingelverzögerungswert", + "la_pp_timetable_intro": "Ihre Stundenplan-Daten (Unterrichtstabelle) umfassen:", + "la_pp_t1": "Unterrichtsfach und -zeit", + "la_pp_t2": "Name des Lehrers", + "la_pp_t3": "Raumname", + "la_pp_t4": "Stundennummer", + "la_pp_t5": "Unterrichtsthema", + "la_pp_t6": "Vertretungsinformationen", + "la_pp_t7": "Status ausgefallener Stunden", + "la_pp_notifications_intro": "Geplante Benachrichtigungsdaten (scheduled_notifications Tabelle) umfassen:", + "la_pp_n1": "Kennung", + "la_pp_n2": "Gerätekennung", + "la_pp_n3": "Geplante Zeit", + "la_pp_n4": "Sendestatus und -zeit", + "la_pp_n5": "Erstellungs- und Aktualisierungszeiten", + "la_pp_purpose_title": "Warum verwenden wir diese Daten?", + "la_pp_purpose_intro": "Wir verwenden die Daten ausschließlich für den Betrieb der Live Activity-Funktion:", + "la_pp_p1": "Anzeige des Live-Stundenplans auf dem Sperrbildschirm", + "la_pp_p2": "Senden von Push-Benachrichtigungen bei Stundenänderungen", + "la_pp_p3": "Synchronisation Ihres Stundenplans auf Ihrem Gerät", + "la_pp_p4": "Sicherstellung der Montagmorgen-Benachrichtigungen auch nach der wöchentlichen Datenbankbereinigung", + "la_pp_no_third_party": "Wir geben Ihre Daten nicht an Dritte weiter und verwenden sie nicht für Marketingzwecke.", + "la_pp_rights_title": "Ihre Rechte", + "la_pp_rights_intro": "Gemäß DSGVO haben Sie folgende Rechte:", + "la_pp_r1": "Recht auf Auskunft: Sie können die in dieser Datenschutzrichtlinie gespeicherten Datentypen einsehen.", + "la_pp_r2": "Recht auf Löschung: Durch Deaktivierung der Live Activity-Funktion werden alle funktionsbezogenen Daten (Gerätekennungen, Stundenplan) sofort und dauerhaft von unseren Servern gelöscht.", + "la_pp_r3": "Recht auf Berichtigung: Stundenplan-Daten werden im Kréta-System von autorisierten Personen (z.B. Lehrern) geändert.", + "la_pp_r4": "Widerspruchsrecht: Sie können der Datenverarbeitung jederzeit widersprechen, indem Sie die Live Activity-Funktion deaktivieren.", + "la_pp_updated": "Datenschutzrichtlinie zuletzt aktualisiert: November 2025", + "la_pp_contact": "Fragen? Kontaktieren Sie uns unter support@firka.app.", "fonts": "Schriftarten", "font_family": "Schriftfamilie", "calendar_sync": "Kalender-Synchronisation", From 86d90adf2b8d7ea1adf83f21debb18a0e9a2b2b7 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sat, 7 Mar 2026 13:09:50 +0100 Subject: [PATCH 24/59] Add live activity consent acceptance handling and update settings model --- refilc/lib/database/init.dart | 1 + refilc/lib/models/settings.dart | 12 ++++++++++++ .../settings/live_activity_consent_dialog.dart | 15 +++++++++++---- .../screens/settings/submenu/general_screen.dart | 9 +++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/refilc/lib/database/init.dart b/refilc/lib/database/init.dart index e51e91f4..0c98e556 100644 --- a/refilc/lib/database/init.dart +++ b/refilc/lib/database/init.dart @@ -59,6 +59,7 @@ const settingsDB = DatabaseStruct("settings", { "new_popups": int, "unseen_new_features": String, "live_activity_enabled": int, + "live_activity_consent_accepted": int, "cloud_sync_enabled": int, "cloud_sync_token": String, "local_updated_at": String, diff --git a/refilc/lib/models/settings.dart b/refilc/lib/models/settings.dart index 9fa05d10..f11b0279 100644 --- a/refilc/lib/models/settings.dart +++ b/refilc/lib/models/settings.dart @@ -111,6 +111,7 @@ class SettingsProvider extends ChangeNotifier { bool _newPopups; List _unseenNewFeatures; bool _liveActivityEnabled; + bool _liveActivityConsentAccepted; bool _cloudSyncEnabled; String _cloudSyncToken; DateTime _updatedAt; @@ -191,6 +192,7 @@ class SettingsProvider extends ChangeNotifier { required bool newPopups, required List unseenNewFeatures, required bool liveActivityEnabled, + required bool liveActivityConsentAccepted, required bool cloudSyncEnabled, required String cloudSyncToken, required DateTime updatedAt, @@ -268,6 +270,7 @@ class SettingsProvider extends ChangeNotifier { _newPopups = newPopups, _unseenNewFeatures = unseenNewFeatures, _liveActivityEnabled = liveActivityEnabled, + _liveActivityConsentAccepted = liveActivityConsentAccepted, _cloudSyncEnabled = cloudSyncEnabled, _cloudSyncToken = cloudSyncToken, _updatedAt = updatedAt, @@ -364,6 +367,7 @@ class SettingsProvider extends ChangeNotifier { newPopups: map['new_popups'] == 1, unseenNewFeatures: jsonDecode(map["unseen_new_features"]).cast(), liveActivityEnabled: map['live_activity_enabled'] == 1, + liveActivityConsentAccepted: map['live_activity_consent_accepted'] == 1, cloudSyncEnabled: map['cloud_sync_enabled'] == 1, cloudSyncToken: map['cloud_sync_token'], updatedAt: DateTime.tryParse(map['local_updated_at']) ?? DateTime.now(), @@ -448,6 +452,7 @@ class SettingsProvider extends ChangeNotifier { "new_popups": _newPopups ? 1 : 0, "unseen_new_features": jsonEncode(_unseenNewFeatures), "live_activity_enabled": _liveActivityEnabled ? 1 : 0, + "live_activity_consent_accepted": _liveActivityConsentAccepted ? 1 : 0, "cloud_sync_enabled": _cloudSyncEnabled ? 1 : 0, "cloud_sync_token": _cloudSyncToken, "local_updated_at": _updatedAt.toIso8601String(), @@ -536,6 +541,7 @@ class SettingsProvider extends ChangeNotifier { newPopups: false, unseenNewFeatures: ['live_activity_consent'], liveActivityEnabled: false, + liveActivityConsentAccepted: false, cloudSyncEnabled: false, cloudSyncToken: '', updatedAt: DateTime.now(), @@ -615,6 +621,7 @@ class SettingsProvider extends ChangeNotifier { bool get newPopups => _newPopups; List get unseenNewFeatures => _unseenNewFeatures; bool get liveActivityEnabled => _liveActivityEnabled; + bool get liveActivityConsentAccepted => _liveActivityConsentAccepted; bool get cloudSyncEnabled => _cloudSyncEnabled; String get cloudSyncToken => _cloudSyncToken; DateTime get updatedAt => _updatedAt; @@ -691,6 +698,7 @@ class SettingsProvider extends ChangeNotifier { bool? newPopups, List? unseenNewFeatures, bool? liveActivityEnabled, + bool? liveActivityConsentAccepted, bool? cloudSyncEnabled, String? cloudSyncToken, bool? qTimetableLessonNum, @@ -900,6 +908,9 @@ class SettingsProvider extends ChangeNotifier { LiveCardProvider.hasActivitySettingsChanged = true; } } + if (liveActivityConsentAccepted != null && liveActivityConsentAccepted != _liveActivityConsentAccepted) { + _liveActivityConsentAccepted = liveActivityConsentAccepted; + } if (cloudSyncEnabled != null && cloudSyncEnabled != _cloudSyncEnabled) { _cloudSyncEnabled = cloudSyncEnabled; } @@ -1020,6 +1031,7 @@ class SettingsProvider extends ChangeNotifier { unseenNewFeatures: jsonDecode(map["unseen_new_features"] ?? "[]").cast(), liveActivityEnabled: map['live_activity_enabled'] == 1, + liveActivityConsentAccepted: map['live_activity_consent_accepted'] == 1, cloudSyncEnabled: map['cloud_sync_enabled'] == 1, cloudSyncToken: map['cloud_sync_token'], qTimetableLessonNum: map['q_timetable_lesson_num'] == 1, diff --git a/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart index 76776792..c506244e 100644 --- a/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart +++ b/refilc_mobile_ui/lib/screens/settings/live_activity_consent_dialog.dart @@ -260,10 +260,17 @@ class LiveActivityConsentDialog extends StatelessWidget { final settings = Provider.of(context, listen: false); final unseen = List.from(settings.unseenNewFeatures); unseen.remove('live_activity_consent'); - settings.update( - liveActivityEnabled: accepted, - unseenNewFeatures: unseen, - ); + if (accepted) { + settings.update( + liveActivityEnabled: true, + liveActivityConsentAccepted: true, + unseenNewFeatures: unseen, + ); + } else { + settings.update( + unseenNewFeatures: unseen, + ); + } Navigator.of(context).pop(); } } diff --git a/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart b/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart index 076dd20a..ca7acc45 100644 --- a/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart +++ b/refilc_mobile_ui/lib/screens/settings/submenu/general_screen.dart @@ -13,6 +13,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_feather_icons/flutter_feather_icons.dart'; import 'package:provider/provider.dart'; import 'package:refilc_mobile_ui/screens/settings/settings_screen.i18n.dart'; +import 'package:refilc_mobile_ui/screens/settings/live_activity_consent_dialog.dart'; class MenuGeneralSettings extends StatelessWidget { const MenuGeneralSettings({ @@ -135,6 +136,10 @@ class GeneralSettingsScreenState extends State { PanelButton( padding: const EdgeInsets.only(left: 14.0, right: 6.0), onPressed: () { + if (!settingsProvider.liveActivityEnabled && !settingsProvider.liveActivityConsentAccepted) { + LiveActivityConsentDialog.show(context).then((_) => setState(() {})); + return; + } final newVal = !settingsProvider.liveActivityEnabled; settingsProvider.update(liveActivityEnabled: newVal); if (!newVal) { @@ -163,6 +168,10 @@ class GeneralSettingsScreenState extends State { ), trailing: Switch( onChanged: (v) { + if (v && !settingsProvider.liveActivityConsentAccepted) { + LiveActivityConsentDialog.show(context).then((_) => setState(() {})); + return; + } settingsProvider.update(liveActivityEnabled: v); if (!v) { PlatformChannel.endLiveActivity(); From f2fdd0005d48c029917c3cd4f3c67d1373cd6dc6 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 8 Mar 2026 09:26:57 +0100 Subject: [PATCH 25/59] Add live activity consent check to unseen new features migration --- refilc/lib/database/init.dart | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/refilc/lib/database/init.dart b/refilc/lib/database/init.dart index 0c98e556..0f332001 100644 --- a/refilc/lib/database/init.dart +++ b/refilc/lib/database/init.dart @@ -189,14 +189,18 @@ Future initDB(DatabaseProvider database) async { } // One-time migration: add 'live_activity_consent' to unseen_new_features for existing users + // Only if they haven't already accepted or dismissed it try { - final rows = await db.query('settings', columns: ['unseen_new_features']); + final rows = await db.query('settings', columns: ['unseen_new_features', 'live_activity_consent_accepted']); if (rows.isNotEmpty) { - final raw = rows.first['unseen_new_features'] as String? ?? '[]'; - final list = (jsonDecode(raw) as List).cast(); - if (!list.contains('live_activity_consent')) { - list.add('live_activity_consent'); - await db.update('settings', {'unseen_new_features': jsonEncode(list)}); + final consentAccepted = rows.first['live_activity_consent_accepted'] as int? ?? 0; + if (consentAccepted == 0) { + final raw = rows.first['unseen_new_features'] as String? ?? '[]'; + final list = (jsonDecode(raw) as List).cast(); + if (!list.contains('live_activity_consent')) { + list.add('live_activity_consent'); + await db.update('settings', {'unseen_new_features': jsonEncode(list)}); + } } } } catch (e) { From 36637e889bfbb7d217c373c9f3338f4a1a848d69 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 08:15:26 +0100 Subject: [PATCH 26/59] Refactor activity start condition message for clarity --- refilc/lib/api/providers/live_card_provider.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 42cbf340..3b8218ab 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -363,12 +363,11 @@ class LiveCardProvider extends ChangeNotifier { if (!hasActivityStarted && !hasUserDismissed && nextLesson != null && - nextLesson!.start.difference(now).inMinutes <= 60 && (currentState == LiveCardState.morning || currentState == LiveCardState.afternoon || currentState == LiveCardState.night)) { debugPrint( - "Az első óra előtt állunk, kevesebb mint egy órával. Létrehozás..."); + "Az első óra előtt állunk. Létrehozás..."); hasActivityStarted = true; _createAndSync(); } else if (!hasActivityStarted && From 0046d18f3abd8e9a44baf8745d3ab7877ac2c104 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 08:16:37 +0100 Subject: [PATCH 27/59] Update activity start condition message for clarity and add time constraint --- refilc/lib/api/providers/live_card_provider.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 3b8218ab..609eadab 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -363,11 +363,12 @@ class LiveCardProvider extends ChangeNotifier { if (!hasActivityStarted && !hasUserDismissed && nextLesson != null && + nextLesson!.start.difference(now).inMinutes <= 120 && (currentState == LiveCardState.morning || currentState == LiveCardState.afternoon || currentState == LiveCardState.night)) { debugPrint( - "Az első óra előtt állunk. Létrehozás..."); + "Az első óra előtt állunk, kevesebb mint két órával. Létrehozás..."); hasActivityStarted = true; _createAndSync(); } else if (!hasActivityStarted && From 1ce961eaaa371a0fca798d4e44c5e080b0ce6209 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 08:27:08 +0100 Subject: [PATCH 28/59] Add debug print statement for live activity state and settings --- refilc/lib/api/providers/live_card_provider.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 609eadab..8b303877 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -348,6 +348,10 @@ class LiveCardProvider extends ChangeNotifier { } //LIVE ACTIVITIES + debugPrint("LA DEBUG: state=$currentState, today=${today.length}, " + "current=${currentLesson?.subject.name}, next=${nextLesson?.subject.name}, " + "hasStarted=$hasActivityStarted, dismissed=$hasUserDismissed, " + "enabled=${_settings.liveActivityEnabled}, weekday=${now.weekday}, hour=${now.hour}"); // Guard: if not enabled, stop any running activity and skip if (!_settings.liveActivityEnabled) { From c4945f6ab9455b4d4141939b8ff9af90889b590f Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 08:32:51 +0100 Subject: [PATCH 29/59] Add cleanup flag to prevent dismiss notifications during activity cleanup --- refilc/ios/Runner/public_vars.swift | 2 ++ refilc/ios/livecard/LiveActivityManager.swift | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/refilc/ios/Runner/public_vars.swift b/refilc/ios/Runner/public_vars.swift index 722cc4a5..4019ce74 100644 --- a/refilc/ios/Runner/public_vars.swift +++ b/refilc/ios/Runner/public_vars.swift @@ -11,3 +11,5 @@ var lessonDataDictionary: [String: Any] = [:] var globalLessonData = LessonData(from: lessonDataDictionary) var activityID: String? = "" var activityPushToken: String? = nil +/// Ha true, a monitorActivityState nem küld dismiss notification-t (cleanup közben vagyunk) +var isCleaningUpOldActivities = false diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 5719a373..792012fc 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -32,9 +32,14 @@ final class LiveActivityManager { class func create(completion: @escaping (Bool) -> Void) { Task { // Előző activity-k eltakarítása, hogy ne legyen dupla + // Flag beállítása, hogy a monitorActivityState ne küldjön dismiss notification-t + isCleaningUpOldActivities = true for activity in Activity.activities { await activity.end(nil, dismissalPolicy: .immediate) } + // Kis várakozás, hogy a state update-ek lefussanak + try? await Task.sleep(nanoseconds: 200_000_000) + isCleaningUpOldActivities = false do { let contentState = LiveActivitiesAppAttributes.ContentState( @@ -96,6 +101,11 @@ final class LiveActivityManager { private class func monitorActivityState(activity: Activity) async { for await state in activity.activityStateUpdates { if state == .dismissed || state == .ended { + // Ha cleanup közben vagyunk (create() hívta), ne küldjünk dismiss notification-t + if isCleaningUpOldActivities { + print("Live Activity ended during cleanup - ignoring dismiss") + break + } print("Live Activity dismissed/ended by user or system") activityID = nil activityPushToken = nil From 93d8bef23852355765a88d386cd6011663727e6d Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 08:33:41 +0100 Subject: [PATCH 30/59] Refactor LiveActivityManager and public_vars to improve clarity and remove unused comments --- refilc/ios/Runner/AppDelegate.swift | 7 --- refilc/ios/Runner/public_vars.swift | 8 --- refilc/ios/livecard/LiveActivityManager.swift | 63 +++++++------------ 3 files changed, 21 insertions(+), 57 deletions(-) diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index 997e0114..f9e9c061 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -32,7 +32,6 @@ import Security self?.handleMethodCall(call, result: result) }) - // Activity dismiss figyelése: ha a user swipe-olja, értesítjük Flutter-t NotificationCenter.default.addObserver( forName: NSNotification.Name("LiveActivityDismissed"), object: nil, @@ -44,7 +43,6 @@ import Security ]) } - // Token rotation figyelése: ha az APNs új tokent ad, értesítjük Flutter-t tokenRotationObserver = NotificationCenter.default.addObserver( forName: NSNotification.Name("LiveActivityTokenUpdated"), object: nil, @@ -123,8 +121,6 @@ import Security } } - // MARK: - Keychain device ID - private func getOrCreateDeviceId() -> String { let keychainKey = "refilc.live.device_id" let query: [String: Any] = [ @@ -139,7 +135,6 @@ import Security let existingId = String(data: data, encoding: .utf8) { return existingId } - // Nem létezik – generálunk egyet let newId = UUID().uuidString let addQuery: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, @@ -150,8 +145,6 @@ import Security return newId } - // MARK: - Helpers - private func checkLiveActivityFeatureAvailable() -> Bool { if #available(iOS 16.2, *) { return ActivityAuthorizationInfo().areActivitiesEnabled diff --git a/refilc/ios/Runner/public_vars.swift b/refilc/ios/Runner/public_vars.swift index 4019ce74..b35fe24b 100644 --- a/refilc/ios/Runner/public_vars.swift +++ b/refilc/ios/Runner/public_vars.swift @@ -1,15 +1,7 @@ -// -// public_vars.swift -// Runner -// -// Created by Geryy on 02/05/2024. -// - import Foundation var lessonDataDictionary: [String: Any] = [:] var globalLessonData = LessonData(from: lessonDataDictionary) var activityID: String? = "" var activityPushToken: String? = nil -/// Ha true, a monitorActivityState nem küld dismiss notification-t (cleanup közben vagyunk) var isCleaningUpOldActivities = false diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift index 792012fc..6a83c70b 100644 --- a/refilc/ios/livecard/LiveActivityManager.swift +++ b/refilc/ios/livecard/LiveActivityManager.swift @@ -26,18 +26,12 @@ final class LiveActivityManager { static let shared = LiveActivityManager() var currentActivity: Activity? - /// Létrehozza a Live Activity-t pushType: .token-nel. - /// A completion azonnal meghívódik a létrehozás után (success/fail). - /// A push token később érkezik a pushTokenUpdates-en keresztül. class func create(completion: @escaping (Bool) -> Void) { Task { - // Előző activity-k eltakarítása, hogy ne legyen dupla - // Flag beállítása, hogy a monitorActivityState ne küldjön dismiss notification-t isCleaningUpOldActivities = true for activity in Activity.activities { await activity.end(nil, dismissalPolicy: .immediate) } - // Kis várakozás, hogy a state update-ek lefussanak try? await Task.sleep(nanoseconds: 200_000_000) isCleaningUpOldActivities = false @@ -71,14 +65,10 @@ final class LiveActivityManager { activityID = activity.id print("Live Activity létrehozva. Azonosító: \(activity.id)") - // Azonnal visszatérünk — a LA látszik completion(true) - // Dismiss/end figyelése háttérben Task { await monitorActivityState(activity: activity) } - // Push token figyelése háttérben — az első és a rotation is - // a LiveActivityTokenUpdated notification-ön keresztül megy Flutter felé Task { for await tokenData in activity.pushTokenUpdates { let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined() @@ -97,11 +87,9 @@ final class LiveActivityManager { } } - /// Activity state figyelése: ha a user dismiss-eli vagy véget ér, értesítjük a Flutter-t. private class func monitorActivityState(activity: Activity) async { for await state in activity.activityStateUpdates { if state == .dismissed || state == .ended { - // Ha cleanup közben vagyunk (create() hívta), ne küldjünk dismiss notification-t if isCleaningUpOldActivities { print("Live Activity ended during cleanup - ignoring dismiss") break @@ -113,47 +101,38 @@ final class LiveActivityManager { name: NSNotification.Name("LiveActivityDismissed"), object: nil ) - // Activity formálisan is leállítjuk ha még fut await activity.end(nil, dismissalPolicy: .immediate) break } } } - /// Token rotation figyelése: ha az APNs új tokent ad ki, értesítjük a Flutter oldalt. - /// MEGJEGYZÉS: Már nem használjuk külön — a create() maga figyeli a pushTokenUpdates-t - /// és minden tokent (elsőt is, rotation-t is) a LiveActivityTokenUpdated notification-ön küld. - class func update() { Task { for activity in Activity.activities { - do { - let contentState = LiveActivitiesAppAttributes.ContentState( - color: globalLessonData.color, - icon: globalLessonData.icon, - index: globalLessonData.index, - title: globalLessonData.title, - subtitle: globalLessonData.subtitle, - description: globalLessonData.description, - startDate: globalLessonData.startDate, - endDate: globalLessonData.endDate, - date: globalLessonData.date, - nextSubject: globalLessonData.nextSubject, - nextRoom: globalLessonData.nextRoom - ) + let contentState = LiveActivitiesAppAttributes.ContentState( + color: globalLessonData.color, + icon: globalLessonData.icon, + index: globalLessonData.index, + title: globalLessonData.title, + subtitle: globalLessonData.subtitle, + description: globalLessonData.description, + startDate: globalLessonData.startDate, + endDate: globalLessonData.endDate, + date: globalLessonData.date, + nextSubject: globalLessonData.nextSubject, + nextRoom: globalLessonData.nextRoom + ) - let activityContent = ActivityContent( - state: contentState, - staleDate: globalLessonData.endDate, - relevanceScore: 0 - ) + let activityContent = ActivityContent( + state: contentState, + staleDate: globalLessonData.endDate, + relevanceScore: 0 + ) - await activity.update(activityContent) - activityID = activity.id - print("Live Activity frissítve. Azonosító: \(activity.id)") - } catch { - print("Hiba történt a Live Activity frissítésekor: \(error)") - } + await activity.update(activityContent) + activityID = activity.id + print("Live Activity frissítve. Azonosító: \(activity.id)") } } } From 439c98dfd93547759a7cda1b4b93787b00bc0979 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:02:07 +0100 Subject: [PATCH 31/59] Refactor lesson data handling in ServerSyncProvider to include breaks between lessons and improve clarity --- .../lib/api/providers/live_card_provider.dart | 31 +----------- .../liveactivity/server_sync_provider.dart | 50 +++++++++++++------ 2 files changed, 36 insertions(+), 45 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 8b303877..f0331026 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -34,7 +34,6 @@ class LiveCardProvider extends ChangeNotifier { Lesson? prevLesson; List? nextLessons; - // new variables static bool hasActivityStarted = false; static bool hasDayEnd = false; static bool hasUserDismissed = false; @@ -43,7 +42,6 @@ class LiveCardProvider extends ChangeNotifier { // ignore: non_constant_identifier_names static Map LAData = {}; static DateTime? now; - // LiveCardState currentState = LiveCardState.empty; // ignore: unused_field @@ -66,12 +64,8 @@ class LiveCardProvider extends ChangeNotifier { ? Duration(seconds: settings.bellDelay) : Duration.zero; - // Token figyelése: amikor az APNs tokent ad (első vagy rotation), regisztráljuk a szerverrel PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) { - if (!_settings.liveActivityEnabled) { - debugPrint("Push token érkezett, de Live Activity nincs engedélyezve - skip"); - return; - } + if (!_settings.liveActivityEnabled) return; debugPrint("Push token érkezett: $pushToken"); serverSync.registerAndSync( deviceId: deviceId, @@ -82,7 +76,6 @@ class LiveCardProvider extends ChangeNotifier { ); }; - // Ha a user dismiss-eli a Live Activity-t (swipe), értesítjük a szervert PlatformChannel.onActivityDismissed = (deviceId) { debugPrint("Live Activity dismissed - unregistering from server"); serverSync.forceUnregister(deviceId); @@ -93,9 +86,7 @@ class LiveCardProvider extends ChangeNotifier { update(); } - // Debugging static DateTime _now() { - // return DateTime(2023, 9, 27, 9, 30); return DateTime.now(); } @@ -116,8 +107,6 @@ class LiveCardProvider extends ChangeNotifier { } Map toMap() { - // print("LIVE ACTIVITY COLOR BELOW:"); - // print(_settings.liveActivityColor.toHexString().substring(2)); String color = '#${_settings.liveActivityColor.toHexString().substring(2)}'; switch (currentState) { @@ -281,8 +270,6 @@ class LiveCardProvider extends ChangeNotifier { storeFirstRunDate = now; } - // Filter cancelled lessons #20 - // Filter label lessons #128 today = today .where((lesson) => lesson.status?.name != "Elmaradt" && @@ -291,7 +278,6 @@ class LiveCardProvider extends ChangeNotifier { .toList(); if (today.isNotEmpty) { - // sort today.sort((a, b) => a.start.compareTo(b.start)); final _lesson = today.firstWhere( @@ -347,13 +333,10 @@ class LiveCardProvider extends ChangeNotifier { currentState = LiveCardState.empty; } - //LIVE ACTIVITIES debugPrint("LA DEBUG: state=$currentState, today=${today.length}, " "current=${currentLesson?.subject.name}, next=${nextLesson?.subject.name}, " "hasStarted=$hasActivityStarted, dismissed=$hasUserDismissed, " "enabled=${_settings.liveActivityEnabled}, weekday=${now.weekday}, hour=${now.hour}"); - - // Guard: if not enabled, stop any running activity and skip if (!_settings.liveActivityEnabled) { if (hasActivityStarted) { debugPrint("Live Activity nincs engedélyezve, de fut – leállítás..."); @@ -363,7 +346,6 @@ class LiveCardProvider extends ChangeNotifier { } } else { - //CREATE if (!hasActivityStarted && !hasUserDismissed && nextLesson != null && @@ -384,7 +366,6 @@ class LiveCardProvider extends ChangeNotifier { hasActivityStarted = true; _createAndSync(); } - // Fake mód: mindig hozzuk létre a Live Activity-t ha nincs elindítva else if (!hasActivityStarted && _settings.developerMode && _settings.devLiveFakeLessons && @@ -395,7 +376,6 @@ class LiveCardProvider extends ChangeNotifier { _createAndSync(); } - //UPDATE else if (hasActivityStarted) { if (hasActivitySettingsChanged) { debugPrint("Valamelyik beállítás megváltozott. Frissítés..."); @@ -421,10 +401,7 @@ class LiveCardProvider extends ChangeNotifier { } } - //END - // Fake módban ne fejezzük be a Live Activity-t if (_settings.developerMode && _settings.devLiveFakeLessons) { - // skip end logic in fake mode } else if ((currentState == LiveCardState.afternoon || currentState == LiveCardState.morning || currentState == LiveCardState.night) && @@ -476,8 +453,6 @@ class LiveCardProvider extends ChangeNotifier { if (!_settings.developerMode || !_settings.devLiveFakeLessons) { return real; } - // Fake mód: ha vannak valódi órák, a fake órákat utánuk rakjuk - // DE: ha az utolsó valódi óra már véget ért, a fake-ek a jelen idő köré kerülnek if (real.isNotEmpty) { final sorted = List.from(real) ..sort((a, b) => a.end.compareTo(b.end)); @@ -485,17 +460,15 @@ class LiveCardProvider extends ChangeNotifier { final now = _now(); final nextIndex = sorted.length; if (lastEnd.isBefore(now)) { - // Az órák már véget értek — fake órákat a jelen idő köré return [...real, ..._generateFakeLessons(startIndex: nextIndex)]; } - // Van még óra — fake órákat az utolsó után + final fakeStart = lastEnd.add(const Duration(minutes: 10)); return [...real, ..._generateFakeLessons(baseStart: fakeStart, startIndex: nextIndex)]; } return _generateFakeLessons(); } - /// Generál fake órákat a jelenlegi idő köré, hogy a Live Activity tesztelhető legyen. static List _generateFakeLessons({DateTime? baseStart, int startIndex = 0}) { final now = _now(); final start0 = baseStart ?? now.subtract(const Duration(minutes: 10)); diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index bccaa42c..1c0651eb 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -32,7 +32,6 @@ class ServerSyncProvider { } } - /// Token rotation esetén frissíti a tokent a szerveren. Future refreshToken({ required String pushToken, required String bundleId, @@ -85,18 +84,38 @@ class ServerSyncProvider { final dateStr = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}'; - final lessonsJson = lessons - .map((l) => { - 'index': l.lessonIndex.toString(), - 'subject': l.subject.renamedTo ?? - ShortSubject.resolve(subject: l.subject).capital(), - 'icon': SubjectIcon.resolveName(subject: l.subject), - 'room': l.room.replaceAll('_', ' '), - 'description': l.description, - 'start': l.start.millisecondsSinceEpoch, - 'end': l.end.millisecondsSinceEpoch, - }) - .toList(); + final entries = >[]; + + for (int i = 0; i < lessons.length; i++) { + final l = lessons[i]; + entries.add({ + 'type': 'lesson', + 'index': l.lessonIndex.toString(), + 'subject': l.subject.renamedTo ?? + ShortSubject.resolve(subject: l.subject).capital(), + 'icon': SubjectIcon.resolveName(subject: l.subject), + 'room': l.room.replaceAll('_', ' '), + 'description': l.description, + 'start': l.start.millisecondsSinceEpoch, + 'end': l.end.millisecondsSinceEpoch, + }); + + if (i < lessons.length - 1) { + final next = lessons[i + 1]; + if (l.end.isBefore(next.start)) { + entries.add({ + 'type': 'break', + 'start': l.end.millisecondsSinceEpoch, + 'end': next.start.millisecondsSinceEpoch, + 'nextSubject': next.subject.renamedTo ?? + ShortSubject.resolve(subject: next.subject).capital(), + 'nextIcon': SubjectIcon.resolveName(subject: next.subject), + 'nextRoom': next.room.replaceAll('_', ' '), + 'nextIndex': next.lessonIndex.toString(), + }); + } + } + } final response = await http.post( Uri.parse('$_baseUrl/schedule'), @@ -104,13 +123,13 @@ class ServerSyncProvider { body: jsonEncode({ 'device_id': deviceId, 'date': dateStr, - 'lessons': lessonsJson, + 'lessons': entries, }), ).timeout(const Duration(seconds: 10)); if (response.statusCode != 200 && response.statusCode != 201) { debugPrint('ServerSync schedule hiba: ${response.statusCode} ${response.body}'); } else { - debugPrint('ServerSync: ${lessons.length} óra feltöltve ($dateStr)'); + debugPrint('ServerSync: ${entries.length} elem feltöltve ($dateStr)'); } } catch (e) { debugPrint('ServerSync schedule kivétel: $e'); @@ -122,7 +141,6 @@ class ServerSyncProvider { await forceUnregister(_deviceId!); } - /// Unregister egy adott deviceId-vel, akkor is ha a _deviceId nincs beállítva (pl. app restart után). Future forceUnregister(String deviceId) async { try { final response = await http.post( From 7e254654d184da8b9ac4727909a321e74809a1c9 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:14:37 +0100 Subject: [PATCH 32/59] Update debug message for activity dismissal to clarify user action --- refilc/lib/api/providers/live_card_provider.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index f0331026..844d3efa 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -77,8 +77,7 @@ class LiveCardProvider extends ChangeNotifier { }; PlatformChannel.onActivityDismissed = (deviceId) { - debugPrint("Live Activity dismissed - unregistering from server"); - serverSync.forceUnregister(deviceId); + debugPrint("Live Activity dismissed by user"); hasActivityStarted = false; hasUserDismissed = true; }; From 0a3d0183f25cb413e53f3f19ab721d75963cab5e Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:15:47 +0100 Subject: [PATCH 33/59] Add activity creation state management to prevent dismiss notifications during creation --- refilc/lib/api/providers/live_card_provider.dart | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 844d3efa..45ae1eb5 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -37,6 +37,7 @@ class LiveCardProvider extends ChangeNotifier { static bool hasActivityStarted = false; static bool hasDayEnd = false; static bool hasUserDismissed = false; + static bool _isCreating = false; static DateTime? storeFirstRunDate; static bool hasActivitySettingsChanged = false; // ignore: non_constant_identifier_names @@ -77,7 +78,12 @@ class LiveCardProvider extends ChangeNotifier { }; PlatformChannel.onActivityDismissed = (deviceId) { + if (_isCreating) { + debugPrint("Live Activity dismiss ignored (create in progress)"); + return; + } debugPrint("Live Activity dismissed by user"); + serverSync.forceUnregister(deviceId); hasActivityStarted = false; hasUserDismissed = true; }; @@ -430,7 +436,9 @@ class LiveCardProvider extends ChangeNotifier { } Future _createAndSync() async { + _isCreating = true; final result = await PlatformChannel.createLiveActivity(toMap()); + _isCreating = false; if (result != null && result['success'] == 'true') { debugPrint("Live Activity létrehozva, várunk a push tokenre..."); } else { From 70ada25915a14cdd0394111c926667bfccf7001e Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:25:17 +0100 Subject: [PATCH 34/59] Remove unused activity creation flag and simplify dismissal logic in LiveCardProvider --- refilc/lib/api/providers/live_card_provider.dart | 8 -------- 1 file changed, 8 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 45ae1eb5..844d3efa 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -37,7 +37,6 @@ class LiveCardProvider extends ChangeNotifier { static bool hasActivityStarted = false; static bool hasDayEnd = false; static bool hasUserDismissed = false; - static bool _isCreating = false; static DateTime? storeFirstRunDate; static bool hasActivitySettingsChanged = false; // ignore: non_constant_identifier_names @@ -78,12 +77,7 @@ class LiveCardProvider extends ChangeNotifier { }; PlatformChannel.onActivityDismissed = (deviceId) { - if (_isCreating) { - debugPrint("Live Activity dismiss ignored (create in progress)"); - return; - } debugPrint("Live Activity dismissed by user"); - serverSync.forceUnregister(deviceId); hasActivityStarted = false; hasUserDismissed = true; }; @@ -436,9 +430,7 @@ class LiveCardProvider extends ChangeNotifier { } Future _createAndSync() async { - _isCreating = true; final result = await PlatformChannel.createLiveActivity(toMap()); - _isCreating = false; if (result != null && result['success'] == 'true') { debugPrint("Live Activity létrehozva, várunk a push tokenre..."); } else { From f524019779598572ea1c53e441b99920d0ccb3e3 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:28:49 +0100 Subject: [PATCH 35/59] Add break entry fields in lesson filtering and remove unused imports in sync provider --- .../providers/liveactivity/server_sync_provider.dart | 5 +++++ refilc/lib/api/providers/sync.dart | 10 ---------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index 1c0651eb..f3b52cc0 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -105,6 +105,11 @@ class ServerSyncProvider { if (l.end.isBefore(next.start)) { entries.add({ 'type': 'break', + 'index': '', + 'subject': 'Szünet', + 'icon': 'cup.and.saucer', + 'room': '', + 'description': '', 'start': l.end.millisecondsSinceEpoch, 'end': next.start.millisecondsSinceEpoch, 'nextSubject': next.subject.renamedTo ?? diff --git a/refilc/lib/api/providers/sync.dart b/refilc/lib/api/providers/sync.dart index eb310a9a..d60e930e 100644 --- a/refilc/lib/api/providers/sync.dart +++ b/refilc/lib/api/providers/sync.dart @@ -23,8 +23,6 @@ import 'package:flutter/widgets.dart'; import 'package:provider/provider.dart'; import 'package:home_widget/home_widget.dart'; -import 'live_card_provider.dart'; -import 'liveactivity/platform_channel.dart'; // Mutex bool lock = false; @@ -148,16 +146,8 @@ Future syncAll(BuildContext context) async { } return Future.wait(tasks).then((value) { - // Unlock lock = false; - if (Platform.isIOS && LiveCardProvider.hasActivityStarted == true) { - PlatformChannel.endLiveActivity(); - LiveCardProvider.serverSync.unregister(); - LiveCardProvider.hasActivityStarted = false; - } - - // Update Widget if (Platform.isAndroid) updateWidget(); }); } From 649381ebbfe899bcafb0b2298a6228bbf5155937 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:30:32 +0100 Subject: [PATCH 36/59] Remove redundant debug print statements in LiveCardProvider to streamline logging --- refilc/lib/api/providers/live_card_provider.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 844d3efa..1f36eeac 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -332,10 +332,7 @@ class LiveCardProvider extends ChangeNotifier { currentState = LiveCardState.empty; } - debugPrint("LA DEBUG: state=$currentState, today=${today.length}, " - "current=${currentLesson?.subject.name}, next=${nextLesson?.subject.name}, " - "hasStarted=$hasActivityStarted, dismissed=$hasUserDismissed, " - "enabled=${_settings.liveActivityEnabled}, weekday=${now.weekday}, hour=${now.hour}"); + if (!_settings.liveActivityEnabled) { if (hasActivityStarted) { debugPrint("Live Activity nincs engedélyezve, de fut – leállítás..."); From 225e75e8d231912cb63c9f53827fef3ea0b646f0 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:31:27 +0100 Subject: [PATCH 37/59] Add forceUnregister call on activity dismissal to ensure proper cleanup --- refilc/lib/api/providers/live_card_provider.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 1f36eeac..b3178c42 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -78,6 +78,7 @@ class LiveCardProvider extends ChangeNotifier { PlatformChannel.onActivityDismissed = (deviceId) { debugPrint("Live Activity dismissed by user"); + serverSync.forceUnregister(deviceId); hasActivityStarted = false; hasUserDismissed = true; }; From 96ebd10ed187377ff5e70dfb15eccb2e2cd32c07 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:31:46 +0100 Subject: [PATCH 38/59] Implement device unregistration on application termination --- refilc/ios/Runner/AppDelegate.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift index f9e9c061..20a4b32d 100644 --- a/refilc/ios/Runner/AppDelegate.swift +++ b/refilc/ios/Runner/AppDelegate.swift @@ -63,6 +63,8 @@ import Security } override func applicationWillTerminate(_ application: UIApplication) { + let deviceId = getOrCreateDeviceId() + unregisterFromServer(deviceId: deviceId) if #available(iOS 16.2, *) { LiveActivityManager.stop() } @@ -71,6 +73,19 @@ import Security } } + private func unregisterFromServer(deviceId: String) { + guard let url = URL(string: "https://legacy-la.devbeni.lol/unregister") else { return } + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try? JSONSerialization.data(withJSONObject: ["device_id": deviceId]) + let semaphore = DispatchSemaphore(value: 0) + URLSession.shared.dataTask(with: request) { _, _, _ in + semaphore.signal() + }.resume() + _ = semaphore.wait(timeout: .now() + 3) + } + private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if call.method == "createLiveActivity" { guard let args = call.arguments as? [String: Any] else { From 9bafd2647fbcf2cd89779322e2dc1cd483379f55 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 09:35:01 +0100 Subject: [PATCH 39/59] Enhance lesson end detection logic in LiveCardProvider to ensure proper activity termination --- refilc/lib/api/providers/live_card_provider.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index b3178c42..2e14bf7b 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -412,7 +412,9 @@ class LiveCardProvider extends ChangeNotifier { } else if (hasActivityStarted && !hasDayEnd && nextLesson == null && - now.isAfter(prevLesson!.end)) { + prevLesson != null && + now.isAfter(prevLesson!.end) && + today.every((l) => l.end.isBefore(now))) { debugPrint("Az utolsó óra véget ért. Befejezés..."); PlatformChannel.endLiveActivity(); serverSync.unregister(); From 5cc3d3d38a36d68c7cb7fec58bcd3611a161c570 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 9 Mar 2026 23:07:16 +0100 Subject: [PATCH 40/59] Refactor lesson display logic in LockScreenLiveActivityView for improved clarity and efficiency --- refilc/ios/livecard/livecard.swift | 28 ++- .../lib/api/providers/live_card_provider.dart | 196 ++++++++++-------- 2 files changed, 135 insertions(+), 89 deletions(-) diff --git a/refilc/ios/livecard/livecard.swift b/refilc/ios/livecard/livecard.swift index 799c623a..251073cb 100644 --- a/refilc/ios/livecard/livecard.swift +++ b/refilc/ios/livecard/livecard.swift @@ -51,6 +51,18 @@ extension Color { struct LockScreenLiveActivityView: View { let context: ActivityViewContext + private var hasNextLesson: Bool { + !context.state.nextSubject.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var nextLessonLine: String { + if context.state.nextRoom.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return context.state.nextSubject + } + + return "\(context.state.nextSubject) - \(context.state.nextRoom)" + } + var body: some View { HStack(alignment: .center, spacing: 0) { // Ikon @@ -84,12 +96,12 @@ struct LockScreenLiveActivityView: View { } // Következő óra - if !context.state.nextSubject.isEmpty && !context.state.nextRoom.isEmpty { + if hasNextLesson { HStack(spacing: 4) { Image(systemName: "arrow.right") .font(.system(size: 8, weight: .semibold)) .foregroundStyle(.secondary) - Text("\(context.state.nextSubject) - \(context.state.nextRoom)") + Text(nextLessonLine) .font(.system(size: 12)) .foregroundStyle(.secondary) } @@ -204,14 +216,18 @@ struct LiveCardWidget: Widget { Spacer(minLength: 2) - if(context.state.nextRoom != "" && context.state.nextSubject != "") { + if(!context.state.nextSubject.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) { Text("Következő óra és terem:") .font(.system(size: 14)) .padding(.trailing, -45) Spacer(minLength: 2) - - Text("\(context.state.nextSubject) - \(context.state.nextRoom)") - .modifier(DynamicFontSizeModifier(text: "\(context.state.nextSubject) - \(context.state.nextRoom)")) + + let nextLessonLine = context.state.nextRoom.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? context.state.nextSubject + : "\(context.state.nextSubject) - \(context.state.nextRoom)" + + Text(nextLessonLine) + .modifier(DynamicFontSizeModifier(text: nextLessonLine)) .padding(.trailing, 35) } else { Text("Ez az utolsó óra! Kitartást!") diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 2e14bf7b..61751295 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -38,6 +38,7 @@ class LiveCardProvider extends ChangeNotifier { static bool hasDayEnd = false; static bool hasUserDismissed = false; static DateTime? storeFirstRunDate; + static DateTime? _lastProcessedDay; static bool hasActivitySettingsChanged = false; // ignore: non_constant_identifier_names static Map LAData = {}; @@ -71,7 +72,8 @@ class LiveCardProvider extends ChangeNotifier { deviceId: deviceId, pushToken: pushToken, bundleId: bundleId, - liveActivityColor: '#${settings.liveActivityColor.toHexString().substring(2)}', + liveActivityColor: + '#${settings.liveActivityColor.toHexString().substring(2)}', todayLessons: _today(_timetable), ); }; @@ -262,6 +264,12 @@ class LiveCardProvider extends ChangeNotifier { : Duration.zero; DateTime now = _now().add(_delay); + _resetDayScopedState(now); + + currentLesson = null; + nextLesson = null; + prevLesson = null; + nextLessons = null; if ((currentState == LiveCardState.morning || currentState == LiveCardState.afternoon || @@ -323,8 +331,9 @@ class LiveCardProvider extends ChangeNotifier { } else if (now.hour >= 20) { currentState = LiveCardState.night; } else if (now.hour >= 5 && now.hour <= 10) { - if (nextLesson == null || ((now.weekday == 6 || now.weekday == 7) && - !(_settings.developerMode && _settings.devLiveFakeLessons))) { + if (nextLesson == null || + ((now.weekday == 6 || now.weekday == 7) && + !(_settings.developerMode && _settings.devLiveFakeLessons))) { currentState = LiveCardState.empty; } else { currentState = LiveCardState.morning; @@ -333,7 +342,6 @@ class LiveCardProvider extends ChangeNotifier { currentState = LiveCardState.empty; } - if (!_settings.liveActivityEnabled) { if (hasActivityStarted) { debugPrint("Live Activity nincs engedélyezve, de fut – leállítás..."); @@ -342,87 +350,88 @@ class LiveCardProvider extends ChangeNotifier { hasActivityStarted = false; } } else { - - if (!hasActivityStarted && - !hasUserDismissed && - nextLesson != null && - nextLesson!.start.difference(now).inMinutes <= 120 && - (currentState == LiveCardState.morning || - currentState == LiveCardState.afternoon || - currentState == LiveCardState.night)) { - debugPrint( - "Az első óra előtt állunk, kevesebb mint két órával. Létrehozás..."); - hasActivityStarted = true; - _createAndSync(); - } else if (!hasActivityStarted && - !hasUserDismissed && - ((currentState == LiveCardState.duringLesson && - currentLesson != null) || - currentState == LiveCardState.duringBreak)) { - debugPrint("Óra van, vagy szünet, de nincs LiveActivity. létrehozás..."); - hasActivityStarted = true; - _createAndSync(); - } - else if (!hasActivityStarted && - _settings.developerMode && - _settings.devLiveFakeLessons && - today.isNotEmpty) { - debugPrint("Fake mód: Live Activity létrehozás..."); - hasActivityStarted = true; - hasUserDismissed = false; - _createAndSync(); - } - - else if (hasActivityStarted) { - if (hasActivitySettingsChanged) { - debugPrint("Valamelyik beállítás megváltozott. Frissítés..."); - PlatformChannel.updateLiveActivity(toMap()); - hasActivitySettingsChanged = false; - } else if (nextLesson != null || currentLesson != null) { - bool afterPrevLessonEnd = prevLesson != null && - now - .subtract(const Duration(seconds: 1)) - .isBefore(prevLesson!.end) && - now.isAfter(prevLesson!.end); - - bool afterCurrentLessonStart = currentLesson != null && - now - .subtract(const Duration(seconds: 1)) - .isBefore(currentLesson!.start) && - now.isAfter(currentLesson!.start); - if (afterPrevLessonEnd || afterCurrentLessonStart) { - debugPrint( - "Óra kezdete/vége után 1 másodperccel vagyunk. Frissítés..."); + if (!hasActivityStarted && + !hasUserDismissed && + nextLesson != null && + nextLesson!.start.difference(now).inMinutes <= 120 && + (currentState == LiveCardState.morning || + currentState == LiveCardState.afternoon || + currentState == LiveCardState.night)) { + debugPrint( + "Az első óra előtt állunk, kevesebb mint két órával. Létrehozás..."); + hasActivityStarted = true; + _createAndSync(); + } else if (!hasActivityStarted && + !hasUserDismissed && + ((currentState == LiveCardState.duringLesson && + currentLesson != null) || + currentState == LiveCardState.duringBreak)) { + debugPrint( + "Óra van, vagy szünet, de nincs LiveActivity. létrehozás..."); + hasActivityStarted = true; + _createAndSync(); + } else if (!hasActivityStarted && + _settings.developerMode && + _settings.devLiveFakeLessons && + today.isNotEmpty) { + debugPrint("Fake mód: Live Activity létrehozás..."); + hasActivityStarted = true; + hasUserDismissed = false; + _createAndSync(); + } else if (hasActivityStarted) { + if (hasActivitySettingsChanged) { + debugPrint("Valamelyik beállítás megváltozott. Frissítés..."); PlatformChannel.updateLiveActivity(toMap()); + hasActivitySettingsChanged = false; + } else if (nextLesson != null || currentLesson != null) { + bool afterPrevLessonEnd = prevLesson != null && + now + .subtract(const Duration(seconds: 1)) + .isBefore(prevLesson!.end) && + now.isAfter(prevLesson!.end); + + bool afterCurrentLessonStart = currentLesson != null && + now + .subtract(const Duration(seconds: 1)) + .isBefore(currentLesson!.start) && + now.isAfter(currentLesson!.start); + if (afterPrevLessonEnd || afterCurrentLessonStart) { + debugPrint( + "Óra kezdete/vége után 1 másodperccel vagyunk. Frissítés..."); + PlatformChannel.updateLiveActivity(toMap()); + } } } - } - - if (_settings.developerMode && _settings.devLiveFakeLessons) { - } else if ((currentState == LiveCardState.afternoon || - currentState == LiveCardState.morning || - currentState == LiveCardState.night) && - hasActivityStarted && - nextLesson != null && - nextLesson!.start.difference(now).inMinutes > 60) { - debugPrint("Több, mint 1 óra van az első óráig. Befejezés..."); - PlatformChannel.endLiveActivity(); - serverSync.unregister(); - hasActivityStarted = false; - } else if (hasActivityStarted && - !hasDayEnd && - nextLesson == null && - prevLesson != null && - now.isAfter(prevLesson!.end) && - today.every((l) => l.end.isBefore(now))) { - debugPrint("Az utolsó óra véget ért. Befejezés..."); - PlatformChannel.endLiveActivity(); - serverSync.unregister(); - hasDayEnd = true; - hasActivityStarted = false; - hasUserDismissed = false; - } + if (_settings.developerMode && _settings.devLiveFakeLessons) { + } else if ((currentState == LiveCardState.afternoon || + currentState == LiveCardState.morning || + currentState == LiveCardState.night) && + hasActivityStarted && + nextLesson != null && + nextLesson!.start.difference(now).inMinutes > 60) { + debugPrint("Több, mint 1 óra van az első óráig. Befejezés..."); + PlatformChannel.endLiveActivity(); + serverSync.unregister(); + hasActivityStarted = false; + } else if (hasActivityStarted && + !hasDayEnd && + nextLesson == null && + prevLesson != null && + now.isAfter(prevLesson!.end) && + today.every((l) => l.end.isBefore(now))) { + debugPrint("Az utolsó óra véget ért. Befejezés..."); + PlatformChannel.endLiveActivity(); + serverSync.unregister(); + hasDayEnd = true; + hasActivityStarted = false; + hasUserDismissed = false; + } else if (hasActivityStarted && currentState == LiveCardState.empty) { + debugPrint("Nincs több megjeleníthető mai állapot. Befejezés..."); + PlatformChannel.endLiveActivity(); + serverSync.unregister(); + hasActivityStarted = false; + } } // end of liveActivityEnabled else block LAData = toMap(); @@ -445,6 +454,23 @@ class LiveCardProvider extends ChangeNotifier { bool _sameDate(DateTime a, DateTime b) => (a.year == b.year && a.month == b.month && a.day == b.day); + void _resetDayScopedState(DateTime now) { + if (_lastProcessedDay != null && _sameDate(_lastProcessedDay!, now)) { + return; + } + + if (hasActivityStarted) { + PlatformChannel.endLiveActivity(); + serverSync.unregister(); + } + + _lastProcessedDay = DateTime(now.year, now.month, now.day); + hasActivityStarted = false; + hasDayEnd = false; + hasUserDismissed = false; + storeFirstRunDate = null; + } + List _today(TimetableProvider p) { final real = (p.getWeek(Week.current()) ?? []) .where((l) => _sameDate(l.date, _now())) @@ -463,12 +489,16 @@ class LiveCardProvider extends ChangeNotifier { } final fakeStart = lastEnd.add(const Duration(minutes: 10)); - return [...real, ..._generateFakeLessons(baseStart: fakeStart, startIndex: nextIndex)]; + return [ + ...real, + ..._generateFakeLessons(baseStart: fakeStart, startIndex: nextIndex) + ]; } return _generateFakeLessons(); } - static List _generateFakeLessons({DateTime? baseStart, int startIndex = 0}) { + static List _generateFakeLessons( + {DateTime? baseStart, int startIndex = 0}) { final now = _now(); final start0 = baseStart ?? now.subtract(const Duration(minutes: 10)); From 10f24af7e49497a3f2d8911b60f1a1d142f33f37 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Tue, 10 Mar 2026 07:04:10 +0100 Subject: [PATCH 41/59] Update lesson start time check to 2 hours in LiveCardProvider for improved activity termination logic --- refilc/lib/api/providers/live_card_provider.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 61751295..2e9e0f41 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -409,8 +409,8 @@ class LiveCardProvider extends ChangeNotifier { currentState == LiveCardState.night) && hasActivityStarted && nextLesson != null && - nextLesson!.start.difference(now).inMinutes > 60) { - debugPrint("Több, mint 1 óra van az első óráig. Befejezés..."); + nextLesson!.start.difference(now).inMinutes > 120) { + debugPrint("Több, mint 2 óra van az első óráig. Befejezés..."); PlatformChannel.endLiveActivity(); serverSync.unregister(); hasActivityStarted = false; From fc261d40058a28428cb1f11bd8ca177266678c78 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Tue, 10 Mar 2026 07:20:01 +0100 Subject: [PATCH 42/59] Enhance countdown timer display in LockScreenLiveActivityView for improved readability and layout --- refilc/ios/livecard/livecard.swift | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/refilc/ios/livecard/livecard.swift b/refilc/ios/livecard/livecard.swift index 251073cb..7685e910 100644 --- a/refilc/ios/livecard/livecard.swift +++ b/refilc/ios/livecard/livecard.swift @@ -63,6 +63,12 @@ struct LockScreenLiveActivityView: View { return "\(context.state.nextSubject) - \(context.state.nextRoom)" } + private var countdownFont: Font { + // h:mm:ss needs more space than mm:ss + let remaining = max(0, context.state.endDate.timeIntervalSinceNow) + return remaining >= 3600 ? .title3 : .title2 + } + var body: some View { HStack(alignment: .center, spacing: 0) { // Ikon @@ -113,15 +119,19 @@ struct LockScreenLiveActivityView: View { } .padding(.horizontal, 12) .padding(.vertical, 14) + .layoutPriority(0) Spacer(minLength: 4) // Visszaszámláló Text(timerInterval: context.state.date, countsDown: true) .multilineTextAlignment(.trailing) - .frame(width: 75) - .font(.title2) + .frame(minWidth: 86, maxWidth: 100, alignment: .trailing) + .font(countdownFont) .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.75) + .layoutPriority(1) .padding(.trailing, 16) } // .activityBackgroundTint( @@ -242,14 +252,17 @@ struct LiveCardWidget: Widget { } /// Compact - } compactLeading: { + } compactLeading: { Image(systemName: context.state.icon) } compactTrailing: { Text(timerInterval: context.state.date, countsDown: true) .multilineTextAlignment(.center) - .frame(width: 40) + .frame(width: 52) .font(.caption2) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.7) /// Collapsed } minimal: { From b8b996a5d39acb05c27f244420e1eb19e9564d8c Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 11 Mar 2026 09:04:29 +0100 Subject: [PATCH 43/59] Add error handling and timeout logic in KretenLoginWidget for improved user experience --- refilc/pubspec.yaml | 1 - .../lib/screens/login/kreten_login.dart | 97 ++++++++++++++++++- 2 files changed, 95 insertions(+), 3 deletions(-) diff --git a/refilc/pubspec.yaml b/refilc/pubspec.yaml index 53e4db29..6221a066 100644 --- a/refilc/pubspec.yaml +++ b/refilc/pubspec.yaml @@ -69,7 +69,6 @@ dependencies: shake_flutter: ^17.1.0 dependency_overrides: - webview_flutter_wkwebview: 3.17.0 intl: 0.20.2 dev_dependencies: diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 86657b2b..cf957713 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -18,6 +18,8 @@ // ignore_for_file: use_build_context_synchronously +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; @@ -38,6 +40,13 @@ class _KretenLoginWidgetState extends State var loadingPercentage = 0; var currentUrl = ''; bool _hasFadedIn = false; + bool _hasError = false; + String _errorMessage = ''; + bool _hasTimedOut = false; + Timer? _timeoutTimer; + + static const _loginUrl = + 'https://idp.e-kreta.hu/connect/authorize?prompt=login&nonce=wylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU&response_type=code&code_challenge_method=S256&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&code_challenge=HByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ&redirect_uri=https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect&client_id=kreta-ellenorzo-student-mobile-ios&state=refilc_student_mobile'; @override void initState() { @@ -123,15 +132,48 @@ class _KretenLoginWidgetState extends State }); }, onPageFinished: (url) { + _timeoutTimer?.cancel(); setState(() { loadingPercentage = 100; }); }, + onWebResourceError: (error) { + _timeoutTimer?.cancel(); + setState(() { + _hasError = true; + _errorMessage = error.description; + }); + }, )) ..loadRequest( - Uri.parse( - 'https://idp.e-kreta.hu/connect/authorize?prompt=login&nonce=wylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU&response_type=code&code_challenge_method=S256&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&code_challenge=HByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ&redirect_uri=https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect&client_id=kreta-ellenorzo-student-mobile-ios&state=refilc_student_mobile'), // &institute_code=${widget.selectedSchool} + Uri.parse(_loginUrl), // &institute_code=${widget.selectedSchool} ); + + _startTimeoutTimer(); + } + + void _startTimeoutTimer() { + _timeoutTimer?.cancel(); + _timeoutTimer = Timer(const Duration(seconds: 15), () { + if (mounted && loadingPercentage < 100 && !_hasError) { + setState(() { + _hasTimedOut = true; + }); + } + }); + } + + void _retry() { + setState(() { + _hasError = false; + _errorMessage = ''; + _hasTimedOut = false; + loadingPercentage = 0; + _hasFadedIn = false; + }); + _animationController.reset(); + controller.loadRequest(Uri.parse(_loginUrl)); + _startTimeoutTimer(); } // Future loadLoginUrl() async { @@ -143,6 +185,7 @@ class _KretenLoginWidgetState extends State @override void dispose() { + _timeoutTimer?.cancel(); // Step 3: Dispose of the animation controller _animationController.dispose(); super.dispose(); @@ -150,6 +193,56 @@ class _KretenLoginWidgetState extends State @override Widget build(BuildContext context) { + // Show error UI if there was a web resource error or a timeout + if (_hasError || _hasTimedOut) { + return Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.error_outline, + size: 48, + color: Theme.of(context).colorScheme.error, + ), + const SizedBox(height: 16), + Text( + 'A bejelentkezesi oldal nem toltheto be', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 16, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + if (_errorMessage.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + _errorMessage, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 24), + FilledButton.icon( + onPressed: _retry, + icon: const Icon(Icons.refresh), + label: const Text('Probald ujra'), + ), + const SizedBox(height: 12), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Vissza'), + ), + ], + ), + ), + ); + } + // Trigger the fade-in animation only once when loading reaches 100% if (loadingPercentage == 100 && !_hasFadedIn) { _animationController.forward(); // Play the animation From 906e2c97cfc55de3dbba3acdf5bf9fc2ce5f458a Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 11 Mar 2026 09:04:43 +0100 Subject: [PATCH 44/59] Fix Hungarian text typos in KretenLoginWidget for improved clarity --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index cf957713..22c74cc2 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -208,7 +208,7 @@ class _KretenLoginWidgetState extends State ), const SizedBox(height: 16), Text( - 'A bejelentkezesi oldal nem toltheto be', + 'A bejelentkezési oldal nem tölthető be', textAlign: TextAlign.center, style: TextStyle( fontSize: 16, @@ -230,7 +230,7 @@ class _KretenLoginWidgetState extends State FilledButton.icon( onPressed: _retry, icon: const Icon(Icons.refresh), - label: const Text('Probald ujra'), + label: const Text('Próbáld újra'), ), const SizedBox(height: 12), TextButton( From d9268505e4e49c2a3ce82b97a96d74aef4295dfb Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 11 Mar 2026 09:09:22 +0100 Subject: [PATCH 45/59] Fix command formatting in Podfile and update Pods_Runner.framework reference in project.pbxproj for improved compatibility --- refilc/ios/Podfile | 2 +- refilc/ios/Runner.xcodeproj/project.pbxproj | 94 ++++++++++----------- 2 files changed, 48 insertions(+), 48 deletions(-) diff --git a/refilc/ios/Podfile b/refilc/ios/Podfile index 02155af8..32dbe6b5 100644 --- a/refilc/ios/Podfile +++ b/refilc/ios/Podfile @@ -51,7 +51,7 @@ post_install do |installer| bitcode_strip_path = `xcrun --find bitcode_strip`.chop! def strip_bitcode_from_framework(bitcode_strip_path, framework_relative_path) framework_path = File.join(Dir.pwd, framework_relative_path) - command = "#{bitcode_strip_path} #{framework_path} -r -o #{framework_path}" + command = "\"#{bitcode_strip_path}\" \"#{framework_path}\" -r -o \"#{framework_path}\"" puts "Stripping bitcode: #{command}" system(command) end diff --git a/refilc/ios/Runner.xcodeproj/project.pbxproj b/refilc/ios/Runner.xcodeproj/project.pbxproj index 0ddff0df..0b4cdce3 100644 --- a/refilc/ios/Runner.xcodeproj/project.pbxproj +++ b/refilc/ios/Runner.xcodeproj/project.pbxproj @@ -8,6 +8,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 1806187910CAF539F6FC2B28 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CCB997B38F457FB73A5A9B6A /* Pods_Runner.framework */; }; 3127F78D28EAEDE200C2EFB3 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3127F75528EAECC800C2EFB3 /* WidgetKit.framework */; }; 3127F78E28EAEDE200C2EFB3 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3127F75728EAECC800C2EFB3 /* SwiftUI.framework */; }; 3127F79828EAEDE300C2EFB3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3127F79728EAEDE300C2EFB3 /* Assets.xcassets */; }; @@ -15,7 +16,6 @@ 3127F7A428EAEE3D00C2EFB3 /* livecard.intentdefinition in Sources */ = {isa = PBXBuildFile; fileRef = 3127F7A328EAEE3D00C2EFB3 /* livecard.intentdefinition */; }; 3127F7A628EAEE5900C2EFB3 /* livecard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3127F7A528EAEE5900C2EFB3 /* livecard.swift */; }; 3127F7A828EAEE8500C2EFB3 /* lesson_model.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3127F7A728EAEE8500C2EFB3 /* lesson_model.swift */; }; - 373A6ECB5FC71FE9D8AF2EDB /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1F0ADD56276103500A3016C8 /* Pods_Runner.framework */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 4F35BF332BE2FFA30098EF72 /* public_vars.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F35BF322BE2FFA30098EF72 /* public_vars.swift */; }; 4F35BF352BE2FFD80098EF72 /* LiveActivityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F35BF342BE2FFD80098EF72 /* LiveActivityManager.swift */; }; @@ -66,7 +66,7 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 1F0ADD56276103500A3016C8 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F639A73BBD0AA532FD89597 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 3127F73928EAEC3200C2EFB3 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; 3127F73F28EAEC8A00C2EFB3 /* IntentsUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IntentsUI.framework; path = System/Library/Frameworks/IntentsUI.framework; sourceTree = SDKROOT; }; 3127F75528EAECC800C2EFB3 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; }; @@ -83,11 +83,10 @@ 4F35BF342BE2FFD80098EF72 /* LiveActivityManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityManager.swift; sourceTree = ""; }; 4F35BF3B2BE303A40098EF72 /* app_group_directory.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = app_group_directory.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 4F35BF3D2BE304550098EF72 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; - 707F8089D970F81C480F73C4 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 60F3B7142FA88CEF9B740E3C /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 80777CF254888CE770D5F909 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -95,7 +94,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 98578F0EBCC6D3FF8391AAEB /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + CCB997B38F457FB73A5A9B6A /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + DCFCD496781E9C672922FB23 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -112,7 +112,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 373A6ECB5FC71FE9D8AF2EDB /* Pods_Runner.framework in Frameworks */, + 1806187910CAF539F6FC2B28 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -137,10 +137,10 @@ isa = PBXGroup; children = ( 4F35BF3B2BE303A40098EF72 /* app_group_directory.framework */, - 1F0ADD56276103500A3016C8 /* Pods_Runner.framework */, 3127F73F28EAEC8A00C2EFB3 /* IntentsUI.framework */, 3127F75528EAECC800C2EFB3 /* WidgetKit.framework */, 3127F75728EAECC800C2EFB3 /* SwiftUI.framework */, + CCB997B38F457FB73A5A9B6A /* Pods_Runner.framework */, ); name = Frameworks; sourceTree = ""; @@ -148,9 +148,9 @@ 91FEB6212755D596FFFFEC73 /* Pods */ = { isa = PBXGroup; children = ( - 80777CF254888CE770D5F909 /* Pods-Runner.debug.xcconfig */, - 98578F0EBCC6D3FF8391AAEB /* Pods-Runner.release.xcconfig */, - 707F8089D970F81C480F73C4 /* Pods-Runner.profile.xcconfig */, + 60F3B7142FA88CEF9B740E3C /* Pods-Runner.debug.xcconfig */, + 2F639A73BBD0AA532FD89597 /* Pods-Runner.release.xcconfig */, + DCFCD496781E9C672922FB23 /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -229,7 +229,7 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 779338C8D92BCBC36F75F791 /* [CP] Check Pods Manifest.lock */, + FF86224C7703027F130483F3 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -237,8 +237,8 @@ 9705A1C41CF9048500538489 /* Embed Frameworks */, 3127F74F28EAEC8A00C2EFB3 /* Embed Foundation Extensions */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 71459C0EB905E05018E3D78F /* [CP] Embed Pods Frameworks */, - 262089761B766E074256257A /* [CP] Copy Pods Resources */, + F87C348DE3B0D2671B7E9A6F /* [CP] Embed Pods Frameworks */, + B0FC589DBDE68DA21F80B4BB /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -312,23 +312,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 262089761B766E074256257A /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Copy Pods Resources"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -347,11 +330,43 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin\n"; }; - 71459C0EB905E05018E3D78F /* [CP] Embed Pods Frameworks */ = { + 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 12; files = ( ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; + }; + B0FC589DBDE68DA21F80B4BB /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + F87C348DE3B0D2671B7E9A6F /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); @@ -364,7 +379,7 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 779338C8D92BCBC36F75F791 /* [CP] Check Pods Manifest.lock */ = { + FF86224C7703027F130483F3 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -386,21 +401,6 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 12; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ From c301b62d37af244e103b40342b61f4a4e945cc6b Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 11 Mar 2026 11:56:50 +0100 Subject: [PATCH 46/59] Add user change listener and restore user logic in TimetableProvider for improved state management --- .../lib/providers/timetable_provider.dart | 28 +++++++++++++++++++ .../lib/pages/timetable/timetable_page.dart | 1 + 2 files changed, 29 insertions(+) diff --git a/refilc_kreta_api/lib/providers/timetable_provider.dart b/refilc_kreta_api/lib/providers/timetable_provider.dart index 4363fae7..ea7c280e 100644 --- a/refilc_kreta_api/lib/providers/timetable_provider.dart +++ b/refilc_kreta_api/lib/providers/timetable_provider.dart @@ -10,6 +10,7 @@ import 'package:flutter/foundation.dart'; class TimetableProvider with ChangeNotifier { Map> lessons = {}; + String? _activeUserId; late final UserProvider _user; late final DatabaseProvider _database; late final KretaClient _kreta; @@ -21,17 +22,38 @@ class TimetableProvider with ChangeNotifier { }) : _user = user, _database = database, _kreta = kreta { + _user.addListener(_onUserChanged); + restoreUser(); + } + + @override + void dispose() { + _user.removeListener(_onUserChanged); + super.dispose(); + } + + void _onUserChanged() { + final userId = _user.id; + if (userId == _activeUserId) return; + + _activeUserId = userId; + lessons = {}; + notifyListeners(); restoreUser(); } Future restoreUser() async { String? userId = _user.id; + _activeUserId = userId; // Load lessons from the database if (userId != null) { var dbLessons = await _database.userQuery.getLessons(userId: userId); lessons = dbLessons; await convertBySettings(); + } else { + lessons = {}; + notifyListeners(); } } @@ -72,6 +94,12 @@ class TimetableProvider with ChangeNotifier { // Fetches Lessons from the Kreta API then stores them in the database Future fetch({Week? week}) async { if (week == null) return; + + if (_activeUserId != _user.id) { + _activeUserId = _user.id; + await restoreUser(); + } + User? user = _user.user; if (user == null) throw "Cannot fetch Lessons for User null"; diff --git a/refilc_mobile_ui/lib/pages/timetable/timetable_page.dart b/refilc_mobile_ui/lib/pages/timetable/timetable_page.dart index 80b134f7..6c4ee002 100644 --- a/refilc_mobile_ui/lib/pages/timetable/timetable_page.dart +++ b/refilc_mobile_ui/lib/pages/timetable/timetable_page.dart @@ -105,6 +105,7 @@ class TimetablePageState extends State // Update timetable on user change Future _userListener() async { + await Provider.of(context, listen: false).restoreUser(); await Provider.of(context, listen: false).refreshLogin(); if (mounted) _controller.jump(_controller.currentWeek, context: context); } From 0dc6cd915c77a6fff896e221cb64eb8594d40d9e Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Fri, 13 Mar 2026 08:11:02 +0100 Subject: [PATCH 47/59] Add expiration handling in LockScreenLiveActivityView for improved user feedback --- refilc/ios/livecard/livecard.swift | 56 +++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/refilc/ios/livecard/livecard.swift b/refilc/ios/livecard/livecard.swift index 7685e910..ca728751 100644 --- a/refilc/ios/livecard/livecard.swift +++ b/refilc/ios/livecard/livecard.swift @@ -51,6 +51,10 @@ extension Color { struct LockScreenLiveActivityView: View { let context: ActivityViewContext + private var isExpired: Bool { + context.state.endDate <= Date() + } + private var hasNextLesson: Bool { !context.state.nextSubject.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } @@ -124,15 +128,26 @@ struct LockScreenLiveActivityView: View { Spacer(minLength: 4) // Visszaszámláló - Text(timerInterval: context.state.date, countsDown: true) - .multilineTextAlignment(.trailing) - .frame(minWidth: 86, maxWidth: 100, alignment: .trailing) - .font(countdownFont) - .monospacedDigit() - .lineLimit(1) - .minimumScaleFactor(0.75) - .layoutPriority(1) - .padding(.trailing, 16) + if isExpired { + Text("Vége") + .multilineTextAlignment(.trailing) + .frame(minWidth: 86, maxWidth: 100, alignment: .trailing) + .font(.headline) + .lineLimit(1) + .minimumScaleFactor(0.75) + .layoutPriority(1) + .padding(.trailing, 16) + } else { + Text(timerInterval: context.state.date, countsDown: true) + .multilineTextAlignment(.trailing) + .frame(minWidth: 86, maxWidth: 100, alignment: .trailing) + .font(countdownFont) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.75) + .layoutPriority(1) + .padding(.trailing, 16) + } } // .activityBackgroundTint( // context.state.color != "#676767" @@ -256,13 +271,22 @@ struct LiveCardWidget: Widget { Image(systemName: context.state.icon) } compactTrailing: { - Text(timerInterval: context.state.date, countsDown: true) - .multilineTextAlignment(.center) - .frame(width: 52) - .font(.caption2) - .monospacedDigit() - .lineLimit(1) - .minimumScaleFactor(0.7) + if context.state.endDate <= Date() { + Text("Vége") + .multilineTextAlignment(.center) + .frame(width: 52) + .font(.caption2) + .lineLimit(1) + .minimumScaleFactor(0.7) + } else { + Text(timerInterval: context.state.date, countsDown: true) + .multilineTextAlignment(.center) + .frame(width: 52) + .font(.caption2) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.7) + } /// Collapsed } minimal: { From cd0026e4c76f73f226f7effea65e3ffc6e0b9c7a Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 15 Mar 2026 11:01:24 +0100 Subject: [PATCH 48/59] Add loading state management and error handling in KretenLoginWidget for improved user experience --- .../lib/screens/login/kreten_login.dart | 167 +++++++++--------- 1 file changed, 87 insertions(+), 80 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 22c74cc2..997a193d 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -39,6 +39,7 @@ class _KretenLoginWidgetState extends State late AnimationController _animationController; var loadingPercentage = 0; var currentUrl = ''; + bool _initialPageLoaded = false; bool _hasFadedIn = false; bool _hasError = false; String _errorMessage = ''; @@ -48,6 +49,28 @@ class _KretenLoginWidgetState extends State static const _loginUrl = 'https://idp.e-kreta.hu/connect/authorize?prompt=login&nonce=wylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU&response_type=code&code_challenge_method=S256&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&code_challenge=HByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ&redirect_uri=https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect&client_id=kreta-ellenorzo-student-mobile-ios&state=refilc_student_mobile'; + static final Uri _redirectUri = Uri.parse( + 'https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect', + ); + + bool _isRedirectUri(Uri uri) { + return uri.scheme == _redirectUri.scheme && + uri.host == _redirectUri.host && + uri.path == _redirectUri.path; + } + + bool _shouldIgnoreError(WebResourceError error) { + if (error.isForMainFrame == false) { + return true; + } + + final String description = error.description.toLowerCase(); + return error.errorCode == -999 || + description.contains('cancelled') || + description.contains('canceled') || + description.contains('frame load interrupted'); + } + @override void initState() { super.initState(); @@ -61,84 +84,63 @@ class _KretenLoginWidgetState extends State ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onNavigationRequest: (n) async { - if (n.url.startsWith('https://mobil.e-kreta.hu')) { - setState(() { - loadingPercentage = 0; - currentUrl = n.url; - }); - - // final String instituteCode = widget.selectedSchool; - // if (!n.url.startsWith( - // 'https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect?code=')) { - // return; - // } - - List requiredThings = n.url - .replaceAll( - 'https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect?code=', - '') - .replaceAll( - '&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&state=refilc_student_mobile&session_state=', - ':') - .split(':'); - - String code = requiredThings[0]; - // String sessionState = requiredThings[1]; - - widget.onLogin(code); - // Future.delayed(const Duration(milliseconds: 500), () { - // Navigator.of(context).pop(); - // }); - // Navigator.of(context).pop(); - - return NavigationDecision.prevent; - } else { - return NavigationDecision.navigate; + final Uri? uri = Uri.tryParse(n.url); + if (uri != null && _isRedirectUri(uri)) { + final String? code = uri.queryParameters['code']; + if (code != null && code.isNotEmpty) { + _timeoutTimer?.cancel(); + widget.onLogin(code); + return NavigationDecision.prevent; + } } + + return NavigationDecision.navigate; }, onPageStarted: (url) async { - // setState(() { - // loadingPercentage = 0; - // currentUrl = url; - // }); + if (!mounted) return; - // // final String instituteCode = widget.selectedSchool; - // if (!url.startsWith( - // 'https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect?code=')) { - // return; - // } + setState(() { + currentUrl = url; + _hasError = false; + _errorMessage = ''; + _hasTimedOut = false; - // List requiredThings = url - // .replaceAll( - // 'https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect?code=', - // '') - // .replaceAll( - // '&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&state=refilc_student_mobile&session_state=', - // ':') - // .split(':'); + if (!_initialPageLoaded) { + loadingPercentage = 0; + } + }); - // String code = requiredThings[0]; - // // String sessionState = requiredThings[1]; - - // widget.onLogin(code); - // // Future.delayed(const Duration(milliseconds: 500), () { - // // Navigator.of(context).pop(); - // // }); - // // Navigator.of(context).pop(); + _startTimeoutTimer(); }, onProgress: (progress) { + if (!mounted) return; + setState(() { loadingPercentage = progress; }); }, onPageFinished: (url) { _timeoutTimer?.cancel(); + + if (!mounted) return; + setState(() { + currentUrl = url; + _initialPageLoaded = true; + _hasError = false; + _hasTimedOut = false; loadingPercentage = 100; }); }, onWebResourceError: (error) { + if (_shouldIgnoreError(error)) { + return; + } + _timeoutTimer?.cancel(); + + if (!mounted) return; + setState(() { _hasError = true; _errorMessage = error.description; @@ -155,7 +157,7 @@ class _KretenLoginWidgetState extends State void _startTimeoutTimer() { _timeoutTimer?.cancel(); _timeoutTimer = Timer(const Duration(seconds: 15), () { - if (mounted && loadingPercentage < 100 && !_hasError) { + if (mounted && !_initialPageLoaded && !_hasError) { setState(() { _hasTimedOut = true; }); @@ -168,6 +170,7 @@ class _KretenLoginWidgetState extends State _hasError = false; _errorMessage = ''; _hasTimedOut = false; + _initialPageLoaded = false; loadingPercentage = 0; _hasFadedIn = false; }); @@ -244,7 +247,7 @@ class _KretenLoginWidgetState extends State } // Trigger the fade-in animation only once when loading reaches 100% - if (loadingPercentage == 100 && !_hasFadedIn) { + if (_initialPageLoaded && !_hasFadedIn) { _animationController.forward(); // Play the animation _hasFadedIn = true; // Set the flag to true, so the animation is not replayed @@ -252,9 +255,8 @@ class _KretenLoginWidgetState extends State return Stack( children: [ - // Webview that will be displayed only when the loading is 100% - if (loadingPercentage == 100) - FadeTransition( + Positioned.fill( + child: FadeTransition( opacity: Tween(begin: 0, end: 1).animate( CurvedAnimation( parent: _animationController, @@ -265,23 +267,28 @@ class _KretenLoginWidgetState extends State controller: controller, ), ), - - // Show the CircularProgressIndicator while loading is not 100% - if (loadingPercentage < 100) - Center( - child: TweenAnimationBuilder( - tween: Tween(begin: 0, end: loadingPercentage / 100.0), - duration: const Duration(milliseconds: 300), - builder: (context, double value, child) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - CircularProgressIndicator( - value: value, // Smoothly animates the progress - ), - ], - ); - }, + ), + if (!_initialPageLoaded) + Positioned.fill( + child: ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: Center( + child: TweenAnimationBuilder( + tween: + Tween(begin: 0, end: loadingPercentage / 100.0), + duration: const Duration(milliseconds: 300), + builder: (context, double value, child) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator( + value: value == 0 ? null : value, + ), + ], + ); + }, + ), + ), ), ), ], From 84e8346ccc0c76ba27f1fa2c154b5892b6091b06 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 15 Mar 2026 14:39:40 +0000 Subject: [PATCH 49/59] Fix login page error message shown on initial load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add auto-retry logic in KretenLoginWidget so that the first web resource error silently retries once before showing the error UI. This prevents the error message from appearing immediately when the e-KRÉTA server is briefly unreachable (e.g., transient network issues), resolving the App Store Guideline 2.1(a) rejection. https://claude.ai/code/session_016dhktF2DaoTQeifUaZrxbP --- .../lib/screens/login/kreten_login.dart | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 997a193d..7e10095e 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -45,6 +45,8 @@ class _KretenLoginWidgetState extends State String _errorMessage = ''; bool _hasTimedOut = false; Timer? _timeoutTimer; + int _autoRetryCount = 0; + static const int _maxAutoRetries = 1; static const _loginUrl = 'https://idp.e-kreta.hu/connect/authorize?prompt=login&nonce=wylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU&response_type=code&code_challenge_method=S256&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&code_challenge=HByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ&redirect_uri=https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect&client_id=kreta-ellenorzo-student-mobile-ios&state=refilc_student_mobile'; @@ -110,6 +112,7 @@ class _KretenLoginWidgetState extends State } }); + _autoRetryCount = 0; _startTimeoutTimer(); }, onProgress: (progress) { @@ -141,6 +144,14 @@ class _KretenLoginWidgetState extends State if (!mounted) return; + // Auto-retry once on first error before showing the error UI, + // to handle transient network issues on initial load. + if (_autoRetryCount < _maxAutoRetries) { + _autoRetryCount++; + _retryLoad(); + return; + } + setState(() { _hasError = true; _errorMessage = error.description; @@ -165,6 +176,18 @@ class _KretenLoginWidgetState extends State }); } + void _retryLoad() { + setState(() { + _hasError = false; + _errorMessage = ''; + _hasTimedOut = false; + _initialPageLoaded = false; + loadingPercentage = 0; + }); + controller.loadRequest(Uri.parse(_loginUrl)); + _startTimeoutTimer(); + } + void _retry() { setState(() { _hasError = false; @@ -174,6 +197,7 @@ class _KretenLoginWidgetState extends State loadingPercentage = 0; _hasFadedIn = false; }); + _autoRetryCount = 0; _animationController.reset(); controller.loadRequest(Uri.parse(_loginUrl)); _startTimeoutTimer(); From c3b1e783b89ffe5f16846bdf8cb2e4fda30202e7 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 15 Mar 2026 18:09:48 +0000 Subject: [PATCH 50/59] Fix auto-retry cap never being reached in KretenLoginWidget _autoRetryCount was reset to 0 in onPageStarted, which fires after every loadRequest call including the one inside _retryLoad. This meant the retry cap (_maxAutoRetries = 1) was never reached, causing an infinite retry loop on persistent errors. Move the _autoRetryCount reset to onPageFinished so it only clears when the page actually loads successfully (or via the user-initiated _retry which already resets it explicitly). https://claude.ai/code/session_016dhktF2DaoTQeifUaZrxbP --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 7e10095e..35a420cf 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -112,7 +112,6 @@ class _KretenLoginWidgetState extends State } }); - _autoRetryCount = 0; _startTimeoutTimer(); }, onProgress: (progress) { @@ -127,6 +126,7 @@ class _KretenLoginWidgetState extends State if (!mounted) return; + _autoRetryCount = 0; setState(() { currentUrl = url; _initialPageLoaded = true; From b33a6d2ca0f51aa93291fc36f041a16446ec6d33 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 15 Mar 2026 18:51:36 +0000 Subject: [PATCH 51/59] Guard auto-retry to initial load only in KretenLoginWidget After the login page first loaded successfully, any subsequent navigation error (e.g. during credential entry) would silently reload _loginUrl, discarding user-entered credentials. This was because the auto-retry block only checked _autoRetryCount, which was reset to 0 by onPageFinished after every successful load. Add _hasLoadedOnce that is set true in onPageFinished and only cleared in _retry() (explicit user action). Gate the silent auto-retry on !_hasLoadedOnce so it only fires before the login page has been shown to the user for the first time. https://claude.ai/code/session_016dhktF2DaoTQeifUaZrxbP --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 35a420cf..b37be39f 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -47,6 +47,7 @@ class _KretenLoginWidgetState extends State Timer? _timeoutTimer; int _autoRetryCount = 0; static const int _maxAutoRetries = 1; + bool _hasLoadedOnce = false; static const _loginUrl = 'https://idp.e-kreta.hu/connect/authorize?prompt=login&nonce=wylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU&response_type=code&code_challenge_method=S256&scope=openid%20email%20offline_access%20kreta-ellenorzo-webapi.public%20kreta-eugyintezes-webapi.public%20kreta-fileservice-webapi.public%20kreta-mobile-global-webapi.public%20kreta-dkt-webapi.public%20kreta-ier-webapi.public&code_challenge=HByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ&redirect_uri=https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect&client_id=kreta-ellenorzo-student-mobile-ios&state=refilc_student_mobile'; @@ -127,6 +128,7 @@ class _KretenLoginWidgetState extends State if (!mounted) return; _autoRetryCount = 0; + _hasLoadedOnce = true; setState(() { currentUrl = url; _initialPageLoaded = true; @@ -146,7 +148,7 @@ class _KretenLoginWidgetState extends State // Auto-retry once on first error before showing the error UI, // to handle transient network issues on initial load. - if (_autoRetryCount < _maxAutoRetries) { + if (!_hasLoadedOnce && _autoRetryCount < _maxAutoRetries) { _autoRetryCount++; _retryLoad(); return; @@ -198,6 +200,7 @@ class _KretenLoginWidgetState extends State _hasFadedIn = false; }); _autoRetryCount = 0; + _hasLoadedOnce = false; _animationController.reset(); controller.loadRequest(Uri.parse(_loginUrl)); _startTimeoutTimer(); From 446988ec0b0609b41e564f461edb27f73b1bef34 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Sun, 15 Mar 2026 22:46:50 +0100 Subject: [PATCH 52/59] Increase auto-retry limit to 3 and improve error messaging in KretenLoginWidget --- .../lib/screens/login/kreten_login.dart | 39 +++++++++---------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index b37be39f..2c44d627 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -42,11 +42,10 @@ class _KretenLoginWidgetState extends State bool _initialPageLoaded = false; bool _hasFadedIn = false; bool _hasError = false; - String _errorMessage = ''; bool _hasTimedOut = false; Timer? _timeoutTimer; int _autoRetryCount = 0; - static const int _maxAutoRetries = 1; + static const int _maxAutoRetries = 3; bool _hasLoadedOnce = false; static const _loginUrl = @@ -105,7 +104,7 @@ class _KretenLoginWidgetState extends State setState(() { currentUrl = url; _hasError = false; - _errorMessage = ''; + _hasTimedOut = false; if (!_initialPageLoaded) { @@ -146,17 +145,18 @@ class _KretenLoginWidgetState extends State if (!mounted) return; - // Auto-retry once on first error before showing the error UI, + // Auto-retry on first errors before showing the error UI, // to handle transient network issues on initial load. if (!_hasLoadedOnce && _autoRetryCount < _maxAutoRetries) { _autoRetryCount++; - _retryLoad(); + Future.delayed(Duration(seconds: _autoRetryCount), () { + if (mounted) _retryLoad(); + }); return; } setState(() { _hasError = true; - _errorMessage = error.description; }); }, )) @@ -181,7 +181,6 @@ class _KretenLoginWidgetState extends State void _retryLoad() { setState(() { _hasError = false; - _errorMessage = ''; _hasTimedOut = false; _initialPageLoaded = false; loadingPercentage = 0; @@ -193,7 +192,6 @@ class _KretenLoginWidgetState extends State void _retry() { setState(() { _hasError = false; - _errorMessage = ''; _hasTimedOut = false; _initialPageLoaded = false; loadingPercentage = 0; @@ -232,30 +230,29 @@ class _KretenLoginWidgetState extends State mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( - Icons.error_outline, + Icons.wifi_off_rounded, size: 48, - color: Theme.of(context).colorScheme.error, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), const SizedBox(height: 16), Text( - 'A bejelentkezési oldal nem tölthető be', + 'A bejelentkezési oldal nem érhető el', textAlign: TextAlign.center, style: TextStyle( fontSize: 16, + fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface, ), ), - if (_errorMessage.isNotEmpty) ...[ - const SizedBox(height: 8), - Text( - _errorMessage, - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 12, - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), + const SizedBox(height: 8), + Text( + 'Az e-KRÉTA bejelentkezés csak magyarországi hálózatról érhető el. Kérjük, ellenőrizd az internetkapcsolatod.', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), - ], + ), const SizedBox(height: 24), FilledButton.icon( onPressed: _retry, From 2ece6bd36f42ce028f060b553a4195d4f57fccb5 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 16 Mar 2026 13:44:33 +0100 Subject: [PATCH 53/59] Add demo mode functionality to KretenLoginWidget and integrate with LoginScreen --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 10 +++++++++- refilc_mobile_ui/lib/screens/login/login_screen.dart | 11 ++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 2c44d627..59a6b580 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -24,10 +24,11 @@ import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class KretenLoginWidget extends StatefulWidget { - const KretenLoginWidget({super.key, required this.onLogin}); + const KretenLoginWidget({super.key, required this.onLogin, this.onDemoMode}); // final String selectedSchool; final void Function(String code) onLogin; + final VoidCallback? onDemoMode; @override State createState() => _KretenLoginWidgetState(); @@ -259,6 +260,13 @@ class _KretenLoginWidgetState extends State icon: const Icon(Icons.refresh), label: const Text('Próbáld újra'), ), + if (widget.onDemoMode != null) ...[ + const SizedBox(height: 12), + OutlinedButton( + onPressed: widget.onDemoMode, + child: const Text('Kipróbálom fiók nélkül'), + ), + ], const SizedBox(height: 12), TextButton( onPressed: () => Navigator.of(context).pop(), diff --git a/refilc_mobile_ui/lib/screens/login/login_screen.dart b/refilc_mobile_ui/lib/screens/login/login_screen.dart index 6c95e732..35b84d6e 100644 --- a/refilc_mobile_ui/lib/screens/login/login_screen.dart +++ b/refilc_mobile_ui/lib/screens/login/login_screen.dart @@ -279,7 +279,7 @@ class LoginScreenState extends State { context: context, isScrollControlled: true, // This ensures the modal accommodates input fields properly - builder: (BuildContext context) { + builder: (BuildContext sheetContext) { return Container( height: MediaQuery.of(context) .size @@ -355,6 +355,15 @@ class LoginScreenState extends State { context) .pop(); }, + onDemoMode: () { + Navigator.of(context).pop(); + final userProvider = Provider.of(context, listen: false); + final demoUser = User.demo(); + userProvider.addUser(demoUser); + userProvider.setUser(demoUser.id); + setSystemChrome(context); + Navigator.of(context).pushReplacementNamed('login_to_navigation'); + }, ), ), ), From 90165f257c8afb75403078cc1484c875698d3945 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Tue, 17 Mar 2026 12:05:10 +0100 Subject: [PATCH 54/59] Update lesson filtering logic to include substitute teachers in ServerSyncProvider --- refilc/lib/api/providers/live_card_provider.dart | 2 +- .../lib/api/providers/liveactivity/server_sync_provider.dart | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 2e9e0f41..214239c2 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -280,7 +280,7 @@ class LiveCardProvider extends ChangeNotifier { today = today .where((lesson) => - lesson.status?.name != "Elmaradt" && + (lesson.status?.name != "Elmaradt" || lesson.substituteTeacher != null) && lesson.subject.id != '' && !lesson.isEmpty) .toList(); diff --git a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart index f3b52cc0..0c7ec4b5 100644 --- a/refilc/lib/api/providers/liveactivity/server_sync_provider.dart +++ b/refilc/lib/api/providers/liveactivity/server_sync_provider.dart @@ -167,7 +167,9 @@ class ServerSyncProvider { List _filterLessons(List lessons) { return lessons .where((l) => - l.status?.name != 'Elmaradt' && l.subject.id != '' && !l.isEmpty) + (l.status?.name != 'Elmaradt' || l.substituteTeacher != null) && + l.subject.id != '' && + !l.isEmpty) .toList() ..sort((a, b) => a.start.compareTo(b.start)); } From 02fecf7ac7e298d05f140333b110a86661ae629a Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 18 Mar 2026 07:05:22 +0100 Subject: [PATCH 55/59] Set custom user agent for WebView in KretenLoginWidget --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index 59a6b580..ebdd851a 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -85,6 +85,7 @@ class _KretenLoginWidgetState extends State controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1') ..setNavigationDelegate(NavigationDelegate( onNavigationRequest: (n) async { final Uri? uri = Uri.tryParse(n.url); @@ -112,8 +113,6 @@ class _KretenLoginWidgetState extends State loadingPercentage = 0; } }); - - _startTimeoutTimer(); }, onProgress: (progress) { if (!mounted) return; From 5210106032daa602b186e42fdb5bdd8640e5d105 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 18 Mar 2026 09:48:32 +0100 Subject: [PATCH 56/59] Refactor LiveCardProvider to track previous state and lesson ID for updates --- .../lib/api/providers/live_card_provider.dart | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart index 214239c2..3c894afa 100644 --- a/refilc/lib/api/providers/live_card_provider.dart +++ b/refilc/lib/api/providers/live_card_provider.dart @@ -45,6 +45,8 @@ class LiveCardProvider extends ChangeNotifier { static DateTime? now; LiveCardState currentState = LiveCardState.empty; + static LiveCardState _previousState = LiveCardState.empty; + static String? _previousLessonId; // ignore: unused_field late Timer _timer; late final TimetableProvider _timetable; @@ -379,28 +381,22 @@ class LiveCardProvider extends ChangeNotifier { hasUserDismissed = false; _createAndSync(); } else if (hasActivityStarted) { + final currentLessonId = currentLesson?.id ?? nextLesson?.id; + final stateChanged = currentState != _previousState; + final lessonChanged = currentLessonId != _previousLessonId; + if (hasActivitySettingsChanged) { debugPrint("Valamelyik beállítás megváltozott. Frissítés..."); PlatformChannel.updateLiveActivity(toMap()); hasActivitySettingsChanged = false; - } else if (nextLesson != null || currentLesson != null) { - bool afterPrevLessonEnd = prevLesson != null && - now - .subtract(const Duration(seconds: 1)) - .isBefore(prevLesson!.end) && - now.isAfter(prevLesson!.end); - - bool afterCurrentLessonStart = currentLesson != null && - now - .subtract(const Duration(seconds: 1)) - .isBefore(currentLesson!.start) && - now.isAfter(currentLesson!.start); - if (afterPrevLessonEnd || afterCurrentLessonStart) { - debugPrint( - "Óra kezdete/vége után 1 másodperccel vagyunk. Frissítés..."); - PlatformChannel.updateLiveActivity(toMap()); - } + } else if (stateChanged || lessonChanged) { + debugPrint( + "Állapot vagy óra váltás: $currentState, lesson: $currentLessonId. Frissítés..."); + PlatformChannel.updateLiveActivity(toMap()); } + + _previousState = currentState; + _previousLessonId = currentLessonId; } if (_settings.developerMode && _settings.devLiveFakeLessons) { @@ -469,6 +465,8 @@ class LiveCardProvider extends ChangeNotifier { hasDayEnd = false; hasUserDismissed = false; storeFirstRunDate = null; + _previousState = LiveCardState.empty; + _previousLessonId = null; } List _today(TimetableProvider p) { From 702912d476aa405b1ed2c3d71726748ecd6710f8 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 18 Mar 2026 22:10:07 +0100 Subject: [PATCH 57/59] Add demo mode auto-launch functionality in KretenLoginWidget --- refilc_mobile_ui/lib/screens/login/kreten_login.dart | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/refilc_mobile_ui/lib/screens/login/kreten_login.dart b/refilc_mobile_ui/lib/screens/login/kreten_login.dart index ebdd851a..72727d03 100644 --- a/refilc_mobile_ui/lib/screens/login/kreten_login.dart +++ b/refilc_mobile_ui/lib/screens/login/kreten_login.dart @@ -155,6 +155,13 @@ class _KretenLoginWidgetState extends State return; } + // If demo mode is available, auto-launch it instead of + // showing an error UI (e.g. when outside Hungary). + if (widget.onDemoMode != null) { + widget.onDemoMode!(); + return; + } + setState(() { _hasError = true; }); @@ -171,6 +178,10 @@ class _KretenLoginWidgetState extends State _timeoutTimer?.cancel(); _timeoutTimer = Timer(const Duration(seconds: 15), () { if (mounted && !_initialPageLoaded && !_hasError) { + if (widget.onDemoMode != null) { + widget.onDemoMode!(); + return; + } setState(() { _hasTimedOut = true; }); From f86bce48778023263bcf132541906bb87995206a Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 18 Mar 2026 22:11:42 +0100 Subject: [PATCH 58/59] Enhance demo mode to load demo data into providers without API calls --- refilc/lib/api/providers/sync.dart | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/refilc/lib/api/providers/sync.dart b/refilc/lib/api/providers/sync.dart index d60e930e..251912b5 100644 --- a/refilc/lib/api/providers/sync.dart +++ b/refilc/lib/api/providers/sync.dart @@ -37,8 +37,18 @@ Future syncAll(BuildContext context) async { UserProvider user = Provider.of(context, listen: false); - // Demo mode: skip all API calls + // Demo mode: load demo data into providers without API calls if (user.isDemo) { + await Provider.of(context, listen: false).fetch(); + await Provider.of(context, listen: false) + .fetch(week: Week.current()); + await Provider.of(context, listen: false).fetch(); + await Provider.of(context, listen: false) + .fetch(from: DateTime.now().subtract(const Duration(days: 30))); + await Provider.of(context, listen: false).fetchAll(); + await Provider.of(context, listen: false).fetch(); + await Provider.of(context, listen: false).fetch(); + await Provider.of(context, listen: false).fetch(); lock = false; return Future.value(); } From e25f62bd8c3a735fb6c411c5a0d1ed04d72b76f5 Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Wed, 18 Mar 2026 22:16:42 +0100 Subject: [PATCH 59/59] Remove demo user login functionality from LoginScreenState --- refilc_mobile_ui/lib/screens/login/login_screen.dart | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/refilc_mobile_ui/lib/screens/login/login_screen.dart b/refilc_mobile_ui/lib/screens/login/login_screen.dart index 35b84d6e..9dcb966a 100644 --- a/refilc_mobile_ui/lib/screens/login/login_screen.dart +++ b/refilc_mobile_ui/lib/screens/login/login_screen.dart @@ -391,17 +391,6 @@ class LoginScreenState extends State { )), ), ), - const SizedBox(height: 19), - GestureDetector( - onTap: () { - final userProvider = Provider.of(context, listen: false); - final demoUser = User.demo(); - userProvider.addUser(demoUser); - userProvider.setUser(demoUser.id); - setSystemChrome(context); - Navigator.of(context).pushReplacementNamed('login_to_navigation'); - }, - ), const SizedBox(height: 12), // privacy policy GestureDetector(