Merge pull request #35 from B3ni15/master

IOS Fix, Live activity, Apple Stuff fix
This commit is contained in:
rnxm
2026-03-19 06:35:50 +01:00
committed by GitHub
38 changed files with 2489 additions and 466 deletions

View File

@@ -20,7 +20,5 @@
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>13.0</string>
</dict>
</plist>

View File

@@ -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

View File

@@ -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 = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
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 = "<group>"; };
3127F73928EAEC3200C2EFB3 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
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 = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
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 = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
/* 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 = "<group>";
@@ -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 = "<group>";
@@ -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";

View File

@@ -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
}
}

View File

@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<string>production</string>
<key>com.apple.security.application-groups</key>
<array>
<string>group.firkaa.legacy</string>

View File

@@ -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

View File

@@ -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<LiveActivitiesAppAttributes>?
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<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>.activities {
await activity.end(nil, dismissalPolicy: .immediate)
}
}
class func update() {
Task {
for activity in Activity<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>) 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<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>.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<LiveActivitiesAppAttributes>.activities {
if activity.id == activityID {
return true
}
for activity in Activity<LiveActivitiesAppAttributes>.activities {
if activity.id == activityID {
return true
}
return false
}
return false
}
}

View File

@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<string>production</string>
<key>com.apple.security.application-groups</key>
<array>
<string>group.firkaa.legacy</string>

View File

@@ -51,72 +51,103 @@ extension Color {
struct LockScreenLiveActivityView: View {
let context: ActivityViewContext<LiveActivitiesAppAttributes>
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: {

View File

@@ -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<Lesson>? 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<String, String> 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<String, String> 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<void> _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<Lesson> _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<Lesson> _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<Lesson>.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<Lesson> _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 = <Lesson>[];
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;
}
}

View File

@@ -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<String?> 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<Map<String, String>?> createLiveActivity(
Map<String, dynamic> activityData) async {
if (Platform.isIOS) {
_setupMethodCallListener();
try {
debugPrint("creating...");
final String? pushToken = await _channel.invokeMethod<String>(
debugPrint("creating live activity...");
final result = await _channel.invokeMethod<Map>(
'createLiveActivity', activityData);
debugPrint("Live Activity push token: $pushToken");
return pushToken;
if (result == null) return null;
return {
'success': (result['success'] as bool? ?? false).toString(),
'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 +59,7 @@ class PlatformChannel {
Map<String, dynamic> 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 +70,11 @@ class PlatformChannel {
static Future<void> 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}");
}
}
}
}
}

View File

@@ -0,0 +1,176 @@
import 'dart:convert';
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';
class ServerSyncProvider {
static const String _baseUrl = 'https://legacy-la.devbeni.lol';
String? _deviceId;
Future<void> registerAndSync({
required String deviceId,
required String pushToken,
required String bundleId,
required String liveActivityColor,
required List<Lesson> 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);
}
}
Future<void> 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<void> _register({
required String deviceId,
required String pushToken,
required String bundleId,
required String liveActivityColor,
}) async {
try {
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} ${response.body}');
} else {
debugPrint('ServerSync: device regisztrálva');
}
} catch (e) {
debugPrint('ServerSync register kivétel: $e');
}
}
Future<void> _uploadSchedule({
required String deviceId,
required List<Lesson> lessons,
}) async {
try {
final now = DateTime.now();
final dateStr =
'${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
final entries = <Map<String, dynamic>>[];
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',
'index': '',
'subject': 'Szünet',
'icon': 'cup.and.saucer',
'room': '',
'description': '',
'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'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'device_id': deviceId,
'date': dateStr,
'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: ${entries.length} elem feltöltve ($dateStr)');
}
} catch (e) {
debugPrint('ServerSync schedule kivétel: $e');
}
}
Future<void> unregister() async {
if (_deviceId == null) return;
await forceUnregister(_deviceId!);
}
Future<void> forceUnregister(String deviceId) async {
try {
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: device + schedule törölve (unregister)');
} else {
debugPrint('ServerSync unregister hiba: ${response.statusCode}');
}
} catch (e) {
debugPrint('ServerSync unregister kivétel: $e');
}
_deviceId = null;
}
List<Lesson> _filterLessons(List<Lesson> lessons) {
return lessons
.where((l) =>
(l.status?.name != 'Elmaradt' || l.substituteTeacher != null) &&
l.subject.id != '' &&
!l.isEmpty)
.toList()
..sort((a, b) => a.start.compareTo(b.start));
}
}

View File

@@ -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;
@@ -39,8 +37,18 @@ Future<void> syncAll(BuildContext context) async {
UserProvider user = Provider.of<UserProvider>(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<GradeProvider>(context, listen: false).fetch();
await Provider.of<TimetableProvider>(context, listen: false)
.fetch(week: Week.current());
await Provider.of<ExamProvider>(context, listen: false).fetch();
await Provider.of<HomeworkProvider>(context, listen: false)
.fetch(from: DateTime.now().subtract(const Duration(days: 30)));
await Provider.of<MessageProvider>(context, listen: false).fetchAll();
await Provider.of<NoteProvider>(context, listen: false).fetch();
await Provider.of<EventProvider>(context, listen: false).fetch();
await Provider.of<AbsenceProvider>(context, listen: false).fetch();
lock = false;
return Future.value();
}
@@ -148,15 +156,8 @@ Future<void> syncAll(BuildContext context) async {
}
return Future.wait(tasks).then((value) {
// Unlock
lock = false;
if (Platform.isIOS && LiveCardProvider.hasActivityStarted == true) {
PlatformChannel.endLiveActivity();
LiveCardProvider.hasActivityStarted = false;
}
// Update Widget
if (Platform.isAndroid) updateWidget();
});
}

View File

@@ -1,5 +1,6 @@
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
import 'package:refilc/api/providers/database_provider.dart';
@@ -14,6 +15,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
@@ -56,6 +58,8 @@ const settingsDB = DatabaseStruct("settings", {
"uwu_mode": int,
"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,
@@ -184,6 +188,25 @@ Future<Database> initDB(DatabaseProvider database) async {
print("ERROR: migrateDB: $error");
}
// 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', 'live_activity_consent_accepted']);
if (rows.isNotEmpty) {
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<String>();
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;
}

View File

@@ -10,6 +10,7 @@ class LiveActivityHelper {
await PlatformChannel.updateLiveActivity(LiveCardProvider.LAData);
} else {
await PlatformChannel.endLiveActivity();
LiveCardProvider.serverSync.unregister();
}
}
}

View File

@@ -54,6 +54,7 @@ class SettingsProvider extends ChangeNotifier {
// minutes: times 15
int _notificationPollInterval;
bool _developerMode;
bool _devLiveFakeLessons;
VibrationStrength _vibrate;
bool _abWeeks;
bool _swapABweeks;
@@ -109,6 +110,8 @@ class SettingsProvider extends ChangeNotifier {
bool _uwuMode;
bool _newPopups;
List<String> _unseenNewFeatures;
bool _liveActivityEnabled;
bool _liveActivityConsentAccepted;
bool _cloudSyncEnabled;
String _cloudSyncToken;
DateTime _updatedAt;
@@ -134,6 +137,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,
@@ -187,6 +191,8 @@ class SettingsProvider extends ChangeNotifier {
required bool uwuMode,
required bool newPopups,
required List<String> unseenNewFeatures,
required bool liveActivityEnabled,
required bool liveActivityConsentAccepted,
required bool cloudSyncEnabled,
required String cloudSyncToken,
required DateTime updatedAt,
@@ -209,6 +215,7 @@ class SettingsProvider extends ChangeNotifier {
_notificationsLessonsEnabled = notificationsLessonsEnabled,
_notificationsBitfield = notificationsBitfield,
_developerMode = developerMode,
_devLiveFakeLessons = devLiveFakeLessons,
_notificationPollInterval = notificationPollInterval,
_vibrate = vibrate,
_abWeeks = abWeeks,
@@ -262,6 +269,8 @@ class SettingsProvider extends ChangeNotifier {
_uwuMode = uwuMode,
_newPopups = newPopups,
_unseenNewFeatures = unseenNewFeatures,
_liveActivityEnabled = liveActivityEnabled,
_liveActivityConsentAccepted = liveActivityConsentAccepted,
_cloudSyncEnabled = cloudSyncEnabled,
_cloudSyncToken = cloudSyncToken,
_updatedAt = updatedAt,
@@ -303,6 +312,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,
@@ -356,6 +366,8 @@ class SettingsProvider extends ChangeNotifier {
uwuMode: map['uwu_mode'] == 1,
newPopups: map['new_popups'] == 1,
unseenNewFeatures: jsonDecode(map["unseen_new_features"]).cast<String>(),
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(),
@@ -381,6 +393,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,
@@ -438,6 +451,8 @@ 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,
"live_activity_consent_accepted": _liveActivityConsentAccepted ? 1 : 0,
"cloud_sync_enabled": _cloudSyncEnabled ? 1 : 0,
"cloud_sync_token": _cloudSyncToken,
"local_updated_at": _updatedAt.toIso8601String(),
@@ -471,6 +486,7 @@ class SettingsProvider extends ChangeNotifier {
notificationsLessonsEnabled: true,
notificationsBitfield: 255,
developerMode: true,
devLiveFakeLessons: false,
notificationPollInterval: 1,
vibrate: VibrationStrength.medium,
abWeeks: false,
@@ -523,7 +539,9 @@ class SettingsProvider extends ChangeNotifier {
newColors: true,
uwuMode: false,
newPopups: false,
unseenNewFeatures: [],
unseenNewFeatures: ['live_activity_consent'],
liveActivityEnabled: false,
liveActivityConsentAccepted: false,
cloudSyncEnabled: false,
cloudSyncToken: '',
updatedAt: DateTime.now(),
@@ -549,6 +567,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;
@@ -601,6 +620,8 @@ class SettingsProvider extends ChangeNotifier {
bool get uwuMode => _uwuMode;
bool get newPopups => _newPopups;
List<String> get unseenNewFeatures => _unseenNewFeatures;
bool get liveActivityEnabled => _liveActivityEnabled;
bool get liveActivityConsentAccepted => _liveActivityConsentAccepted;
bool get cloudSyncEnabled => _cloudSyncEnabled;
String get cloudSyncToken => _cloudSyncToken;
DateTime get updatedAt => _updatedAt;
@@ -626,6 +647,7 @@ class SettingsProvider extends ChangeNotifier {
bool? notificationsLessonsEnabled,
int? notificationsBitfield,
bool? developerMode,
bool? devLiveFakeLessons,
int? notificationPollInterval,
VibrationStrength? vibrate,
bool? abWeeks,
@@ -675,6 +697,8 @@ class SettingsProvider extends ChangeNotifier {
bool? uwuMode,
bool? newPopups,
List<String>? unseenNewFeatures,
bool? liveActivityEnabled,
bool? liveActivityConsentAccepted,
bool? cloudSyncEnabled,
String? cloudSyncToken,
bool? qTimetableLessonNum,
@@ -727,6 +751,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;
@@ -875,6 +902,15 @@ 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 (liveActivityConsentAccepted != null && liveActivityConsentAccepted != _liveActivityConsentAccepted) {
_liveActivityConsentAccepted = liveActivityConsentAccepted;
}
if (cloudSyncEnabled != null && cloudSyncEnabled != _cloudSyncEnabled) {
_cloudSyncEnabled = cloudSyncEnabled;
}
@@ -930,6 +966,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,
@@ -993,6 +1030,8 @@ class SettingsProvider extends ChangeNotifier {
newPopups: map['new_popups'] == 1,
unseenNewFeatures:
jsonDecode(map["unseen_new_features"] ?? "[]").cast<String>(),
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,

View File

@@ -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
@@ -69,7 +69,6 @@ dependencies:
shake_flutter: ^17.1.0
dependency_overrides:
webview_flutter_wkwebview: 3.17.0
intl: 0.20.2
dev_dependencies:

View File

@@ -0,0 +1,394 @@
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/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';
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<Grade> 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<Week, List<Lesson>> get timetable {
final week = Week.current();
return {week: _lessonsForWeek(week)};
}
static List<Lesson> _lessonsForWeek(Week week) {
final monday = week.start;
List<Lesson> 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<Lesson> _dayLessons(DateTime day, List<_LessonDef> defs) {
final List<Lesson> 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<Absence> 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<Exam> 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<Homework> 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<Message> 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 List<GroupAverage> 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;
}
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);
}

View File

@@ -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<void> fetch() async {
User? user = Provider.of<UserProvider>(_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<KretaClient>(_context, listen: false)

View File

@@ -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<void> fetch() async {
User? user = Provider.of<UserProvider>(_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<KretaClient>(_context, listen: false)

View File

@@ -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<void> fetch() async {
User? user = Provider.of<UserProvider>(_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<KretaClient>(_context, listen: false)

View File

@@ -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,15 @@ Future<void> unseenAll() async {
// Fetches Grades from the Kreta API then stores them in the database
Future<void> 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);
await storeGroupAvg(DemoData.groupAverages);
return;
}
String iss = user.instituteCode;
List? gradesJson = await _kreta.getAPI(KretaAPI.grades(iss));

View File

@@ -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<UserProvider>(_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 = [];

View File

@@ -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<void> 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<UserProvider>(_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<KretaClient>(_context, listen: false)
.getAPI(KretaAPI.messages(messageType));
@@ -127,6 +136,8 @@ class MessageProvider with ChangeNotifier {
User? user = Provider.of<UserProvider>(_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<KretaClient>(_context, listen: false)

View File

@@ -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<void> fetch() async {
User? user = Provider.of<UserProvider>(_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<KretaClient>(_context, listen: false)

View File

@@ -3,12 +3,14 @@ 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';
class TimetableProvider with ChangeNotifier {
Map<Week, List<Lesson>> lessons = {};
String? _activeUserId;
late final UserProvider _user;
late final DatabaseProvider _database;
late final KretaClient _kreta;
@@ -20,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<void> 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();
}
}
@@ -71,8 +94,21 @@ class TimetableProvider with ChangeNotifier {
// Fetches Lessons from the Kreta API then stores them in the database
Future<void> 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";
if (DemoData.isDemo(user.id)) {
lessons = DemoData.timetable;
notifyListeners();
return;
}
String iss = user.instituteCode;
List? lessonsJson;

View File

@@ -305,6 +305,8 @@ class _GradeSubjectViewState extends State<GradeSubjectView>
if (DateTime.now().day > 5) {
_timetableController.next(context);
}
fetchGoalPlans();
}
void fetchGoalPlans() async {
@@ -370,8 +372,6 @@ class _GradeSubjectViewState extends State<GradeSubjectView>
buildTiles(ghostGrades);
}
fetchGoalPlans();
return Scaffold(
key: _scaffoldKey,
floatingActionButtonLocation: ExpandableFab.location,

View File

@@ -105,6 +105,7 @@ class TimetablePageState extends State<TimetablePage>
// Update timetable on user change
Future<void> _userListener() async {
await Provider.of<TimetableProvider>(context, listen: false).restoreUser();
await Provider.of<KretaClient>(context, listen: false).refreshLogin();
if (mounted) _controller.jump(_controller.currentWeek, context: context);
}

View File

@@ -18,14 +18,17 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:async';
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<KretenLoginWidget> createState() => _KretenLoginWidgetState();
@@ -37,7 +40,39 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
late AnimationController _animationController;
var loadingPercentage = 0;
var currentUrl = '';
bool _initialPageLoaded = false;
bool _hasFadedIn = false;
bool _hasError = false;
bool _hasTimedOut = false;
Timer? _timeoutTimer;
int _autoRetryCount = 0;
static const int _maxAutoRetries = 3;
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';
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() {
@@ -50,88 +85,134 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
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 {
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<String> 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;
// List<String> 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(':');
_hasTimedOut = false;
// 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();
if (!_initialPageLoaded) {
loadingPercentage = 0;
}
});
},
onProgress: (progress) {
if (!mounted) return;
setState(() {
loadingPercentage = progress;
});
},
onPageFinished: (url) {
_timeoutTimer?.cancel();
if (!mounted) return;
_autoRetryCount = 0;
_hasLoadedOnce = true;
setState(() {
currentUrl = url;
_initialPageLoaded = true;
_hasError = false;
_hasTimedOut = false;
loadingPercentage = 100;
});
},
onWebResourceError: (error) {
if (_shouldIgnoreError(error)) {
return;
}
_timeoutTimer?.cancel();
if (!mounted) return;
// Auto-retry on first errors before showing the error UI,
// to handle transient network issues on initial load.
if (!_hasLoadedOnce && _autoRetryCount < _maxAutoRetries) {
_autoRetryCount++;
Future.delayed(Duration(seconds: _autoRetryCount), () {
if (mounted) _retryLoad();
});
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;
});
},
))
..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 && !_initialPageLoaded && !_hasError) {
if (widget.onDemoMode != null) {
widget.onDemoMode!();
return;
}
setState(() {
_hasTimedOut = true;
});
}
});
}
void _retryLoad() {
setState(() {
_hasError = false;
_hasTimedOut = false;
_initialPageLoaded = false;
loadingPercentage = 0;
});
controller.loadRequest(Uri.parse(_loginUrl));
_startTimeoutTimer();
}
void _retry() {
setState(() {
_hasError = false;
_hasTimedOut = false;
_initialPageLoaded = false;
loadingPercentage = 0;
_hasFadedIn = false;
});
_autoRetryCount = 0;
_hasLoadedOnce = false;
_animationController.reset();
controller.loadRequest(Uri.parse(_loginUrl));
_startTimeoutTimer();
}
// Future<void> loadLoginUrl() async {
@@ -143,6 +224,7 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
@override
void dispose() {
_timeoutTimer?.cancel();
// Step 3: Dispose of the animation controller
_animationController.dispose();
super.dispose();
@@ -150,8 +232,64 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
@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.wifi_off_rounded,
size: 48,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'A bejelentkezési oldal nem érhető el',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurface,
),
),
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,
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(),
child: const Text('Vissza'),
),
],
),
),
);
}
// 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
@@ -159,9 +297,8 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
return Stack(
children: [
// Webview that will be displayed only when the loading is 100%
if (loadingPercentage == 100)
FadeTransition(
Positioned.fill(
child: FadeTransition(
opacity: Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(
parent: _animationController,
@@ -172,23 +309,28 @@ class _KretenLoginWidgetState extends State<KretenLoginWidget>
controller: controller,
),
),
// Show the CircularProgressIndicator while loading is not 100%
if (loadingPercentage < 100)
Center(
child: TweenAnimationBuilder(
tween: Tween<double>(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<double>(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,
),
],
);
},
),
),
),
),
],

View File

@@ -279,7 +279,7 @@ class LoginScreenState extends State<LoginScreen> {
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<LoginScreen> {
context)
.pop();
},
onDemoMode: () {
Navigator.of(context).pop();
final userProvider = Provider.of<UserProvider>(context, listen: false);
final demoUser = User.demo();
userProvider.addUser(demoUser);
userProvider.setUser(demoUser.id);
setSystemChrome(context);
Navigator.of(context).pushReplacementNamed('login_to_navigation');
},
),
),
),
@@ -382,7 +391,7 @@ class LoginScreenState extends State<LoginScreen> {
)),
),
),
const SizedBox(height: 19),
const SizedBox(height: 12),
// privacy policy
GestureDetector(
onTap: () => PrivacyView.show(context),

View File

@@ -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",
},
};

View File

@@ -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<NavigationScreen>
// 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

View File

@@ -55,9 +55,8 @@ class StatusBarState extends State<StatusBar> {
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
@@ -87,9 +86,8 @@ class StatusBarState extends State<StatusBar> {
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(

View File

@@ -0,0 +1,334 @@
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<void> show(BuildContext context) {
return Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(
builder: (context) => const LiveActivityConsentDialog(),
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = AppColors.of(context);
return Scaffold(
backgroundColor: theme.scaffoldBackgroundColor,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 24.0),
// Header: bell icon + title
Row(
children: [
Icon(
Icons.notifications_active,
color: theme.colorScheme.secondary,
size: 36.0,
),
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,
),
),
),
),
],
),
),
],
),
),
),
);
}
void _respond(BuildContext context, bool accepted) {
final settings = Provider.of<SettingsProvider>(context, listen: false);
final unseen = List<String>.from(settings.unseenNewFeatures);
unseen.remove('live_activity_consent');
if (accepted) {
settings.update(
liveActivityEnabled: true,
liveActivityConsentAccepted: true,
unseenNewFeatures: unseen,
);
} else {
settings.update(
unseenNewFeatures: unseen,
);
}
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),
),
),
],
),
),
],
);
}
}

View File

@@ -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<String> 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(),
);
}
}

View File

@@ -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';
@@ -1044,7 +1046,7 @@ class SettingsScreenState extends State<SettingsScreen>
],
),
// developer options
if (true)
if (settings.developerMode)
SplittedPanel(
title: Text("devsettings".i18n),
cardPadding: const EdgeInsets.all(4.0),
@@ -1083,8 +1085,9 @@ class SettingsScreenState extends State<SettingsScreen>
PanelButton(
borderRadius: BorderRadius.vertical(
top: const Radius.circular(4.0),
bottom: Provider.of<PlusProvider>(context, listen: false)
.hasPremium
bottom: (Platform.isIOS ||
Provider.of<PlusProvider>(context, listen: false)
.hasPremium)
? const Radius.circular(4.0)
: const Radius.circular(12.0),
),
@@ -1097,7 +1100,39 @@ class SettingsScreenState extends State<SettingsScreen>
onPressed: () => Clipboard.setData(ClipboardData(
text: Provider.of<KretaClient>(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;
}
// Trigger LiveCardProvider update immediately
Provider.of<LiveCardProvider>(context, listen: false).update();
},
value: settings.devLiveFakeLessons,
activeColor: Theme.of(context).colorScheme.secondary,
),
),
],
),

View File

@@ -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",
@@ -96,6 +98,64 @@ 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": "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",
@@ -199,6 +259,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",
@@ -224,6 +286,64 @@ 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": "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",
@@ -327,6 +447,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",
@@ -352,6 +474,64 @@ 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": "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",

View File

@@ -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';
@@ -10,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({
@@ -123,6 +127,69 @@ class GeneralSettingsScreenState extends State<GeneralSettingsScreen> {
),
],
),
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: () {
if (!settingsProvider.liveActivityEnabled && !settingsProvider.liveActivityConsentAccepted) {
LiveActivityConsentDialog.show(context).then((_) => setState(() {}));
return;
}
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) {
if (v && !settingsProvider.liveActivityConsentAccepted) {
LiveActivityConsentDialog.show(context).then((_) => setState(() {}));
return;
}
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),