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
diff --git a/refilc/ios/Podfile b/refilc/ios/Podfile
index 8f025e07..32dbe6b5 100644
--- a/refilc/ios/Podfile
+++ b/refilc/ios/Podfile
@@ -41,13 +41,17 @@ 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
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 b6d9f820..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 */
@@ -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";
diff --git a/refilc/ios/Runner/AppDelegate.swift b/refilc/ios/Runner/AppDelegate.swift
index d7697333..20a4b32d 100644
--- a/refilc/ios/Runner/AppDelegate.swift
+++ b/refilc/ios/Runner/AppDelegate.swift
@@ -2,112 +2,168 @@ 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)
+ })
+
+ NotificationCenter.default.addObserver(
+ forName: NSNotification.Name("LiveActivityDismissed"),
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ let deviceId = self?.getOrCreateDeviceId() ?? ""
+ self?.methodChannel?.invokeMethod("liveActivityDismissed", arguments: [
+ "deviceId": deviceId,
+ ])
+ }
+
+ 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) {
+ let deviceId = getOrCreateDeviceId()
+ unregisterFromServer(deviceId: deviceId)
+ 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 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 {
+ 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 { success in
+ let deviceId = self.getOrCreateDeviceId()
+ let bundleId = Bundle.main.bundleIdentifier ?? ""
+ result([
+ "success": success,
+ "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)
+ }
+ }
+
+ 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
+ }
+ 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
+ }
+
+ private func checkLiveActivityFeatureAvailable() -> Bool {
+ if #available(iOS 16.2, *) {
+ return ActivityAuthorizationInfo().areActivitiesEnabled
+ }
+ return false
+ }
}
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/Runner/public_vars.swift b/refilc/ios/Runner/public_vars.swift
index f084d22d..b35fe24b 100644
--- a/refilc/ios/Runner/public_vars.swift
+++ b/refilc/ios/Runner/public_vars.swift
@@ -1,12 +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
+var isCleaningUpOldActivities = false
diff --git a/refilc/ios/livecard/LiveActivityManager.swift b/refilc/ios/livecard/LiveActivityManager.swift
index 25f9eabf..6a83c70b 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,153 @@ final class LiveActivityManager {
static let shared = LiveActivityManager()
var currentActivity: Activity?
- class func create() {
-
- 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: nil
- )
-
- activityID = activity.id
- print("Live Activity létrehozva. Azonosító: \(activity.id)")
- } catch {
- print("Hiba történt a Live Activity létrehozásakor: \(error)")
- }
+ class func create(completion: @escaping (Bool) -> Void) {
+ Task {
+ isCleaningUpOldActivities = true
+ for activity in Activity.activities {
+ await activity.end(nil, dismissalPolicy: .immediate)
}
- }
-
- 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)
+ try? await Task.sleep(nanoseconds: 200_000_000)
+ isCleaningUpOldActivities = false
- 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)")
- }
+ 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)")
+
+ completion(true)
+
+ Task { await monitorActivityState(activity: activity) }
+
+ 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(false)
+ }
}
-
-
+ }
+
+ private class func monitorActivityState(activity: Activity) async {
+ for await state in activity.activityStateUpdates {
+ if state == .dismissed || state == .ended {
+ if isCleaningUpOldActivities {
+ print("Live Activity ended during cleanup - ignoring dismiss")
+ break
+ }
+ print("Live Activity dismissed/ended by user or system")
+ activityID = nil
+ activityPushToken = nil
+ NotificationCenter.default.post(
+ name: NSNotification.Name("LiveActivityDismissed"),
+ object: nil
+ )
+ await activity.end(nil, dismissalPolicy: .immediate)
+ break
+ }
+ }
+ }
+
+ class func update() {
+ 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
+ )
+
+ 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)")
+ }
+ }
+ }
+
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/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
diff --git a/refilc/ios/livecard/livecard.swift b/refilc/ios/livecard/livecard.swift
index 55f431e8..ca728751 100644
--- a/refilc/ios/livecard/livecard.swift
+++ b/refilc/ios/livecard/livecard.swift
@@ -51,72 +51,103 @@ 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
+ }
+
+ private var nextLessonLine: String {
+ if context.state.nextRoom.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return context.state.nextSubject
+ }
+
+ 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) {
+ 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 hasNextLesson {
+ HStack(spacing: 4) {
+ Image(systemName: "arrow.right")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(.secondary)
+ Text(nextLessonLine)
+ .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)
+ .layoutPriority(0)
- Spacer()
+ Spacer(minLength: 4)
// Visszaszámláló
- Text(timerInterval: context.state.date, countsDown: true)
- .multilineTextAlignment(.center)
- .frame(width: 85)
- .font(.title2)
- .monospacedDigit()
- .padding(.trailing)
+ 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"
@@ -210,14 +241,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!")
@@ -232,14 +267,26 @@ struct LiveCardWidget: Widget {
}
/// Compact
- } compactLeading: {
+ } compactLeading: {
Image(systemName: context.state.icon)
}
compactTrailing: {
- Text(timerInterval: context.state.date, countsDown: true)
- .multilineTextAlignment(.center)
- .frame(width: 40)
- .font(.caption2)
+ 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: {
diff --git a/refilc/lib/api/providers/live_card_provider.dart b/refilc/lib/api/providers/live_card_provider.dart
index 8b50a74e..3c894afa 100644
--- a/refilc/lib/api/providers/live_card_provider.dart
+++ b/refilc/lib/api/providers/live_card_provider.dart
@@ -3,10 +3,14 @@
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';
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';
@@ -30,21 +34,24 @@ class LiveCardProvider extends ChangeNotifier {
Lesson? prevLesson;
List? nextLessons;
- // new variables
static bool hasActivityStarted = false;
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 = {};
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;
late final SettingsProvider _settings;
+ static final ServerSyncProvider serverSync = ServerSyncProvider();
late Duration _delay;
@@ -59,12 +66,31 @@ class LiveCardProvider extends ChangeNotifier {
_delay = settings.bellDelayEnabled
? Duration(seconds: settings.bellDelay)
: Duration.zero;
+
+ PlatformChannel.onTokenUpdated = (pushToken, deviceId, bundleId) {
+ if (!_settings.liveActivityEnabled) return;
+ debugPrint("Push token érkezett: $pushToken");
+ serverSync.registerAndSync(
+ deviceId: deviceId,
+ pushToken: pushToken,
+ bundleId: bundleId,
+ liveActivityColor:
+ '#${settings.liveActivityColor.toHexString().substring(2)}',
+ todayLessons: _today(_timetable),
+ );
+ };
+
+ PlatformChannel.onActivityDismissed = (deviceId) {
+ debugPrint("Live Activity dismissed by user");
+ serverSync.forceUnregister(deviceId);
+ hasActivityStarted = false;
+ hasUserDismissed = true;
+ };
+
update();
}
- // Debugging
static DateTime _now() {
- // return DateTime(2023, 9, 27, 9, 30);
return DateTime.now();
}
@@ -85,8 +111,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) {
@@ -242,6 +266,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 ||
@@ -250,17 +280,14 @@ class LiveCardProvider extends ChangeNotifier {
storeFirstRunDate = now;
}
- // Filter cancelled lessons #20
- // Filter label lessons #128
today = today
.where((lesson) =>
- lesson.status?.name != "Elmaradt" &&
+ (lesson.status?.name != "Elmaradt" || lesson.substituteTeacher != null) &&
lesson.subject.id != '' &&
!lesson.isEmpty)
.toList();
if (today.isNotEmpty) {
- // sort
today.sort((a, b) => a.start.compareTo(b.start));
final _lesson = today.firstWhere(
@@ -294,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;
@@ -305,7 +333,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) {
+ if (nextLesson == null ||
+ ((now.weekday == 6 || now.weekday == 7) &&
+ !(_settings.developerMode && _settings.devLiveFakeLessons))) {
currentState = LiveCardState.empty;
} else {
currentState = LiveCardState.morning;
@@ -314,84 +344,195 @@ class LiveCardProvider extends ChangeNotifier {
currentState = LiveCardState.empty;
}
- //LIVE ACTIVITIES
+ if (!_settings.liveActivityEnabled) {
+ if (hasActivityStarted) {
+ debugPrint("Live Activity nincs engedélyezve, de fut – leállítás...");
+ PlatformChannel.endLiveActivity();
+ serverSync.unregister();
+ 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) {
+ final currentLessonId = currentLesson?.id ?? nextLesson?.id;
+ final stateChanged = currentState != _previousState;
+ final lessonChanged = currentLessonId != _previousLessonId;
- //CREATE
- if (!hasActivityStarted &&
- 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...");
- PlatformChannel.createLiveActivity(toMap());
- hasActivityStarted = true;
- } 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;
- }
-
- //UPDATE
- 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) {
+ if (hasActivitySettingsChanged) {
+ debugPrint("Valamelyik beállítás megváltozott. Frissítés...");
+ PlatformChannel.updateLiveActivity(toMap());
+ hasActivitySettingsChanged = false;
+ } else if (stateChanged || lessonChanged) {
debugPrint(
- "Óra kezdete/vége után 1 másodperccel vagyunk. Frissítés...");
+ "Állapot vagy óra váltás: $currentState, lesson: $currentLessonId. Frissítés...");
PlatformChannel.updateLiveActivity(toMap());
}
- }
- }
- //END
- 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();
- hasActivityStarted = false;
- } else if (hasActivityStarted &&
- !hasDayEnd &&
- nextLesson == null &&
- now.isAfter(prevLesson!.end)) {
- debugPrint("Az utolsó óra véget ért. Befejezés...");
- PlatformChannel.endLiveActivity();
- hasDayEnd = true;
- hasActivityStarted = false;
- }
+ _previousState = currentState;
+ _previousLessonId = currentLessonId;
+ }
+
+ if (_settings.developerMode && _settings.devLiveFakeLessons) {
+ } else if ((currentState == LiveCardState.afternoon ||
+ currentState == LiveCardState.morning ||
+ currentState == LiveCardState.night) &&
+ hasActivityStarted &&
+ nextLesson != null &&
+ 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;
+ } 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();
notifyListeners();
}
+ Future _createAndSync() async {
+ final result = await PlatformChannel.createLiveActivity(toMap());
+ if (result != null && result['success'] == 'true') {
+ debugPrint("Live Activity létrehozva, várunk a push tokenre...");
+ } else {
+ debugPrint("Live Activity létrehozás sikertelen");
+ hasActivityStarted = false;
+ }
+ }
+
bool get show => currentState != LiveCardState.empty;
Duration get delay => _delay;
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();
+ 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;
+ _previousState = LiveCardState.empty;
+ _previousLessonId = null;
+ }
+
+ List _today(TimetableProvider p) {
+ final real = (p.getWeek(Week.current()) ?? [])
+ .where((l) => _sameDate(l.date, _now()))
+ .toList();
+ if (!_settings.developerMode || !_settings.devLiveFakeLessons) {
+ return real;
+ }
+ 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)) {
+ return [...real, ..._generateFakeLessons(startIndex: nextIndex)];
+ }
+
+ final fakeStart = lastEnd.add(const Duration(minutes: 10));
+ return [
+ ...real,
+ ..._generateFakeLessons(baseStart: fakeStart, startIndex: nextIndex)
+ ];
+ }
+ return _generateFakeLessons();
+ }
+
+ static List _generateFakeLessons(
+ {DateTime? baseStart, int startIndex = 0}) {
+ final now = _now();
+ final start0 = 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 = 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_${startIndex + i}',
+ date: DateTime(now.year, now.month, now.day),
+ subject: GradeSubject(
+ id: id,
+ category: kreta.Category(id: '', name: ''),
+ name: name,
+ ),
+ lessonIndex: '${startIndex + 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/api/providers/liveactivity/platform_channel.dart b/refilc/lib/api/providers/liveactivity/platform_channel.dart
index c6f7ba2f..bb2ccad5 100644
--- a/refilc/lib/api/providers/liveactivity/platform_channel.dart
+++ b/refilc/lib/api/providers/liveactivity/platform_channel.dart
@@ -6,16 +6,48 @@ 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).
+ 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(String deviceId)? onActivityDismissed;
+
+ static void _setupMethodCallListener() {
+ _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? ?? '',
+ );
+ }
+ } else if (call.method == 'liveActivityDismissed') {
+ final args = call.arguments as Map?;
+ final deviceId = args?['deviceId'] as String? ?? '';
+ debugPrint("Live Activity dismissed by user (device: $deviceId)");
+ onActivityDismissed?.call(deviceId);
+ }
+ });
+ }
+
+ /// 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