diff --git a/.gitignore b/.gitignore index 04d5b316..f44deb15 100644 --- a/.gitignore +++ b/.gitignore @@ -94,7 +94,11 @@ firka/debug-info/ **/ios/Flutter/flutter_export_environment.sh **/ios/ServiceDefinitions.json **/ios/Runner/GeneratedPluginRegistrant.* -**/ios/Flutter/ +**/ios/Flutter/* +!**/ios/Flutter/Debug.xcconfig +!**/ios/Flutter/Release.xcconfig +!**/ios/Flutter/WidgetExtension.xcconfig +!**/ios/Flutter/AppFrameworkInfo.plist # dart **/.env* diff --git a/README.md b/README.md index 9263437b..920cb19e 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Balkezes mód is van, mert úgy tűnik, van, aki nem volt szerencsés az életbe ## Mit támogattok? -Jelenleg **Androidot** támogatunk (Wear OS-es okosóra-kísérőalkalmazással). +Jelenleg **Androidot** és **iOS-t** támogatunk.
Tervezzük a böngészős támogatást is! diff --git a/README_de.md b/README_de.md index 92aba21e..f521569b 100644 --- a/README_de.md +++ b/README_de.md @@ -38,7 +38,7 @@ Der Einstellungsbildschirm bietet Optionen, von denen du nicht wusstest, dass du ## Was wird unterstützt? -Derzeit unterstützen wir **Android** (mit einer Wear OS Smartwatch-Begleit-App). +Derzeit unterstützen wir **Android** und **iOS**.
Wir planen, auch deinen Browser zu unterstützen! diff --git a/README_en.md b/README_en.md index c153a396..3de349dc 100644 --- a/README_en.md +++ b/README_en.md @@ -38,7 +38,7 @@ The settings screen has options you didn't know you needed. Adjust the bell offs ## What do you support? -Currently, we support **Android** (with a Wear OS smartwatch companion app). +Currently, we support **Android** and **iOS**.
We're planning on supporting your browser also! diff --git a/firka/.env.example b/firka/.env.example index 0dfee9a4..c7fa54b8 100644 --- a/firka/.env.example +++ b/firka/.env.example @@ -3,3 +3,6 @@ # Production: https://your-domain.com/api/v1 BACKEND_BASE_URL=http://192.168.X.YYY:3000/api/v1 BACKEND_API_KEY=development_api_key_12345 + +# Live Activity push server (refilc-live-server) +LIVE_SERVER_URL=https://live.firka.app diff --git a/firka/codegen-lock.yaml b/firka/codegen-lock.yaml index 66411813..90cc896f 100644 --- a/firka/codegen-lock.yaml +++ b/firka/codegen-lock.yaml @@ -1,10 +1,10 @@ icons: - "flutter_launcher_icons.yaml": "993c1cd3a99db70747299601e556d19ec959b0a16fd9ff2dbf2386cb6f2a640d" - "pubspec.yaml": "97e478fd72968c34de0c0ad4421daa9b2e2531d60bb28a893d7d3b5a9a90116c" + "flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1" + "pubspec.yaml": "2dc106a9058067fe175f3ebd53fff68ee7e78261133ac5983af4f8ac88cf97aa" "assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983" "assets/images/logos/monochrome_logo.png": "c269a5e689622484d800a4fda5927591a0bf99d34790a4f146b93cf6edabd455" "assets/images/logos/colored_logo_without_mustache.png": "d11cff9f38985885873bfdd2d84e61f8fab03803eada94d4caac1545ef3685f3" "assets/images/logos/colored_logo_only_mustache.png": "bad6220c11bdfb1dfe04e5173bd2ebedd3999689d4b3a68fc63dc520c96dd33b" splash: - "flutter_native_splash.yaml": "f1bddb74798b1539c4e9213ca9ae305d625ebb0ac5bcbe079b523437e0abc2c4" + "flutter_native_splash.yaml": "64d1847d02072fbd66f90c772ec59c33b4bc304d73a81d6934204a456841ef0c" "assets/images/logos/splash.png": "88fbebc3d686cb9095bcce362029b69978b1b14270e465e91d962b1425db1152" diff --git a/firka/flutter_launcher_icons.yaml b/firka/flutter_launcher_icons.yaml index 446f7a79..bec69ebf 100644 --- a/firka/flutter_launcher_icons.yaml +++ b/firka/flutter_launcher_icons.yaml @@ -1,10 +1,11 @@ flutter_launcher_icons: generate: true android: "launcher_icon" - ios: false image_path: "assets/images/logos/colored_logo.webp" adaptive_icon_monochrome: "assets/images/logos/monochrome_logo.png" adaptive_icon_background: "assets/images/logos/colored_logo_without_mustache.png" adaptive_icon_foreground: "assets/images/logos/colored_logo_only_mustache.png" adaptive_icon_foreground_inset: 0 min_sdk_android: 21 + ios: true + remove_alpha_channel_ios: true diff --git a/firka/flutter_native_splash.yaml b/firka/flutter_native_splash.yaml index 3cd9d5a8..91c3af1b 100644 --- a/firka/flutter_native_splash.yaml +++ b/firka/flutter_native_splash.yaml @@ -18,5 +18,5 @@ flutter_native_splash: icon_background_color_dark: "#7ca120" android: true - ios: false + ios: true web: false diff --git a/firka/ios/.gitignore b/firka/ios/.gitignore new file mode 100644 index 00000000..bf0b2096 --- /dev/null +++ b/firka/ios/.gitignore @@ -0,0 +1,39 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 + +/.DerivedData + +# Developer-specific configuration +.dev_config \ No newline at end of file diff --git a/firka/ios/FirkaWatch Watch App/Assets.xcassets/AccentColor.colorset/Contents.json b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Contents.json b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..5ffa0e32 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "Icon-1024.png", + "idiom" : "universal", + "platform" : "watchos", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Icon-1024.png b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Icon-1024.png new file mode 100644 index 00000000..0b50e8b5 Binary files /dev/null and b/firka/ios/FirkaWatch Watch App/Assets.xcassets/AppIcon.appiconset/Icon-1024.png differ diff --git a/firka/ios/FirkaWatch Watch App/Assets.xcassets/Contents.json b/firka/ios/FirkaWatch Watch App/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatch Watch App/Components/CountdownRing.swift b/firka/ios/FirkaWatch Watch App/Components/CountdownRing.swift new file mode 100644 index 00000000..8841a507 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/CountdownRing.swift @@ -0,0 +1,64 @@ +import SwiftUI + +struct CountdownRing: View { + let totalMinutes: Int + let remainingMinutes: Int + let label: String + var size: CGFloat = 80 + var lineWidth: CGFloat = 8 + var displayOffset: Int = 0 // Add to displayed minutes (e.g., +1) + + private var clampedRemainingMinutes: Int { + guard totalMinutes > 0 else { return 0 } + return max(0, min(remainingMinutes, totalMinutes)) + } + + var progress: Double { + guard totalMinutes > 0 else { return 0 } + return Double(totalMinutes - clampedRemainingMinutes) / Double(totalMinutes) + } + + var displayedMinutes: Int { + max(0, remainingMinutes + displayOffset) + } + + var ringColor: Color { + if clampedRemainingMinutes < 5 { return .red } + if clampedRemainingMinutes < 10 { return .yellow } + return .green + } + + var body: some View { + ZStack { + Circle() + .stroke(Color(white: 0.2), lineWidth: lineWidth) + + Circle() + .trim(from: 0, to: progress) + .stroke(ringColor, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round)) + .rotationEffect(.degrees(-90)) + .animation(.easeInOut, value: progress) + + VStack(spacing: 1) { + Text("\(displayedMinutes)") + .font(size > 60 ? .title2 : .headline) + .fontWeight(.bold) + Text(label) + .font(.caption2) + .foregroundColor(.secondary) + } + } + .frame(width: size, height: size) + } +} + +#Preview { + VStack(spacing: 20) { + CountdownRing(totalMinutes: 45, remainingMinutes: 30, label: "min") + + CountdownRing(totalMinutes: 45, remainingMinutes: 8, label: "min") + + CountdownRing(totalMinutes: 45, remainingMinutes: 3, label: "min") + } + .padding() +} diff --git a/firka/ios/FirkaWatch Watch App/Components/FirkaCard.swift b/firka/ios/FirkaWatch Watch App/Components/FirkaCard.swift new file mode 100644 index 00000000..b74be370 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/FirkaCard.swift @@ -0,0 +1,42 @@ +import SwiftUI + +struct FirkaCard: View { + let content: Content + var isHighlighted: Bool = false + var backgroundColor: Color? = nil + + init( + isHighlighted: Bool = false, + backgroundColor: Color? = nil, + @ViewBuilder content: () -> Content + ) { + self.isHighlighted = isHighlighted + self.backgroundColor = backgroundColor + self.content = content() + } + + var body: some View { + content + .padding(12) + .background( + backgroundColor ?? + (isHighlighted ? Color.green.opacity(0.2) : Color(white: 0.12)) + ) + .cornerRadius(12) + } +} + +#Preview { + VStack(spacing: 12) { + FirkaCard { + Text("Normal Card") + .foregroundColor(.primary) + } + + FirkaCard(isHighlighted: true) { + Text("Highlighted Card") + .foregroundColor(.primary) + } + } + .padding() +} diff --git a/firka/ios/FirkaWatch Watch App/Components/GradeBadge.swift b/firka/ios/FirkaWatch Watch App/Components/GradeBadge.swift new file mode 100644 index 00000000..223c411e --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/GradeBadge.swift @@ -0,0 +1,39 @@ +import SwiftUI + +struct GradeBadge: View { + let grade: Int + var size: CGFloat = 24 + + var color: Color { + switch grade { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + default: return .red + } + } + + var body: some View { + ZStack { + Circle() + .fill(color) + .frame(width: size, height: size) + + Text("\(grade)") + .font(.system(size: size * 0.5, weight: .bold)) + .foregroundColor(.white) + } + } +} + +#Preview { + HStack(spacing: 12) { + GradeBadge(grade: 5) + GradeBadge(grade: 4) + GradeBadge(grade: 3) + GradeBadge(grade: 2) + GradeBadge(grade: 1) + } + .padding() +} diff --git a/firka/ios/FirkaWatch Watch App/Components/GradeRow.swift b/firka/ios/FirkaWatch Watch App/Components/GradeRow.swift new file mode 100644 index 00000000..1b83f1de --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/GradeRow.swift @@ -0,0 +1,46 @@ +import SwiftUI + +struct GradeRow: View { + let grade: WidgetGrade + + var body: some View { + HStack(alignment: .center, spacing: 8) { + Text(grade.displayValue) + .font(.caption) + .fontWeight(.semibold) + .foregroundColor(.white) + .frame(width: 24, height: 24) + .background( + Circle() + .fill(grade.gradeColor) + ) + + VStack(alignment: .leading, spacing: 2) { + if let topic = grade.topic { + Text(topic) + .font(.caption2) + .foregroundColor(.primary) + .lineLimit(2) + } + + HStack(spacing: 4) { + Text(grade.type.name) + .font(.system(size: 10)) + .foregroundColor(.secondary) + + if let weight = grade.weightPercentage, weight != 100 { + Text("(\(weight)%)") + .font(.system(size: 10)) + .foregroundColor(.secondary) + } + } + } + + Spacer() + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + .background(Color(white: 0.15)) + .cornerRadius(6) + } +} diff --git a/firka/ios/FirkaWatch Watch App/Components/LessonCard.swift b/firka/ios/FirkaWatch Watch App/Components/LessonCard.swift new file mode 100644 index 00000000..3ba2ea71 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/LessonCard.swift @@ -0,0 +1,146 @@ +import SwiftUI + +struct LessonCard: View { + let lesson: WidgetLesson + let isActive: Bool + let colors: WidgetColors? + + var backgroundColor: Color { + if let colors = colors { + return colors.cardColor + } + return Color(white: 0.15) + } + + var textPrimaryColor: Color { + if let colors = colors { + return colors.textPrimaryColor + } + return .primary + } + + var textSecondaryColor: Color { + if let colors = colors { + return colors.textSecondaryColor + } + return .secondary + } + + var textTertiaryColor: Color { + if let colors = colors { + return colors.textTertiaryColor + } + return .secondary.opacity(0.7) + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .top, spacing: 8) { + if let number = lesson.lessonNumber { + Text("\(number)") + .font(.headline) + .fontWeight(.semibold) + .foregroundColor(isActive ? .white : textPrimaryColor) + .frame(width: 28, height: 28) + .background( + Circle() + .fill(isActive ? Color.green : Color.clear) + ) + } + + VStack(alignment: .leading, spacing: 2) { + Text(lesson.displayName) + .font(.headline) + .fontWeight(.semibold) + .foregroundColor(lesson.isCancelled ? .red : + lesson.isSubstitution ? .orange : textPrimaryColor) + .strikethrough(lesson.isCancelled, color: .red) + .lineLimit(1) + + Text(lesson.timeString) + .font(.caption2) + .foregroundColor(lesson.isCancelled ? .red.opacity(0.8) : + lesson.isSubstitution ? .orange.opacity(0.8) : textSecondaryColor) + } + + Spacer() + } + + if let room = lesson.roomName { + HStack(spacing: 4) { + Image(systemName: "door.right.hand.closed") + .font(.caption2) + Text(room) + .font(.caption2) + } + .foregroundColor(lesson.isCancelled ? .red.opacity(0.7) : + lesson.isSubstitution ? .orange.opacity(0.7) : textSecondaryColor) + .lineLimit(1) + } + + if let teacher = lesson.teacher { + Text(teacher) + .font(.caption2) + .foregroundColor(lesson.isCancelled ? .red.opacity(0.7) : + lesson.isSubstitution ? .orange.opacity(0.7) : textTertiaryColor) + .lineLimit(1) + } + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(backgroundColor) + .cornerRadius(10) + .overlay( + RoundedRectangle(cornerRadius: 10) + .stroke( + isActive ? Color.green : Color.clear, + lineWidth: isActive ? 2 : 0 + ) + ) + } +} + +#Preview { + VStack(spacing: 12) { + LessonCard( + lesson: WidgetLesson( + uid: "1", + date: "2026-02-01", + start: Date(), + end: Date().addingTimeInterval(3600), + name: "Matematika", + lessonNumber: 3, + teacher: "Nagy János", + substituteTeacher: nil, + subject: WidgetSubject(uid: "math", name: "Matematika", category: nil, sortIndex: 1, teacherName: "Nagy János"), + theme: nil, + roomName: "201", + isCancelled: false, + isSubstitution: false + ), + isActive: true, + colors: nil + ) + + LessonCard( + lesson: WidgetLesson( + uid: "2", + date: "2026-02-01", + start: Date().addingTimeInterval(7200), + end: Date().addingTimeInterval(10800), + name: "Angol", + lessonNumber: 4, + teacher: "Kovács Éva", + substituteTeacher: nil, + subject: WidgetSubject(uid: "eng", name: "Angol", category: nil, sortIndex: 2, teacherName: "Kovács Éva"), + theme: nil, + roomName: "105", + isCancelled: false, + isSubstitution: false + ), + isActive: false, + colors: nil + ) + } + .padding() +} diff --git a/firka/ios/FirkaWatch Watch App/Components/ProgressBar.swift b/firka/ios/FirkaWatch Watch App/Components/ProgressBar.swift new file mode 100644 index 00000000..4c3bcc04 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/ProgressBar.swift @@ -0,0 +1,68 @@ +import SwiftUI + +struct AverageProgressBar: View { + let average: Double + + var progress: Double { + (average - 1) / 4 + } + + var color: Color { + switch average { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } + + var body: some View { + GeometryReader { geo in + ZStack(alignment: .leading) { + RoundedRectangle(cornerRadius: 2) + .fill(Color(white: 0.3)) + + RoundedRectangle(cornerRadius: 2) + .fill(color) + .frame(width: geo.size.width * progress) + } + } + .frame(height: 4) + } +} + +#Preview { + VStack(spacing: 16) { + VStack(alignment: .leading) { + Text("5.0 - Excellent") + .font(.caption) + AverageProgressBar(average: 5.0) + } + + VStack(alignment: .leading) { + Text("4.2 - Good") + .font(.caption) + AverageProgressBar(average: 4.2) + } + + VStack(alignment: .leading) { + Text("3.0 - Average") + .font(.caption) + AverageProgressBar(average: 3.0) + } + + VStack(alignment: .leading) { + Text("2.0 - Below Average") + .font(.caption) + AverageProgressBar(average: 2.0) + } + + VStack(alignment: .leading) { + Text("1.2 - Poor") + .font(.caption) + AverageProgressBar(average: 1.2) + } + } + .padding() +} diff --git a/firka/ios/FirkaWatch Watch App/Components/SubjectRow.swift b/firka/ios/FirkaWatch Watch App/Components/SubjectRow.swift new file mode 100644 index 00000000..23407ec1 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Components/SubjectRow.swift @@ -0,0 +1,43 @@ +import SwiftUI + +struct SubjectRow: View { + let name: String + let average: Double? + let gradeCount: Int + + var averageColor: Color { + guard let avg = average else { return .gray } + switch avg { + case 4.5...: return .green + case 3.5...: return .blue + case 2.5...: return .yellow + case 1.5...: return .orange + default: return .red + } + } + + var body: some View { + HStack(alignment: .center, spacing: 8) { + Text(name) + .font(.caption) + .foregroundColor(.primary) + + Spacer() + + if let avg = average { + Text(String(format: "%.2f", avg)) + .font(.caption) + .fontWeight(.bold) + .foregroundColor(averageColor) + } else { + Text("\(gradeCount)") + .font(.caption) + .foregroundColor(.secondary) + } + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + .background(Color(white: 0.15)) + .cornerRadius(6) + } +} diff --git a/firka/ios/FirkaWatch Watch App/ContentView.swift b/firka/ios/FirkaWatch Watch App/ContentView.swift new file mode 100644 index 00000000..919c8400 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/ContentView.swift @@ -0,0 +1,189 @@ +import SwiftUI +import WatchConnectivity +internal import Combine + +struct ContentView: View { + var dataStore = DataStore.shared + @State private var selectedTab = 0 + @State private var isRequestingToken = false + @Environment(\.scenePhase) private var scenePhase + + private let staleCheckTimer = Timer.publish(every: 30, on: .main, in: .common).autoconnect() + + private let autoRefreshThreshold: TimeInterval = 10 * 60 + + var body: some View { + Group { + if dataStore.isRecoveringToken { + VStack(spacing: 16) { + ProgressView() + .scaleEffect(1.2) + Text("recovering_token".localized) + .font(.caption) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + } + .padding() + } + else if dataStore.needsReauth && dataStore.hasToken { + ReauthRequiredView(onTokenReceived: { + dataStore.resetRecoveryState() + dataStore.checkTokenState() + Task { + await dataStore.refreshAllWithRecovery() + } + }) + } else if !dataStore.hasToken && dataStore.data == nil { + if isRequestingToken { + ProgressView("connecting".localized) + } else { + PairingView(onRequestToken: requestToken) + } + } else { + mainContent + } + } + .task { + dataStore.reconcileSharedSessionState() + WatchL10n.shared.reconcileFromSharedState() + dataStore.checkTokenState() + dataStore.loadFromCache() + if dataStore.hasToken { + await dataStore.refreshAllWithRecovery() + } else { + requestToken() + } + } + .onChange(of: scenePhase) { oldPhase, newPhase in + if newPhase == .active && oldPhase != .active { + dataStore.reconcileSharedSessionState() + WatchL10n.shared.reconcileFromSharedState() + if shouldAutoRefresh { + print("[Watch] App came to foreground, data is stale (>10 min), refreshing...") + Task { + await dataStore.refreshAllWithRecovery() + } + } else { + print("[Watch] App came to foreground, data is fresh (<10 min), skipping refresh") + } + } + } + .onReceive(staleCheckTimer) { _ in + guard scenePhase == .active else { return } + dataStore.reconcileSharedSessionState() + WatchL10n.shared.reconcileFromSharedState() + + if !dataStore.hasToken { + dataStore.checkTokenState() + if dataStore.hasToken { + print("[Watch] Token appeared (iCloud Keychain sync?), refreshing...") + Task { + await dataStore.refreshAllWithRecovery() + } + } + return + } + + if shouldAutoRefresh && !dataStore.isLoading { + print("[Watch] Data became stale (>10 min), auto-refreshing...") + Task { + await dataStore.refreshAllWithRecovery() + } + } + } + } + + private var shouldAutoRefresh: Bool { + guard dataStore.hasToken else { return false } + guard let lastUpdated = dataStore.lastUpdated else { return true } + let elapsed = Date().timeIntervalSince(lastUpdated) + return elapsed >= autoRefreshThreshold + } + + private func requestToken() { + guard !isRequestingToken else { return } + guard WCSession.default.activationState == .activated else { + print("[Watch] Cannot request token: session not activated") + return + } + guard WCSession.default.isReachable else { + print("[Watch] Cannot request token: iPhone not reachable") + return + } + + print("[Watch] Requesting token from iPhone...") + isRequestingToken = true + WatchConnectivityManager.shared.requestTokenFromPhone() + + DispatchQueue.main.asyncAfter(deadline: .now() + 10) { + self.isRequestingToken = false + } + } + + private var mainContent: some View { + TabView(selection: $selectedTab) { + HomeView(dataStore: dataStore) + .tag(0) + + TimetableView(dataStore: dataStore) + .tag(1) + + GradesView(dataStore: dataStore) + .tag(2) + + NavigationStack { + SettingsView() + } + .tag(3) + } + .tabViewStyle(.verticalPage) + } +} + +struct PairingView: View { + var onRequestToken: (() -> Void)? + + private var isWatchSystemPaired: Bool { + guard WCSession.isSupported() else { return false } + return WCSession.default.isCompanionAppInstalled + } + + private var titleKey: String { + isWatchSystemPaired ? "login_on_iphone" : "pair_with_iphone" + } + + private var descriptionKey: String { + isWatchSystemPaired ? "open_and_login_on_iphone" : "open_firka_on_iphone" + } + + private var iconName: String { + isWatchSystemPaired + ? "person.crop.circle.badge.exclamationmark" + : "iphone.and.arrow.right.inward" + } + + var body: some View { + VStack(spacing: 10) { + Image(systemName: iconName) + .font(.system(size: 36)) + .foregroundColor(.blue) + + Text(titleKey.localized) + .font(.headline) + + Text(descriptionKey.localized) + .font(.caption2) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal) + + if isWatchSystemPaired { + Button("sync_button".localized) { + onRequestToken?() + } + .buttonStyle(.borderedProminent) + } + } + .padding() + } +} diff --git a/firka/ios/FirkaWatch Watch App/FirkaWatch Watch App.entitlements b/firka/ios/FirkaWatch Watch App/FirkaWatch Watch App.entitlements new file mode 100644 index 00000000..1d2765fb --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/FirkaWatch Watch App.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.developer.ubiquity-kvstore-identifier + $(TeamIdentifierPrefix)app.firkaa.legacy + com.apple.security.application-groups + + group.app.firkaa.legacy + + keychain-access-groups + + $(AppIdentifierPrefix)app.firka.shared + + + diff --git a/firka/ios/FirkaWatch Watch App/FirkaWatchApp.swift b/firka/ios/FirkaWatch Watch App/FirkaWatchApp.swift new file mode 100644 index 00000000..37390e81 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/FirkaWatchApp.swift @@ -0,0 +1,35 @@ +import SwiftUI +import WatchKit + +@main +struct FirkaWatchApp: App { + @WKApplicationDelegateAdaptor(WatchAppDelegate.self) var delegate + + var body: some Scene { + WindowGroup { + ContentView() + .preferredColorScheme(.dark) + } + } +} + +class WatchAppDelegate: NSObject, WKApplicationDelegate { + func applicationDidFinishLaunching() { + print("[Watch] applicationDidFinishLaunching called") + WatchConnectivityManager.shared.activate() + } + + func handle(_ backgroundTasks: Set) { + for task in backgroundTasks { + switch task { + case let refreshTask as WKApplicationRefreshBackgroundTask: + Task { + await BackgroundRefreshManager.shared.handleBackgroundRefresh() + refreshTask.setTaskCompletedWithSnapshot(false) + } + default: + task.setTaskCompletedWithSnapshot(false) + } + } + } +} diff --git a/firka/ios/FirkaWatch Watch App/Localization/WatchL10n.swift b/firka/ios/FirkaWatch Watch App/Localization/WatchL10n.swift new file mode 100644 index 00000000..c328fd25 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Localization/WatchL10n.swift @@ -0,0 +1,464 @@ +import Foundation +import SwiftUI +import WidgetKit + +enum WatchLanguage: String, CaseIterable, Codable { + case hungarian = "hu" + case english = "en" + case german = "de" + + var displayName: String { + switch self { + case .hungarian: return "Magyar" + case .english: return "English" + case .german: return "Deutsch" + } + } + + var flag: String { + switch self { + case .hungarian: return "🇭🇺" + case .english: return "🇬🇧" + case .german: return "🇩🇪" + } + } +} + +@Observable +class WatchL10n { + static let shared = WatchL10n() + + private let languageKey = "watch_language" + private let syncWithiPhoneKey = "watch_sync_language_with_iphone" + private let lastAppliedSharedLanguageVersionKey = "watch_last_applied_shared_language_version" + private static let appGroupID = "group.app.firkaa.legacy" + private var appGroupDefaults: UserDefaults? { + UserDefaults(suiteName: Self.appGroupID) + } + + var currentLanguage: WatchLanguage { + didSet { + UserDefaults.standard.set(currentLanguage.rawValue, forKey: languageKey) + appGroupDefaults?.set(currentLanguage.rawValue, forKey: languageKey) + } + } + + var syncWithiPhone: Bool { + didSet { + UserDefaults.standard.set(syncWithiPhone, forKey: syncWithiPhoneKey) + appGroupDefaults?.set(syncWithiPhone, forKey: syncWithiPhoneKey) + if syncWithiPhone { + refreshFromiPhoneAndSharedState() + } + } + } + + private var strings: [String: String] = [:] + + private init() { + let savedLanguage = UserDefaults.standard.string(forKey: languageKey) ?? "hu" + self.currentLanguage = WatchLanguage(rawValue: savedLanguage) ?? .hungarian + if let storedSyncPref = UserDefaults.standard.object(forKey: syncWithiPhoneKey) as? Bool { + self.syncWithiPhone = storedSyncPref + } else { + self.syncWithiPhone = true + UserDefaults.standard.set(true, forKey: syncWithiPhoneKey) + appGroupDefaults?.set(true, forKey: syncWithiPhoneKey) + } + appGroupDefaults?.set(currentLanguage.rawValue, forKey: languageKey) + loadStrings() + } + + private func loadStrings() { + strings = Self.stringsForLanguage(currentLanguage) + } + + func setLanguage(_ language: WatchLanguage) { + if Thread.isMainThread { + currentLanguage = language + loadStrings() + WidgetCenter.shared.reloadAllTimelines() + } else { + DispatchQueue.main.async { [self] in + currentLanguage = language + loadStrings() + WidgetCenter.shared.reloadAllTimelines() + } + } + } + + func updateFromiPhone(languageCode: String, sharedStateVersion: Int64? = nil) { + guard syncWithiPhone else { return } + let lastAppliedVersion = lastAppliedSharedLanguageVersion() + if let sharedStateVersion, + sharedStateVersion > 0, + sharedStateVersion < lastAppliedVersion { + print("[WatchL10n] Ignoring stale WC language update (version: \(sharedStateVersion), lastApplied: \(lastAppliedVersion))") + return + } + + if let language = WatchLanguage(rawValue: languageCode) { + if language != currentLanguage { + setLanguage(language) + } + if let sharedStateVersion, sharedStateVersion > 0 { + setLastAppliedSharedLanguageVersion(max(lastAppliedVersion, sharedStateVersion)) + } + } + } + + private func parseInt64(_ value: Any?) -> Int64? { + if let value = value as? Int64 { return value } + if let value = value as? Int { return Int64(value) } + if let value = value as? Double { return Int64(value) } + if let value = value as? String, let parsed = Int64(value) { return parsed } + return nil + } + + private func lastAppliedSharedLanguageVersion() -> Int64 { + parseInt64(UserDefaults.standard.object(forKey: lastAppliedSharedLanguageVersionKey)) ?? 0 + } + + private func setLastAppliedSharedLanguageVersion(_ value: Int64) { + UserDefaults.standard.set(value, forKey: lastAppliedSharedLanguageVersionKey) + } + + func resetLanguageVersionTracking() { + setLastAppliedSharedLanguageVersion(0) + print("[WatchL10n] Language version tracking reset for account switch") + } + + func reconcileFromSharedState() { + guard syncWithiPhone else { return } + guard let sharedState = SharedLanguageStateManager.shared.loadState() else { return } + let lastAppliedVersion = lastAppliedSharedLanguageVersion() + guard sharedState.stateVersion > lastAppliedVersion else { return } + + if let language = WatchLanguage(rawValue: sharedState.languageCode) { + if language != currentLanguage { + setLanguage(language) + } + setLastAppliedSharedLanguageVersion(sharedState.stateVersion) + } + } + + func refreshFromiPhoneAndSharedState() { + guard syncWithiPhone else { return } + requestLanguageFromiPhone() + reconcileFromSharedState() + } + + private func requestLanguageFromiPhone() { + WatchConnectivityManager.shared.requestLanguageFromPhone() + } + + func string(_ key: String) -> String { + return strings[key] ?? key + } + + func string(_ key: String, _ args: CVarArg...) -> String { + let format = strings[key] ?? key + return String(format: format, arguments: args) + } + + static func stringsForLanguage(_ language: WatchLanguage) -> [String: String] { + switch language { + case .hungarian: + return hungarianStrings + case .english: + return englishStrings + case .german: + return germanStrings + } + } + + private static let hungarianStrings: [String: String] = [ + // Home View + "current_lesson": "Jelenlegi óra", + "next": "Következő", + "break": "Szünet", + "next_lesson": "Következő: %@", + "first_lesson": "Első órád", + "today_lessons_count": "Ma %d órád van", + "no_more_lessons": "Ma nincs több órád", + "pair_with_iphone": "Párosítsd az iPhone-oddal", + "open_firka_on_iphone": "Nyisd meg a Firka appot az iPhone-odon", + "login_on_iphone": "Jelentkezz be iPhone-on", + "open_and_login_on_iphone": "Nyisd meg a Firka appot iPhone-on, és lépj be egy fiókba", + "updated": "Frissítve: %@", + "minutes": "perc", + "time_now": "most", + "time_hours_minutes": "%d ó %d p", + "time_hours": "%d óra", + "time_minutes_only": "%d perc", + "time_since_minutes_one": "1 perce", + "time_since_minutes_many": "%d perce", + "time_since_hours_one": "1 órája", + "time_since_hours_many": "%d órája", + "time_since_days_one": "1 napja", + "time_since_days_many": "%d napja", + + // Timetable View + "free_day": "Szabad nap", + "lesson_number": "%d. óra", + "day_mon": "H", + "day_tue": "K", + "day_wed": "Sz", + "day_thu": "Cs", + "day_fri": "P", + + // Grades View + "grades_count": "%d jegy", + "total_average": "Teljes átlag", + "average": "Átlag:", + "no_data": "Nincs adat", + "no_grades": "Nincsenek jegyek", + + // Lesson Detail + "lesson_details": "Óra részletei", + "cancelled": "Elmarad", + "substitution": "Helyettesítés", + "teacher": "Tanár", + "room": "Terem", + "topic": "Téma", + + // Settings + "settings": "Beállítások", + "refresh_interval": "Frissítési időköz", + "auto": "Automatikus", + "15_minutes": "15 perc", + "30_minutes": "30 perc", + "1_hour": "1 óra", + "version": "Verzió", + "language": "Nyelv", + "sync_with_iphone": "iPhone nyelvével", + "clear_cache": "Cache törlése", + "logout": "Kijelentkezés", + + // Refresh + "refresh": "Frissítés", + "refreshing": "Frissítés...", + "refresh_success": "Sikeres!", + "refresh_failed": "Sikertelen", + "error_api": "Kréta API hiba", + "error_network": "Hálózati hiba", + + // Date labels + "tomorrow_first_lesson": "Holnap első órád", + "day_first_lesson": "%@ első órád", + "next_school_day": "Következő iskolai nap", + + // Navigation + "home": "Kezdőlap", + "timetable": "Órarend", + "grades": "Jegyek", + + // Reauth + "reauth_required": "Újrabelépés szükséges", + "reauth_description": "A munkamenet lejárt. Lépj be újra az iPhone appban.", + "sync_button": "Szinkronizálás", + "syncing": "Szinkronizálás...", + "sync_success": "Sikeres!", + "sync_failed": "Sikertelen", + "phone_not_reachable": "iPhone nem elérhető", + "connecting": "Kapcsolódás...", + "recovering_token": "Token helyreállítása...", + ] + + private static let englishStrings: [String: String] = [ + // Home View + "current_lesson": "Current Lesson", + "next": "Next", + "break": "Break", + "next_lesson": "Next: %@", + "first_lesson": "First Lesson", + "today_lessons_count": "You have %d lessons today", + "no_more_lessons": "No more lessons today", + "pair_with_iphone": "Pair with iPhone", + "open_firka_on_iphone": "Open Firka app on your iPhone", + "login_on_iphone": "Sign in on iPhone", + "open_and_login_on_iphone": "Open Firka on your iPhone and sign in to an account", + "updated": "Updated: %@", + "minutes": "min", + "time_now": "now", + "time_hours_minutes": "%dh %dm", + "time_hours": "%d hours", + "time_minutes_only": "%d min", + "time_since_minutes_one": "1 min ago", + "time_since_minutes_many": "%d mins ago", + "time_since_hours_one": "1 hour ago", + "time_since_hours_many": "%d hours ago", + "time_since_days_one": "1 day ago", + "time_since_days_many": "%d days ago", + + // Timetable View + "free_day": "Free Day", + "lesson_number": "Lesson %d", + "day_mon": "Mon", + "day_tue": "Tue", + "day_wed": "Wed", + "day_thu": "Thu", + "day_fri": "Fri", + + // Grades View + "grades_count": "%d grades", + "total_average": "Total Average", + "average": "Average:", + "no_data": "No data", + "no_grades": "No grades", + + // Lesson Detail + "lesson_details": "Lesson Details", + "cancelled": "Cancelled", + "substitution": "Substitution", + "teacher": "Teacher", + "room": "Room", + "topic": "Topic", + + // Settings + "settings": "Settings", + "refresh_interval": "Refresh Interval", + "auto": "Auto", + "15_minutes": "15 minutes", + "30_minutes": "30 minutes", + "1_hour": "1 hour", + "version": "Version", + "language": "Language", + "sync_with_iphone": "Sync with iPhone", + "clear_cache": "Clear Cache", + "logout": "Log Out", + + // Refresh + "refresh": "Refresh", + "refreshing": "Refreshing...", + "refresh_success": "Success!", + "refresh_failed": "Failed", + "error_api": "Kréta API Error", + "error_network": "Network Error", + + // Date labels + "tomorrow_first_lesson": "Tomorrow's first lesson", + "day_first_lesson": "%@'s first lesson", + "next_school_day": "Next school day", + + // Navigation + "home": "Home", + "timetable": "Timetable", + "grades": "Grades", + + // Reauth + "reauth_required": "Re-login Required", + "reauth_description": "Your session has expired. Please log in again on your iPhone.", + "sync_button": "Sync", + "syncing": "Syncing...", + "sync_success": "Success!", + "sync_failed": "Failed", + "phone_not_reachable": "iPhone not reachable", + "connecting": "Connecting...", + "recovering_token": "Recovering session...", + ] + + private static let germanStrings: [String: String] = [ + // Home View + "current_lesson": "Aktuelle Stunde", + "next": "Nächste", + "break": "Pause", + "next_lesson": "Nächste: %@", + "first_lesson": "Erste Stunde", + "today_lessons_count": "Du hast heute %d Stunden", + "no_more_lessons": "Keine Stunden mehr heute", + "pair_with_iphone": "Mit iPhone koppeln", + "open_firka_on_iphone": "Öffne Firka auf deinem iPhone", + "login_on_iphone": "Auf iPhone anmelden", + "open_and_login_on_iphone": "Öffne Firka auf deinem iPhone und melde dich mit einem Konto an", + "updated": "Aktualisiert: %@", + "minutes": "Min", + "time_now": "jetzt", + "time_hours_minutes": "%d Std %d Min", + "time_hours": "%d Stunden", + "time_minutes_only": "%d Min", + "time_since_minutes_one": "vor 1 Min", + "time_since_minutes_many": "vor %d Min", + "time_since_hours_one": "vor 1 Std", + "time_since_hours_many": "vor %d Std", + "time_since_days_one": "vor 1 Tag", + "time_since_days_many": "vor %d Tagen", + + // Timetable View + "free_day": "Freier Tag", + "lesson_number": "%d. Stunde", + "day_mon": "Mo", + "day_tue": "Di", + "day_wed": "Mi", + "day_thu": "Do", + "day_fri": "Fr", + + // Grades View + "grades_count": "%d Noten", + "total_average": "Gesamtdurchschnitt", + "average": "Durchschnitt:", + "no_data": "Keine Daten", + "no_grades": "Keine Noten", + + // Lesson Detail + "lesson_details": "Stundendetails", + "cancelled": "Entfällt", + "substitution": "Vertretung", + "teacher": "Lehrer", + "room": "Raum", + "topic": "Thema", + + // Settings + "settings": "Einstellungen", + "refresh_interval": "Aktualisierungsintervall", + "auto": "Automatisch", + "15_minutes": "15 Minuten", + "30_minutes": "30 Minuten", + "1_hour": "1 Stunde", + "version": "Version", + "language": "Sprache", + "sync_with_iphone": "Mit iPhone synchronisieren", + "clear_cache": "Cache löschen", + "logout": "Abmelden", + + // Refresh + "refresh": "Aktualisieren", + "refreshing": "Wird aktualisiert...", + "refresh_success": "Erfolgreich!", + "refresh_failed": "Fehlgeschlagen", + "error_api": "Kréta API Fehler", + "error_network": "Netzwerkfehler", + + // Date labels + "tomorrow_first_lesson": "Morgen erste Stunde", + "day_first_lesson": "%@ erste Stunde", + "next_school_day": "Nächster Schultag", + + // Navigation + "home": "Startseite", + "timetable": "Stundenplan", + "grades": "Noten", + + // Reauth + "reauth_required": "Erneute Anmeldung erforderlich", + "reauth_description": "Ihre Sitzung ist abgelaufen. Bitte melden Sie sich erneut auf dem iPhone an.", + "sync_button": "Synchronisieren", + "syncing": "Synchronisierung...", + "sync_success": "Erfolgreich!", + "sync_failed": "Fehlgeschlagen", + "phone_not_reachable": "iPhone nicht erreichbar", + "connecting": "Verbindung...", + "recovering_token": "Sitzung wiederherstellen...", + ] +} + +extension String { + var localized: String { + WatchL10n.shared.string(self) + } + + func localized(_ args: CVarArg...) -> String { + let format = WatchL10n.shared.string(self) + return String(format: format, arguments: args) + } +} diff --git a/firka/ios/FirkaWatch Watch App/Services/BackgroundRefreshManager.swift b/firka/ios/FirkaWatch Watch App/Services/BackgroundRefreshManager.swift new file mode 100644 index 00000000..451e85e3 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Services/BackgroundRefreshManager.swift @@ -0,0 +1,120 @@ +import Foundation +import WatchKit +import WidgetKit + +class BackgroundRefreshManager { + static let shared = BackgroundRefreshManager() + + private init() {} + + func scheduleNextRefresh() { + let interval = calculateOptimalRefreshInterval() + + let preferredDate = Date().addingTimeInterval(interval) + WKApplication.shared().scheduleBackgroundRefresh( + withPreferredDate: preferredDate, + userInfo: nil + ) { error in + if let error = error { + print("[BackgroundRefresh] Schedule error: \(error)") + } else { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + print("[BackgroundRefresh] Next refresh scheduled at: \(formatter.string(from: preferredDate)) (\(Int(interval/60)) min)") + } + } + } + + private func calculateOptimalRefreshInterval() -> TimeInterval { + let userRefreshMinutes = UserDefaults.standard.integer(forKey: "refreshInterval") + let now = Date() + let calendar = Calendar.current + + let todayLessons = getTodayLessons() + + guard !todayLessons.isEmpty else { + return getDefaultInterval(userSetting: userRefreshMinutes, now: now, calendar: calendar) + } + + let sortedLessons = todayLessons.sorted { $0.start < $1.start } + + guard let firstLesson = sortedLessons.first, + let lastLesson = sortedLessons.last else { + return getDefaultInterval(userSetting: userRefreshMinutes, now: now, calendar: calendar) + } + + let firstStart = firstLesson.start + let lastEnd = lastLesson.end + + let schoolStartBuffer = firstStart.addingTimeInterval(-30 * 60) + + if now < schoolStartBuffer { + let intervalUntilWakeUp = schoolStartBuffer.timeIntervalSince(now) + let interval = max(intervalUntilWakeUp, 15 * 60) + print("[BackgroundRefresh] Before school - next refresh in \(Int(interval/60)) min (30 min before first lesson)") + return min(interval, 60 * 60) // Max 1 hour + } + + if now >= schoolStartBuffer && now <= lastEnd { + let interval = TimeInterval((userRefreshMinutes > 0 ? userRefreshMinutes : 15) * 60) + print("[BackgroundRefresh] During school - using \(Int(interval/60)) min interval") + return interval + } + + let tomorrowLessons = getTomorrowLessons() + if !tomorrowLessons.isEmpty, + let tomorrowFirst = tomorrowLessons.sorted(by: { $0.start < $1.start }).first { + + let tomorrowStartBuffer = tomorrowFirst.start.addingTimeInterval(-30 * 60) + let timeUntilTomorrowWakeUp = tomorrowStartBuffer.timeIntervalSince(now) + + if timeUntilTomorrowWakeUp > 2 * 60 * 60 { + print("[BackgroundRefresh] After school - 1 hour interval (tomorrow's first lesson in \(Int(timeUntilTomorrowWakeUp/60)) min)") + return 60 * 60 + } else { + print("[BackgroundRefresh] After school, tomorrow soon - 30 min interval") + return 30 * 60 + } + } + + print("[BackgroundRefresh] After school, no tomorrow lessons - 1 hour interval") + return 60 * 60 + } + + private func getDefaultInterval(userSetting: Int, now: Date, calendar: Calendar) -> TimeInterval { + if userSetting > 0 { + print("[BackgroundRefresh] No timetable - using user setting: \(userSetting) min") + return TimeInterval(userSetting * 60) + } + + let hour = calendar.component(.hour, from: now) + let weekday = calendar.component(.weekday, from: now) + let isWeekday = weekday >= 2 && weekday <= 6 + + if isWeekday && hour >= 6 && hour <= 16 { + print("[BackgroundRefresh] No timetable - weekday school hours: 15 min") + return 15 * 60 + } else { + print("[BackgroundRefresh] No timetable - off hours: 1 hour") + return 60 * 60 + } + } + + private func getTodayLessons() -> [WidgetLesson] { + guard let data = DataStore.shared.data else { return [] } + return data.timetable.today + } + + private func getTomorrowLessons() -> [WidgetLesson] { + guard let data = DataStore.shared.data else { return [] } + return data.timetable.tomorrow + } + + func handleBackgroundRefresh() async { + await DataStore.shared.refreshAllWithRecovery() + + WidgetCenter.shared.reloadAllTimelines() + + scheduleNextRefresh() + } +} diff --git a/firka/ios/FirkaWatch Watch App/Services/DataStore.swift b/firka/ios/FirkaWatch Watch App/Services/DataStore.swift new file mode 100644 index 00000000..7d99fbfb --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Services/DataStore.swift @@ -0,0 +1,551 @@ +import Foundation +import Observation +import WidgetKit + +// MARK: - Cache Wrapper + +struct CachedWatchData: Codable { + let widgetData: WidgetData + let lastUpdated: Date +} + +// MARK: - DataStore + +@Observable +class DataStore { + static let shared = DataStore() + + var data: WidgetData? + var lastUpdated: Date? + var isLoading: Bool = false + var error: String? + + var isRecoveringToken: Bool = false + + private(set) var recoveryAttempted: Bool = false + + private(set) var hasToken: Bool = false + + var needsReauth: Bool { + (error == "token_expired" || error == "no_token") && recoveryAttempted && !isRecoveringToken + } + + private let appGroupID = "group.app.firkaa.legacy" + private let cacheFileName = "watch_data.json" + private let lastHandledSessionStateVersionKey = "firka.watch.last_handled_session_state_version" + private let lastHandledSessionActiveStudentIdNormKey = "firka.watch.last_handled_session_active_student_id_norm" + + private init() { + checkTokenState() + loadFromCache() + } + + + var hasValidToken: Bool { + TokenManager.shared.loadToken() != nil + } + + func checkTokenState() { + hasToken = TokenManager.shared.loadToken() != nil + print("[Watch] Token state updated: hasToken = \(hasToken)") + } + + private func parseInt64(_ value: Any?) -> Int64? { + if let value = value as? Int64 { return value } + if let value = value as? Int { return Int64(value) } + if let value = value as? Double { return Int64(value) } + if let value = value as? String, let parsed = Int64(value) { return parsed } + return nil + } + + private func lastHandledSessionStateVersion() -> Int64 { + parseInt64(UserDefaults.standard.object(forKey: lastHandledSessionStateVersionKey)) ?? 0 + } + + private func setLastHandledSessionStateVersion(_ value: Int64) { + UserDefaults.standard.set(value, forKey: lastHandledSessionStateVersionKey) + } + + private func lastHandledSessionActiveStudentIdNorm() -> Int64? { + parseInt64(UserDefaults.standard.object(forKey: lastHandledSessionActiveStudentIdNormKey)) + } + + private func setLastHandledSessionActiveStudentIdNorm(_ value: Int64?) { + if let value { + UserDefaults.standard.set(value, forKey: lastHandledSessionActiveStudentIdNormKey) + } else { + UserDefaults.standard.removeObject(forKey: lastHandledSessionActiveStudentIdNormKey) + } + } + + func reconcileSharedSessionState() { + guard let state = SharedSessionStateManager.shared.loadState() else { + return + } + + let lastVersion = lastHandledSessionStateVersion() + guard state.stateVersion > lastVersion else { + return + } + + if !state.hasAnyAccount { + print("[Watch] Shared session state: no active iPhone account, clearing watch state") + clearAll() + resetRecoveryState() + setLastHandledSessionStateVersion(state.stateVersion) + setLastHandledSessionActiveStudentIdNorm(nil) + return + } + + if let activeStudentIdNorm = state.activeStudentIdNorm { + let lastHandledActiveStudentIdNorm = lastHandledSessionActiveStudentIdNorm() + if lastHandledActiveStudentIdNorm != activeStudentIdNorm { + print("[Watch] Shared session switched active account to \(activeStudentIdNorm), clearing stale cache") + clearCache() + data = nil + lastUpdated = nil + error = nil + recoveryAttempted = false + WatchL10n.shared.resetLanguageVersionTracking() + } + setLastHandledSessionActiveStudentIdNorm(activeStudentIdNorm) + } else { + setLastHandledSessionActiveStudentIdNorm(nil) + } + + setLastHandledSessionStateVersion(state.stateVersion) + checkTokenState() + } + + // MARK: - Cache Loading + + func loadFromCache() { + if let widgetData = WidgetData.load() { + self.data = widgetData + self.lastUpdated = widgetData.lastUpdated + return + } + + guard let cachedData = loadWatchCache() else { + return + } + + self.data = cachedData.widgetData + self.lastUpdated = cachedData.lastUpdated + } + + private func loadWatchCache() -> CachedWatchData? { + guard let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: appGroupID + ) else { + return nil + } + + let fileURL = containerURL.appendingPathComponent(cacheFileName) + + guard let cacheData = try? Data(contentsOf: fileURL) else { + return nil + } + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + + return try? decoder.decode(CachedWatchData.self, from: cacheData) + } + + private func saveToCache(_ data: WidgetData) { + guard let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: appGroupID + ) else { + return + } + + let fileURL = containerURL.appendingPathComponent(cacheFileName) + let cached = CachedWatchData(widgetData: data, lastUpdated: Date()) + + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + + do { + let encodedData = try encoder.encode(cached) + try encodedData.write(to: fileURL) + } catch { + self.error = "Failed to save cache" + } + } + + // MARK: - Cache Management + + func clearCache() { + guard let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: appGroupID + ) else { return } + + let fileURL = containerURL.appendingPathComponent(cacheFileName) + try? FileManager.default.removeItem(at: fileURL) + + data = nil + lastUpdated = nil + + print("[Watch] Cache cleared") + } + + func clearAll() { + clearCache() + error = nil + isLoading = false + checkTokenState() + + print("[Watch] All data cleared") + } + + func clearError() { + error = nil + print("[Watch] Error cleared") + } + + func setReauthRequired() { + error = "token_expired" + print("[Watch] Reauth required state set") + } + + func resetRecoveryState() { + recoveryAttempted = false + error = nil + print("[Watch] Recovery state reset") + } + + func attemptTokenRecovery() async -> Bool { + guard !isRecoveringToken else { + print("[Watch] Token recovery already in progress") + return false + } + + isRecoveringToken = true + recoveryAttempted = false + error = nil + print("[Watch] Starting token recovery via central method...") + + defer { + isRecoveringToken = false + } + + if let token = TokenManager.shared.loadToken(), !TokenManager.shared.isTokenExpired() { + print("[Watch] Recovery: Token is already valid") + checkTokenState() + return true + } + + if let _ = await TokenManager.shared.recoverToken() { + print("[Watch] Recovery: Central recovery succeeded") + checkTokenState() + return true + } + + print("[Watch] Recovery: All attempts failed") + recoveryAttempted = true + self.error = "token_expired" + return false + } + + private func refreshComplications() { + WidgetCenter.shared.reloadAllTimelines() + print("[Watch] Complications refreshed") + } + + // MARK: - Proactive Token Refresh + + func refreshTokenProactively() async { + guard hasValidToken else { return } + await TokenManager.shared.refreshTokenProactively() + checkTokenState() + } + + // MARK: - Data Refresh + + func refreshAll() async { + guard !isLoading else { + print("[Watch] DataStore.refreshAll() already in progress, skipping duplicate call") + return + } + + print("[Watch] DataStore.refreshAll() called") + isLoading = true + error = nil + + defer { isLoading = false } + + await TokenManager.shared.refreshTokenProactively() + + guard hasValidToken else { + print("[Watch] No valid token, setting error = no_token") + error = "no_token" + return + } + + do { + let (startOfWeek, endOfWeek) = getCurrentWeekDateRange() + + async let timetableTask = KretaAPIClient.shared.fetchTimetable( + from: startOfWeek, + to: endOfWeek + ) + async let gradesTask = KretaAPIClient.shared.fetchGrades() + + let (lessons, grades) = try await (timetableTask, gradesTask) + + let timetableData = buildTimetableData(from: lessons) + let averagesData = buildAveragesData(from: grades) + + let widgetData = WidgetData( + lastUpdated: Date(), + locale: Locale.current.language.languageCode?.identifier ?? "hu", + theme: "dark", + timetable: timetableData, + grades: grades, + averages: averagesData + ) + + self.data = widgetData + self.lastUpdated = Date() + + saveToCache(widgetData) + + refreshComplications() + + print("[Watch] refreshAll() completed successfully") + + } catch let error as APIError { + handleAPIError(error) + } catch { + print("[Watch] refreshAll() network error: \(error)") + self.error = "network" + } + } + + private var isRecoveryInProgress: Bool = false + + func refreshAllWithRecovery() async { + guard !isRecoveryInProgress && !isLoading else { + print("[Watch] refreshAllWithRecovery() already in progress or refreshAll() running, skipping duplicate call") + return + } + isRecoveryInProgress = true + defer { isRecoveryInProgress = false } + + reconcileSharedSessionState() + WatchL10n.shared.refreshFromiPhoneAndSharedState() + + let sharedActiveStudentIdNorm = SharedSessionStateManager.shared.loadState()?.activeStudentIdNorm + let localStudentIdNorm = TokenManager.shared.loadToken()?.studentIdNorm + let shouldRequestTokenFromPhone = + !hasValidToken || + (sharedActiveStudentIdNorm != nil && localStudentIdNorm != sharedActiveStudentIdNorm) + + if shouldRequestTokenFromPhone { + WatchConnectivityManager.shared.requestTokenFromPhone() + try? await Task.sleep(nanoseconds: 2_000_000_000) + checkTokenState() + } + + await refreshAll() + + guard error == "token_expired" || error == "no_token" else { + return + } + + print("[Watch] Token issue after refreshAll(), starting auto-recovery flow...") + let recovered = await attemptTokenRecovery() + if recovered { + await refreshAll() + } + } + + /// Handles API errors and maps them to user-friendly messages + private func handleAPIError(_ error: APIError) { + print("[Watch] handleAPIError: \(error)") + switch error { + case .tokenError(let tokenError): + switch tokenError { + case .noToken: + print("[Watch] Setting error = no_token") + self.error = "no_token" + case .refreshExpired, .invalidGrant: + print("[Watch] Setting error = token_expired") + self.error = "token_expired" + case .invalidResponse, .networkError: + print("[Watch] Setting error = network (token error)") + self.error = "network" + } + case .unauthorized: + print("[Watch] Setting error = token_expired (unauthorized)") + self.error = "token_expired" + case .requestFailed(let statusCode): + if statusCode >= 500 { + print("[Watch] Setting error = api_error (server error \(statusCode))") + self.error = "api_error" + } else { + print("[Watch] Setting error = network (request failed \(statusCode))") + self.error = "network" + } + case .decodingFailed, .invalidURL: + print("[Watch] Setting error = network") + self.error = "network" + } + } + + // MARK: - Data Processing + + private func buildTimetableData(from lessons: [WidgetLesson]) -> TimetableData { + let today = Date() + let todayString = formatDateForComparison(today) + let tomorrowString = formatDateForComparison(today.addingTimeInterval(86400)) + + let todayLessons = lessons.filter { $0.date == todayString }.sorted { $0.start < $1.start } + let tomorrowLessons = lessons.filter { $0.date == tomorrowString }.sorted { $0.start < $1.start } + + var nextSchoolDayLessons: [WidgetLesson]? = nil + var nextSchoolDayDateString: String? = nil + + for daysOffset in 2...14 { + let checkDate = today.addingTimeInterval(TimeInterval(daysOffset * 86400)) + let checkDateString = formatDateForComparison(checkDate) + let checkLessons = lessons.filter { $0.date == checkDateString } + + if !checkLessons.isEmpty { + nextSchoolDayLessons = checkLessons.sorted { $0.start < $1.start } + nextSchoolDayDateString = checkDateString + break + } + } + + let currentBreak: BreakInfo? = nil + + return TimetableData( + today: todayLessons, + tomorrow: tomorrowLessons, + nextSchoolDay: nextSchoolDayLessons, + nextSchoolDayDate: nextSchoolDayDateString, + currentBreak: currentBreak, + allLessons: lessons + ) + } + + /// Builds AveragesData from grades (matching Flutter's calculation) + private func buildAveragesData(from grades: [WidgetGrade]) -> AveragesData { + guard !grades.isEmpty else { + return AveragesData(overall: nil, subjects: []) + } + + var subjectGradesMap: [String: [(value: Int, weight: Double)]] = [:] + + for grade in grades { + if let numeric = grade.normalizedNumericValue { + let key = grade.subject.uid + let weight = Double(grade.weightPercentage ?? 100) / 100.0 + subjectGradesMap[key, default: []].append((value: numeric, weight: weight)) + } + } + + var subjectAverages: [SubjectAverage] = [] + + for (uid, gradeValues) in subjectGradesMap { + if let firstGrade = grades.first(where: { $0.subject.uid == uid }) { + var weightedSum = 0.0 + var totalWeight = 0.0 + + for (value, weight) in gradeValues { + weightedSum += Double(value) * weight + totalWeight += weight + } + + let average = totalWeight > 0 ? weightedSum / totalWeight : Double.nan + + if !average.isNaN { + subjectAverages.append( + SubjectAverage( + uid: uid, + name: firstGrade.subject.name, + average: average, + gradeCount: gradeValues.count + ) + ) + } + } + } + + let overall: Double? + if !subjectAverages.isEmpty { + let sumOfAverages = subjectAverages.reduce(0.0) { $0 + $1.average } + overall = sumOfAverages / Double(subjectAverages.count) + } else { + overall = nil + } + + return AveragesData(overall: overall, subjects: subjectAverages) + } + + private func getCurrentWeekDateRange() -> (start: Date, end: Date) { + let calendar = Calendar.current + let today = Date() + + let weekday = calendar.component(.weekday, from: today) + let daysToMonday = weekday == 1 ? -6 : (2 - weekday) + let monday = calendar.date(byAdding: .day, value: daysToMonday, to: today)! + + let nextSunday = calendar.date(byAdding: .day, value: 13, to: monday)! + + return (monday, nextSunday) + } + + private func formatDateForComparison(_ date: Date) -> String { + let calendar = Calendar.current + let components = calendar.dateComponents([.year, .month, .day], from: date) + return String(format: "%04d-%02d-%02d", + components.year ?? 0, + components.month ?? 0, + components.day ?? 0) + } + + // MARK: - Computed Helpers + + var timeSinceUpdate: String? { + guard let lastUpdated = lastUpdated else { return nil } + + let elapsed = Date().timeIntervalSince(lastUpdated) + + if elapsed < 60 { + return "time_now".localized + } + + // Minutes + let minutes = Int(elapsed / 60) + if minutes < 60 { + return minutes == 1 + ? "time_since_minutes_one".localized + : "time_since_minutes_many".localized(minutes) + } + + // Hours + let hours = Int(elapsed / 3600) + if hours < 24 { + return hours == 1 + ? "time_since_hours_one".localized + : "time_since_hours_many".localized(hours) + } + + // Days + let days = Int(elapsed / 86400) + return days == 1 + ? "time_since_days_one".localized + : "time_since_days_many".localized(days) + } + + /// Returns true if data is stale (> 1 hour old or never updated) + var isStale: Bool { + guard let lastUpdated = lastUpdated else { return true } + + let elapsed = Date().timeIntervalSince(lastUpdated) + return elapsed > 3600 // 1 hour + } +} diff --git a/firka/ios/FirkaWatch Watch App/Services/WatchConnectivityManager.swift b/firka/ios/FirkaWatch Watch App/Services/WatchConnectivityManager.swift new file mode 100644 index 00000000..ce5175be --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Services/WatchConnectivityManager.swift @@ -0,0 +1,456 @@ +import Foundation +import WatchConnectivity + +class WatchConnectivityManager: NSObject, WCSessionDelegate { + static let shared = WatchConnectivityManager() + private let lastAppliedTokenUpdateKey = "watch_last_applied_token_update_ms" + private let minPhoneTokenRequestInterval: TimeInterval = 5 + private var lastPhoneTokenRequestAt: Date? + + private override init() { + super.init() + } + + private var lastAppliedTokenUpdateMs: Int64 { + get { + Int64(UserDefaults.standard.double(forKey: lastAppliedTokenUpdateKey)) + } + set { + UserDefaults.standard.set(Double(newValue), forKey: lastAppliedTokenUpdateKey) + } + } + + private func extractSentAtMs(from authDict: [String: Any]) -> Int64? { + if let value = authDict["sentAtMs"] as? Int64 { + return value + } + if let value = authDict["sentAtMs"] as? Int { + return Int64(value) + } + if let value = authDict["sentAtMs"] as? Double { + return Int64(value) + } + if let value = authDict["sentAtMs"] as? String, + let parsed = Int64(value) { + return parsed + } + return nil + } + + private func parseInt64(_ value: Any?) -> Int64? { + if let value = value as? Int64 { + return value + } + if let value = value as? Int { + return Int64(value) + } + if let value = value as? Double { + return Int64(value) + } + if let value = value as? String, let parsed = Int64(value) { + return parsed + } + return nil + } + + func activate() { + print("[Watch] WatchConnectivityManager.activate() called") + if WCSession.isSupported() { + print("[Watch] WCSession is supported, activating...") + WCSession.default.delegate = self + WCSession.default.activate() + } else { + print("[Watch] WCSession is NOT supported!") + } + } + + func session( + _ session: WCSession, + activationDidCompleteWith activationState: WCSessionActivationState, + error: Error? + ) { + print("[Watch] Session activation completed with state: \(activationState.rawValue)") + if let error = error { + print("[Watch] Activation error: \(error.localizedDescription)") + } + DispatchQueue.main.async { + if activationState == .activated { + let context = session.receivedApplicationContext + if !context.isEmpty { + self.processApplicationContext(context) + } + } + } + } + + func session( + _ session: WCSession, + didReceiveApplicationContext applicationContext: [String: Any] + ) { + print("[Watch] didReceiveApplicationContext called") + DispatchQueue.main.async { + self.processApplicationContext(applicationContext) + } + } + + func session( + _ session: WCSession, + didReceiveUserInfo userInfo: [String: Any] = [:] + ) { + print("[Watch] didReceiveUserInfo called") + DispatchQueue.main.async { + self.processUserInfo(userInfo) + } + } + + func session( + _ session: WCSession, + didReceiveMessage message: [String: Any], + replyHandler: @escaping ([String: Any]) -> Void + ) { + print("[Watch] didReceiveMessage called: \(message)") + + if let messageId = message["id"] as? String, messageId == "token_update" { + if let authDict = message["auth"] as? [String: Any] { + print("[Watch] Received immediate token_update via sendMessage") + processAuthData(authDict) + replyHandler(["success": true]) + } else { + replyHandler(["error": "no_auth"]) + } + return + } + + guard let action = message["action"] as? String else { + replyHandler(["error": "no_action"]) + return + } + + switch action { + case "getToken": + handleGetTokenRequest(replyHandler: replyHandler) + default: + replyHandler(["error": "unknown_action"]) + } + } + + private func handleGetTokenRequest(replyHandler: @escaping ([String: Any]) -> Void) { + guard TokenManager.shared.loadToken() != nil else { + print("[Watch] No token to send to iPhone") + replyHandler(["error": "no_token"]) + return + } + + if TokenManager.shared.isTokenExpired() { + print("[Watch] Token expired, attempting refresh before sending to iPhone...") + Task { + do { + let freshToken = try await KretaAPIClient.shared.getValidToken() + print("[Watch] Token refresh succeeded, sending fresh token to iPhone") + + var tokenData: [String: Any] = [ + "studentId": freshToken.studentId, + "studentIdNorm": freshToken.studentIdNorm, + "iss": freshToken.iss, + "idToken": freshToken.idToken, + "accessToken": freshToken.accessToken, + "refreshToken": freshToken.refreshToken, + "expiryDate": Int64(freshToken.expiryDate.timeIntervalSince1970 * 1000) + ] + if let tokenVersion = freshToken.effectiveTokenVersion { + tokenData["tokenVersion"] = tokenVersion + } + tokenData["updatedAtMs"] = freshToken.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000) + + replyHandler(["token": tokenData]) + } catch { + print("[Watch] Token refresh failed after all retries: \(error)") + replyHandler(["error": "refresh_failed"]) + } + } + return + } + + guard let token = TokenManager.shared.loadToken() else { + replyHandler(["error": "no_token"]) + return + } + + var tokenData: [String: Any] = [ + "studentId": token.studentId, + "studentIdNorm": token.studentIdNorm, + "iss": token.iss, + "idToken": token.idToken, + "accessToken": token.accessToken, + "refreshToken": token.refreshToken, + "expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000) + ] + if let tokenVersion = token.effectiveTokenVersion { + tokenData["tokenVersion"] = tokenVersion + } + tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000) + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + print("[Watch] Sending token to iPhone, expiry: \(formatter.string(from: token.expiryDate))") + replyHandler(["token": tokenData]) + } + + func requestTokenFromPhone() { + guard WCSession.default.activationState == .activated else { + print("[Watch] Cannot request token: session not activated") + return + } + + guard WCSession.default.isReachable else { + print("[Watch] Cannot request token: iPhone not reachable") + return + } + + let now = Date() + if let lastPhoneTokenRequestAt, + now.timeIntervalSince(lastPhoneTokenRequestAt) < minPhoneTokenRequestInterval { + print("[Watch] Skipping token request due to cooldown") + return + } + lastPhoneTokenRequestAt = now + + print("[Watch] Requesting token from iPhone...") + + WCSession.default.sendMessage( + ["action": "requestToken"], + replyHandler: { response in + print("[Watch] Received response from iPhone") + DispatchQueue.main.async { + if let authDict = response["auth"] as? [String: Any] { + print("[Watch] Token received from iPhone") + self.processAuthData(authDict) + } else if let error = response["error"] as? String { + print("[Watch] Token request error: \(error)") + } + } + }, + errorHandler: { error in + print("[Watch] Token request failed: \(error.localizedDescription)") + } + ) + } + + private func processApplicationContext(_ context: [String: Any]) { + if (context["force_logout"] as? Bool) == true { + print("[Watch] Received force_logout via applicationContext") + handleForceLogoutFromPhone() + return + } + + if let authDict = context["auth"] as? [String: Any] { + print("[Watch] Received auth from iPhone") + processAuthData(authDict) + } + + if let language = context["language"] as? String { + let sharedStateVersion = + parseInt64(context["language_state_version"]) ?? + parseInt64(context["languageStateVersion"]) + print("[Watch] Received language from iPhone: \(language)") + WatchL10n.shared.updateFromiPhone( + languageCode: language, + sharedStateVersion: sharedStateVersion + ) + } + } + + private func processUserInfo(_ userInfo: [String: Any]) { + if let messageId = userInfo["id"] as? String { + switch messageId { + case "token_update": + if let authDict = userInfo["auth"] as? [String: Any] { + print("[Watch] Received token_update via userInfo") + processAuthData(authDict) + } + case "language_update": + if let language = userInfo["language"] as? String { + let sharedStateVersion = + parseInt64(userInfo["language_state_version"]) ?? + parseInt64(userInfo["languageStateVersion"]) + print("[Watch] Received language_update via userInfo: \(language)") + WatchL10n.shared.updateFromiPhone( + languageCode: language, + sharedStateVersion: sharedStateVersion + ) + } + case "reauth_required": + print("[Watch] Received reauth_required notification from iPhone") + DataStore.shared.setReauthRequired() + case "force_logout": + print("[Watch] Received force_logout notification from iPhone") + handleForceLogoutFromPhone() + default: + break + } + } + } + + private func handleForceLogoutFromPhone() { + TokenManager.shared.deleteToken() + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: false, + activeStudentIdNorm: nil + ) + DataStore.shared.clearAll() + DataStore.shared.resetRecoveryState() + DataStore.shared.checkTokenState() + } + + func sendTokenToiPhoneInBackground() { + guard WCSession.default.activationState == .activated else { + print("[Watch] Cannot send token: session not activated") + return + } + + guard let token = TokenManager.shared.loadToken() else { + print("[Watch] No token to send to iPhone") + return + } + + var tokenData: [String: Any] = [ + "studentId": token.studentId, + "studentIdNorm": token.studentIdNorm, + "iss": token.iss, + "idToken": token.idToken, + "accessToken": token.accessToken, + "refreshToken": token.refreshToken, + "expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000) + ] + if let tokenVersion = token.effectiveTokenVersion { + tokenData["tokenVersion"] = tokenVersion + } + tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000) + + do { + try WCSession.default.updateApplicationContext(["auth": tokenData]) + print("[Watch] Token sent via applicationContext") + } catch { + print("[Watch] Failed to update applicationContext: \(error)") + } + + WCSession.default.transferUserInfo([ + "id": "token_update_from_watch", + "auth": tokenData + ]) + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + print("[Watch] Token sent to iPhone (background), expiry: \(formatter.string(from: token.expiryDate))") + } + + func requestLanguageFromPhone() { + guard WCSession.default.activationState == .activated else { + print("[Watch] Cannot request language: session not activated") + return + } + + guard WCSession.default.isReachable else { + print("[Watch] Cannot request language: iPhone not reachable") + return + } + + print("[Watch] Requesting language from iPhone...") + + WCSession.default.sendMessage( + ["action": "requestLanguage"], + replyHandler: { response in + print("[Watch] Received language response from iPhone") + DispatchQueue.main.async { + if let language = response["language"] as? String { + let sharedStateVersion = + self.parseInt64(response["language_state_version"]) ?? + self.parseInt64(response["languageStateVersion"]) + print("[Watch] Language received from iPhone: \(language)") + WatchL10n.shared.updateFromiPhone( + languageCode: language, + sharedStateVersion: sharedStateVersion + ) + } + } + }, + errorHandler: { error in + print("[Watch] Language request failed: \(error.localizedDescription)") + } + ) + } + + private func processAuthData(_ authDict: [String: Any]) { + print("[Watch] processAuthData called") + do { + let incomingSentAtMs = extractSentAtMs(from: authDict) ?? 0 + let previousSentAtMs = lastAppliedTokenUpdateMs + + if incomingSentAtMs > 0 && incomingSentAtMs < previousSentAtMs { + print("[Watch] Ignoring stale token_update (sentAtMs: \(incomingSentAtMs), lastApplied: \(previousSentAtMs))") + return + } + + let jsonData = try JSONSerialization.data(withJSONObject: authDict) + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let timestamp = try container.decode(Int64.self) + return Date(timeIntervalSince1970: Double(timestamp) / 1000.0) + } + + let token = try decoder.decode(WatchToken.self, from: jsonData) + let currentToken = TokenManager.shared.loadToken() + + let isAccountSwitch = currentToken != nil && !token.isSameAccount(as: currentToken!) + let shouldForceAccountSwitch: Bool + if isAccountSwitch { + if incomingSentAtMs > 0 { + shouldForceAccountSwitch = true + } else { + shouldForceAccountSwitch = token.isNewer(than: currentToken!) + } + } else { + shouldForceAccountSwitch = false + } + + if incomingSentAtMs <= 0, + let currentToken, + !isAccountSwitch, + !token.isNewer(than: currentToken) { + print("[Watch] Ignoring stale token_update without sentAtMs (same account, not newer)") + return + } + + print("[Watch] Token decoded, saving... (sentAtMs: \(incomingSentAtMs), forceSwitch: \(shouldForceAccountSwitch))") + + try TokenManager.shared.saveToken( + token, + syncToSharedKeychain: false, + forceAccountSwitch: shouldForceAccountSwitch + ) + print("[Watch] Token saved successfully") + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: true, + activeStudentIdNorm: token.studentIdNorm + ) + if incomingSentAtMs > 0 { + lastAppliedTokenUpdateMs = max(previousSentAtMs, incomingSentAtMs) + } + + DataStore.shared.clearError() + DataStore.shared.resetRecoveryState() + DataStore.shared.checkTokenState() + + Task { + await DataStore.shared.refreshAllWithRecovery() + print("[Watch] Data refresh completed") + } + } catch { + print("[Watch] Failed to process auth data: \(error)") + } + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/GradeSubjectView.swift b/firka/ios/FirkaWatch Watch App/Views/GradeSubjectView.swift new file mode 100644 index 00000000..daae6a5c --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/GradeSubjectView.swift @@ -0,0 +1,119 @@ +import SwiftUI + +struct GradeSubjectView: View { + let subjectName: String + let grades: [WidgetGrade] + let average: Double + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + FirkaCard { + HStack { + Text("average".localized) + .font(.caption) + .foregroundColor(.secondary) + Text(String(format: "%.2f", average)) + .font(.headline) + .fontWeight(.bold) + .foregroundColor(averageColor(average)) + } + } + + ForEach(groupedGrades, id: \.date) { group in + VStack(alignment: .leading, spacing: 6) { + Text(formatDate(group.date)) + .font(.caption) + .foregroundColor(.secondary) + + ForEach(group.grades) { grade in + gradeRow(grade) + } + } + } + } + .padding() + } + .navigationTitle(subjectName) + } + + private var groupedGrades: [(date: Date, grades: [WidgetGrade])] { + let calendar = Calendar.current + let grouped = Dictionary(grouping: grades) { grade in + calendar.startOfDay(for: grade.recordDate) + } + return grouped + .map { (date: $0.key, grades: $0.value) } + .sorted { $0.date > $1.date } + } + + @ViewBuilder + private func gradeRow(_ grade: WidgetGrade) -> some View { + FirkaCard { + HStack(alignment: .top, spacing: 10) { + if let normalizedValue = grade.normalizedNumericValue { + if grade.isPercentageGrade, let rawValue = grade.numericValue { + ZStack { + Circle() + .fill(gradeColor(normalizedValue)) + .frame(width: 32, height: 32) + Text("\(rawValue)%") + .font(.system(size: 10, weight: .bold)) + .foregroundColor(.white) + } + } else { + GradeBadge(grade: normalizedValue) + } + } else { + Text(grade.displayValue) + .font(.caption) + .fontWeight(.bold) + .padding(6) + .background(Color.gray) + .cornerRadius(12) + } + + VStack(alignment: .leading, spacing: 2) { + Text(grade.displayTypeWithWeight) + .font(.subheadline) + .fontWeight(.medium) + + if let topic = grade.topic, !topic.isEmpty { + Text(topic) + .font(.caption) + .foregroundColor(.secondary) + .lineLimit(2) + } + } + + Spacer() + } + } + } + + private func gradeColor(_ value: Int) -> Color { + switch value { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + default: return .red + } + } + + private func formatDate(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "yyyy. MM. dd." + return formatter.string(from: date) + } + + private func averageColor(_ avg: Double) -> Color { + switch avg { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/GradesView.swift b/firka/ios/FirkaWatch Watch App/Views/GradesView.swift new file mode 100644 index 00000000..0a69a8a7 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/GradesView.swift @@ -0,0 +1,108 @@ +import SwiftUI + +struct GradesView: View { + let dataStore: DataStore + + var body: some View { + NavigationStack { + if dataStore.data == nil { + ContentUnavailableView("no_data".localized, systemImage: "graduationcap") + } else if subjects.isEmpty { + ContentUnavailableView("no_grades".localized, systemImage: "graduationcap") + } else { + ScrollView { + VStack(spacing: 8) { + ForEach(subjects, id: \.uid) { subject in + NavigationLink { + GradeSubjectView( + subjectName: subject.name, + grades: gradesFor(subject.uid), + average: subject.average + ) + } label: { + subjectRow(subject) + } + .buttonStyle(.plain) + } + + if let overall = dataStore.data?.averages.overall { + overallAverageCard(overall) + } + } + .padding() + } + } + } + } + + private var subjects: [SubjectAverage] { + (dataStore.data?.averages.subjects ?? []).sorted { $0.name < $1.name } + } + + private func gradesFor(_ uid: String) -> [WidgetGrade] { + dataStore.data?.grades.filter { $0.subject.uid == uid } ?? [] + } + + @ViewBuilder + private func subjectRow(_ subject: SubjectAverage) -> some View { + FirkaCard { + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(subject.name) + .font(.subheadline) + .fontWeight(.medium) + .lineLimit(1) + + Spacer() + + Text(String(format: "%.2f", subject.average)) + .font(.subheadline) + .fontWeight(.bold) + .foregroundColor(averageColor(subject.average)) + } + + HStack(spacing: 8) { + AverageProgressBar(average: subject.average) + + Text("grades_count".localized(subject.gradeCount)) + .font(.caption2) + .foregroundColor(.secondary) + } + } + } + } + + @ViewBuilder + private func overallAverageCard(_ average: Double) -> some View { + FirkaCard { + VStack(alignment: .leading, spacing: 4) { + Text("total_average".localized) + .font(.caption) + .foregroundColor(.secondary) + + HStack { + Text(String(format: "%.2f", average)) + .font(.title3) + .fontWeight(.bold) + .foregroundColor(averageColor(average)) + + Spacer() + + AverageProgressBar(average: average) + .frame(width: 60) + } + } + } + .padding(.top, 8) + } + + private func averageColor(_ avg: Double) -> Color { + switch avg { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/HomeView.swift b/firka/ios/FirkaWatch Watch App/Views/HomeView.swift new file mode 100644 index 00000000..84bf4ba9 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/HomeView.swift @@ -0,0 +1,598 @@ +import SwiftUI +import WatchConnectivity +internal import Combine + +struct HomeView: View { + let dataStore: DataStore + @State private var currentTime = Date() + + private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() + + var body: some View { + ScrollView { + VStack(spacing: 12) { + if let breakInfo = dataStore.data?.timetable.currentBreak { + breakView(breakInfo) + } else if !dataStore.hasToken && dataStore.data == nil { + noTokenView + } else if let current = currentLesson { + currentLessonView(current) + } else if let next = nextLesson { + if isBreakBetweenLessons { + breakBetweenView(next) + } else { + beforeSchoolView(next) + } + } else { + noMoreLessonsView + } + + refreshButton + + if dataStore.lastUpdated != nil { + lastUpdatedView + } + } + .padding() + } + .onReceive(timer) { _ in + currentTime = Date() + } + } + + // MARK: - Refresh Button + + @State private var refreshStatus: RefreshStatus = .idle + @State private var wasLoadingFromBackground: Bool = false + @State private var lastUpdateTime: Date? = nil + + enum RefreshStatus { + case idle, loading, success, failure + } + + private var refreshButton: some View { + Button(action: { + guard !dataStore.isLoading else { return } + Task { + refreshStatus = .loading + await dataStore.refreshAllWithRecovery() + if dataStore.error == nil && dataStore.data != nil { + refreshStatus = .success + } else { + refreshStatus = .failure + } + try? await Task.sleep(nanoseconds: 2_000_000_000) + refreshStatus = .idle + } + }) { + HStack(spacing: 6) { + if dataStore.isLoading && refreshStatus != .loading { + ProgressView() + .scaleEffect(0.8) + } else { + switch refreshStatus { + case .idle: + Image(systemName: "arrow.clockwise") + case .loading: + ProgressView() + .scaleEffect(0.8) + case .success: + Image(systemName: "checkmark.circle.fill") + .foregroundColor(.green) + case .failure: + Image(systemName: "xmark.circle.fill") + .foregroundColor(.red) + } + } + Text(refreshStatusText) + } + .font(.caption) + .foregroundColor(.blue) + } + .buttonStyle(.plain) + .disabled(dataStore.isLoading || refreshStatus == .loading) + .padding(.top, 8) + .onChange(of: dataStore.isLoading) { oldValue, newValue in + if newValue && refreshStatus != .loading { + wasLoadingFromBackground = true + } + if !newValue && wasLoadingFromBackground && refreshStatus != .loading { + wasLoadingFromBackground = false + if dataStore.error == nil && dataStore.data != nil { + refreshStatus = .success + } else if dataStore.error != nil { + refreshStatus = .failure + } + Task { + try? await Task.sleep(nanoseconds: 2_000_000_000) + if refreshStatus == .success || refreshStatus == .failure { + refreshStatus = .idle + } + } + } + } + .onChange(of: dataStore.lastUpdated) { oldValue, newValue in + guard let oldValue, let newValue else { return } + guard newValue > oldValue else { return } + guard dataStore.error == nil else { return } + guard refreshStatus != .loading else { return } + + refreshStatus = .success + Task { + try? await Task.sleep(nanoseconds: 2_000_000_000) + if refreshStatus == .success { + refreshStatus = .idle + } + } + } + } + + private var refreshStatusText: String { + if dataStore.isLoading && refreshStatus != .loading { + return "refreshing".localized + } + + switch refreshStatus { + case .idle: return "refresh".localized + case .loading: return "refreshing".localized + case .success: return "refresh_success".localized + case .failure: + if let error = dataStore.error { + switch error { + case "api_error": return "error_api".localized + case "network": return "error_network".localized + case "token_expired", "no_token": return "reauth_required".localized + default: return "refresh_failed".localized + } + } + return "refresh_failed".localized + } + } + + // MARK: - Computed Properties + + private var now: Date { currentTime } + + private var todayLessons: [WidgetLesson] { + let todayStr = formatDateForHomeView(currentTime) + + if let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty { + return allLessons + .filter { $0.date == todayStr } + .sorted { $0.start < $1.start } + } + + return dataStore.data?.timetable.today ?? [] + } + + private var currentLesson: WidgetLesson? { + todayLessons.first { currentTime >= $0.start && currentTime <= $0.end } + } + + private var nextLesson: WidgetLesson? { + todayLessons + .filter { $0.start > currentTime } + .sorted { $0.start < $1.start } + .first + } + + private var previousLesson: WidgetLesson? { + todayLessons + .filter { $0.end < currentTime } + .sorted { $0.end > $1.end } + .first + } + + private var isBreakBetweenLessons: Bool { + guard let prev = previousLesson, let next = nextLesson else { return false } + return currentTime > prev.end && currentTime < next.start + } + + // MARK: - Current Lesson View (with CountdownRing) + + @ViewBuilder + private func currentLessonView(_ lesson: WidgetLesson) -> some View { + VStack(spacing: 10) { + Text("current_lesson".localized) + .font(.caption) + .foregroundColor(.secondary) + + let totalMinutes = Int(lesson.end.timeIntervalSince(lesson.start) / 60) + let remaining = max(0, Int(lesson.end.timeIntervalSince(now) / 60)) + + HStack(spacing: 10) { + CountdownRing( + totalMinutes: totalMinutes, + remainingMinutes: remaining, + label: "minutes".localized, + size: 56, + lineWidth: 6, + displayOffset: 1 + ) + .id("lesson-\(lesson.start.timeIntervalSince1970)") + FirkaCard( + isHighlighted: true, + backgroundColor: lessonCardBackgroundColor( + for: lesson, + isHighlighted: true + ) + ) { + VStack(alignment: .leading, spacing: 4) { + lessonTitleWithStatus( + lesson, + font: .subheadline, + weight: .semibold, + lineLimit: 2 + ) + + HStack(spacing: 6) { + if let room = lesson.roomName { + Label(room, systemImage: "door.right.hand.closed") + } + Text(lesson.timeString) + } + .font(.caption2) + .foregroundColor(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + // Next lesson preview + if let next = nextLesson { + Text("next".localized) + .font(.caption) + .foregroundColor(.secondary) + + FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) { + HStack { + VStack(alignment: .leading, spacing: 2) { + lessonTitleWithStatus( + next, + font: .subheadline, + weight: .regular, + lineLimit: 2 + ) + if let room = next.roomName { + Text(room) + .font(.caption2) + .foregroundColor(.secondary) + } + } + Spacer() + Text(next.start, style: .time) + .font(.caption) + .foregroundColor(.secondary) + } + } + } + } + } + + // MARK: - Break Between Lessons (with CountdownRing) + + @ViewBuilder + private func breakBetweenView(_ next: WidgetLesson) -> some View { + VStack(spacing: 10) { + Text("break".localized) + .font(.caption) + .foregroundColor(.secondary) + + let remaining = max(0, Int(ceil(next.start.timeIntervalSince(now) / 60))) + let totalBreakMinutes: Int = { + guard let previous = previousLesson else { return max(remaining, 1) } + let breakSeconds = max(60, next.start.timeIntervalSince(previous.end)) + return max(1, Int(ceil(breakSeconds / 60))) + }() + + HStack(spacing: 10) { + CountdownRing( + totalMinutes: totalBreakMinutes, + remainingMinutes: remaining, + label: "minutes".localized, + size: 56, + lineWidth: 6, + displayOffset: 1 + ) + .id("break-\(next.start.timeIntervalSince1970)") + + FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 4) { + Text("next_lesson".localized(next.displayName)) + .font(.subheadline) + .fontWeight(.semibold) + .lineLimit(2) + } + + HStack(spacing: 6) { + if let room = next.roomName { + Label(room, systemImage: "door.right.hand.closed") + } + Text(next.start, style: .time) + } + .font(.caption2) + .foregroundColor(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + } + + // MARK: - Before School View + + @ViewBuilder + private func beforeSchoolView(_ first: WidgetLesson) -> some View { + VStack(spacing: 12) { + Text("first_lesson".localized) + .font(.caption) + .foregroundColor(.secondary) + + FirkaCard(backgroundColor: lessonCardBackgroundColor(for: first)) { + VStack(alignment: .leading, spacing: 8) { + lessonTitleWithStatus( + first, + font: .headline, + weight: .regular, + lineLimit: 2 + ) + + HStack { + if let room = first.roomName { + Label(room, systemImage: "door.right.hand.closed") + .font(.caption) + .foregroundColor(.secondary) + } + + Spacer() + + Text(relativeTimeString(to: first.start)) + .font(.caption) + .foregroundColor(.blue) + } + } + } + + if !todayLessons.isEmpty { + Text("today_lessons_count".localized(todayLessons.count)) + .font(.caption) + .foregroundColor(.secondary) + } + } + } + + // MARK: - No More Lessons View + + private var noMoreLessonsView: some View { + VStack(spacing: 12) { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 44)) + .foregroundColor(.green) + + Text("no_more_lessons".localized) + .font(.headline) + + if let (nextLesson, dayLabel) = nextSchoolDayFirstLesson { + Text(dayLabel) + .font(.caption) + .foregroundColor(.secondary) + .padding(.top, 8) + + FirkaCard(backgroundColor: lessonCardBackgroundColor(for: nextLesson)) { + HStack { + lessonTitleWithStatus( + nextLesson, + font: .subheadline, + weight: .regular, + lineLimit: 2 + ) + Spacer() + Text(nextLesson.start, style: .time) + .font(.caption) + .foregroundColor(.secondary) + } + } + } + } + } + + private var nextSchoolDayFirstLesson: (lesson: WidgetLesson, label: String)? { + guard let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty else { + if let tomorrow = dataStore.data?.timetable.tomorrow.first { + return (tomorrow, "tomorrow_first_lesson".localized) + } + return nil + } + + let calendar = Calendar.current + let now = currentTime + let todayStr = formatDateForHomeView(now) + + let futureLessons = allLessons.filter { $0.date > todayStr } + .sorted { $0.date < $1.date || ($0.date == $1.date && $0.start < $1.start) } + + guard let firstFuture = futureLessons.first else { + return nil + } + + let label = labelForDate(firstFuture.date, relativeTo: now) + + return (firstFuture, label) + } + + private func formatDateForHomeView(_ date: Date) -> String { + let calendar = Calendar.current + let components = calendar.dateComponents([.year, .month, .day], from: date) + return String(format: "%04d-%02d-%02d", + components.year ?? 0, + components.month ?? 0, + components.day ?? 0) + } + + private func labelForDate(_ dateStr: String, relativeTo: Date) -> String { + let calendar = Calendar.current + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd" + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone.current + + guard let targetDate = formatter.date(from: dateStr) else { + return "next_school_day".localized + } + + let today = calendar.startOfDay(for: relativeTo) + let target = calendar.startOfDay(for: targetDate) + + let daysDiff = calendar.dateComponents([.day], from: today, to: target).day ?? 0 + + switch daysDiff { + case 1: + return "tomorrow_first_lesson".localized + case 2...6: + let dayFormatter = DateFormatter() + let langCode = WatchL10n.shared.currentLanguage.rawValue + dayFormatter.locale = Locale(identifier: langCode) + dayFormatter.dateFormat = "EEEE" + let dayName = dayFormatter.string(from: targetDate).capitalized + return "day_first_lesson".localized(dayName) + default: + return "next_school_day".localized + } + } + + @ViewBuilder + private func lessonTitleWithStatus( + _ lesson: WidgetLesson, + font: Font, + weight: Font.Weight = .regular, + lineLimit: Int = 2 + ) -> some View { + Text(lesson.displayName) + .font(font) + .fontWeight(weight) + .lineLimit(lineLimit) + .foregroundColor(lessonPrimaryTextColor(for: lesson)) + } + + private func lessonPrimaryTextColor(for lesson: WidgetLesson) -> Color { + if lesson.isCancelled { + return .red + } + if lesson.isSubstitution { + return .yellow + } + return .primary + } + + private func lessonCardBackgroundColor( + for lesson: WidgetLesson, + isHighlighted: Bool = false + ) -> Color { + if lesson.isCancelled { + return Color.red.opacity(0.16) + } + if lesson.isSubstitution { + return Color.yellow.opacity(0.16) + } + if isHighlighted { + return Color.green.opacity(0.2) + } + return Color(white: 0.12) + } + + // MARK: - Break/Vacation View + + @ViewBuilder + private func breakView(_ breakInfo: BreakInfo) -> some View { + VStack(spacing: 12) { + let icon = SeasonalIconHelper.iconName(for: breakInfo.nameKey, season: nil) + let color = SeasonalIconHelper.iconColor(for: breakInfo.nameKey, season: nil) + + Image(systemName: icon) + .font(.system(size: 44)) + .foregroundColor(color) + + Text(breakInfo.name) + .font(.headline) + } + } + + // MARK: - No Token View + + private var isWatchSystemPaired: Bool { + guard WCSession.isSupported() else { return false } + return WCSession.default.isCompanionAppInstalled + } + + private var noTokenTitleKey: String { + isWatchSystemPaired ? "login_on_iphone" : "pair_with_iphone" + } + + private var noTokenDescriptionKey: String { + isWatchSystemPaired ? "open_and_login_on_iphone" : "open_firka_on_iphone" + } + + private var noTokenIconName: String { + isWatchSystemPaired + ? "person.crop.circle.badge.exclamationmark" + : "iphone.and.arrow.right.inward" + } + + private var noTokenView: some View { + VStack(spacing: 12) { + Image(systemName: noTokenIconName) + .font(.system(size: 44)) + .foregroundColor(.blue) + + Text(noTokenTitleKey.localized) + .font(.headline) + .multilineTextAlignment(.center) + + Text(noTokenDescriptionKey.localized) + .font(.caption) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + } + } + + // MARK: - Last Updated View + + private var lastUpdatedView: some View { + HStack(spacing: 4) { + if dataStore.isStale { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundColor(.yellow) + } + if let text = dataStore.timeSinceUpdate { + Text("updated".localized(text)) + } + } + .font(.caption2) + .foregroundColor(.secondary) + .padding(.top, 8) + } + + // MARK: - Relative Time Helper + + private func relativeTimeString(to date: Date) -> String { + let now = currentTime + let interval = date.timeIntervalSince(now) + + guard interval > 0 else { + return "time_now".localized + } + + let totalMinutes = Int(interval / 60) + let hours = totalMinutes / 60 + let minutes = totalMinutes % 60 + + if hours > 0 && minutes > 0 { + return "time_hours_minutes".localized(hours, minutes) + } else if hours > 0 { + return "time_hours".localized(hours) + } else { + return "time_minutes_only".localized(minutes) + } + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/LessonDetailView.swift b/firka/ios/FirkaWatch Watch App/Views/LessonDetailView.swift new file mode 100644 index 00000000..4489d161 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/LessonDetailView.swift @@ -0,0 +1,109 @@ +import SwiftUI + +struct LessonDetailView: View { + let lesson: WidgetLesson + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + HStack { + if let number = lesson.lessonNumber { + Text("lesson_number".localized(number)) + .font(.caption) + .foregroundColor(.blue) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(Color.blue.opacity(0.2)) + .cornerRadius(8) + } + + Spacer() + + Text("\(formatTime(lesson.start)) - \(formatTime(lesson.end))") + .font(.caption) + .foregroundColor(.secondary) + } + + Text(lesson.displayName) + .font(.headline) + .lineLimit(3) + + if lesson.isCancelled || lesson.isSubstitution { + HStack(spacing: 8) { + if lesson.isCancelled { + Label("cancelled".localized, systemImage: "xmark.circle.fill") + .font(.caption2) + .foregroundColor(.red) + } + if lesson.isSubstitution { + Label("substitution".localized, systemImage: "person.2.fill") + .font(.caption2) + .foregroundColor(.orange) + } + } + } + + Divider() + + VStack(alignment: .leading, spacing: 10) { + if lesson.isSubstitution, let substitute = lesson.substituteTeacher { + VStack(alignment: .leading, spacing: 4) { + Label("teacher".localized, systemImage: "person.fill") + .font(.caption) + .foregroundColor(.secondary) + + if let original = lesson.teacher { + HStack(spacing: 4) { + Text(original) + .strikethrough() + .foregroundColor(.secondary) + Text("→") + .foregroundColor(.orange) + Text(substitute) + .foregroundColor(.orange) + } + .font(.subheadline) + } else { + Text(substitute) + .font(.subheadline) + .foregroundColor(.orange) + } + } + } else if let teacher = lesson.teacher { + detailRow(icon: "person.fill", label: "teacher".localized, value: teacher) + } + + if let room = lesson.roomName { + detailRow(icon: "door.right.hand.closed", label: "room".localized, value: room) + } + + if let theme = lesson.theme, !theme.isEmpty { + detailRow(icon: "doc.text.fill", label: "topic".localized, value: theme) + } + } + } + .padding() + } + .navigationTitle("lesson_details".localized) + .navigationBarTitleDisplayMode(.inline) + } + + @ViewBuilder + private func detailRow(icon: String, label: String, value: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Label(label, systemImage: icon) + .font(.caption) + .foregroundColor(.secondary) + + Text(value) + .font(.subheadline) + .lineLimit(5) + } + } + + private func formatTime(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter.string(from: date) + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/ReauthRequiredView.swift b/firka/ios/FirkaWatch Watch App/Views/ReauthRequiredView.swift new file mode 100644 index 00000000..0f9b02b9 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/ReauthRequiredView.swift @@ -0,0 +1,308 @@ +import SwiftUI +import WatchConnectivity + +struct ReauthRequiredView: View { + @State private var isSyncing = false + @State private var syncStatus: SyncStatus = .idle + var onTokenReceived: (() -> Void)? + + enum SyncStatus { + case idle + case syncing + case success + case failed + case phoneNotReachable + } + + var body: some View { + ScrollView { + VStack(spacing: 16) { + Image(systemName: statusIcon) + .font(.system(size: 44)) + .foregroundColor(statusColor) + .symbolEffect(.pulse, isActive: syncStatus == .syncing) + + Text("reauth_required".localized) + .font(.headline) + .multilineTextAlignment(.center) + + Text("reauth_description".localized) + .font(.caption) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal, 8) + + if let statusMessage = statusMessage { + Text(statusMessage) + .font(.caption2) + .foregroundColor(statusMessageColor) + .multilineTextAlignment(.center) + } + + Button(action: syncWithiPhone) { + HStack { + if syncStatus == .syncing { + ProgressView() + .scaleEffect(0.8) + } else { + Image(systemName: "arrow.triangle.2.circlepath") + } + Text("sync_button".localized) + } + } + .buttonStyle(.borderedProminent) + .tint(syncStatus == .success ? .green : .blue) + .disabled(syncStatus == .syncing) + } + .padding() + } + } + + private var statusIcon: String { + switch syncStatus { + case .idle: + return "exclamationmark.arrow.circlepath" + case .syncing: + return "arrow.triangle.2.circlepath" + case .success: + return "checkmark.circle.fill" + case .failed: + return "xmark.circle.fill" + case .phoneNotReachable: + return "iphone.slash" + } + } + + private var statusColor: Color { + switch syncStatus { + case .idle: + return .orange + case .syncing: + return .blue + case .success: + return .green + case .failed: + return .red + case .phoneNotReachable: + return .gray + } + } + + private var statusMessage: String? { + switch syncStatus { + case .idle: + return nil + case .syncing: + return "syncing".localized + case .success: + return "sync_success".localized + case .failed: + return "sync_failed".localized + case .phoneNotReachable: + return "phone_not_reachable".localized + } + } + + private var statusMessageColor: Color { + switch syncStatus { + case .success: + return .green + case .failed, .phoneNotReachable: + return .red + default: + return .secondary + } + } + + private func syncWithiPhone() { + guard WCSession.default.activationState == .activated else { + syncStatus = .failed + return + } + + guard WCSession.default.isReachable else { + syncStatus = .phoneNotReachable + return + } + + syncStatus = .syncing + + WCSession.default.sendMessage( + ["action": "requestToken"], + replyHandler: { response in + DispatchQueue.main.async { + if let authDict = response["auth"] as? [String: Any] { + print("[Watch] Token received from iPhone via reauth sync") + self.processAuthData(authDict) + + if !TokenManager.shared.isTokenExpired() { + self.syncStatus = .success + + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + self.onTokenReceived?() + } + } else { + print("[Watch] Received token is already expired - iPhone needs reauth") + self.syncStatus = .failed + } + } else if let error = response["error"] as? String { + print("[Watch] iPhone returned error: \(error)") + + if error == "needsReauth" || error == "no_token" { + self.sendWatchTokenToiPhone() + } else { + self.syncStatus = .failed + } + } else { + print("[Watch] No token in response - iPhone may need reauth") + self.syncStatus = .failed + } + } + }, + errorHandler: { error in + DispatchQueue.main.async { + print("[Watch] Reauth sync failed: \(error.localizedDescription)") + self.syncStatus = .failed + } + } + ) + + DispatchQueue.main.asyncAfter(deadline: .now() + 15) { + if self.syncStatus == .syncing { + self.syncStatus = .failed + } + } + } + + private func sendWatchTokenToiPhone() { + guard TokenManager.shared.loadToken() != nil else { + print("[Watch] No token to send to iPhone") + syncStatus = .failed + return + } + + if TokenManager.shared.isTokenExpired() { + print("[Watch] Watch token is expired - attempting to refresh with retries...") + Task { + do { + _ = try await KretaAPIClient.shared.getValidToken() + print("[Watch] Token refresh succeeded! Now sending to iPhone...") + await MainActor.run { + self.sendRefreshedTokenToiPhone() + } + } catch { + print("[Watch] Token refresh failed after all retries: \(error)") + await MainActor.run { + self.syncStatus = .failed + } + } + } + return + } + + sendRefreshedTokenToiPhone() + } + + private func sendRefreshedTokenToiPhone() { + guard let token = TokenManager.shared.loadToken() else { + print("[Watch] No token after refresh") + syncStatus = .failed + return + } + + print("[Watch] Sending Watch token to iPhone...") + + var tokenData: [String: Any] = [ + "studentId": token.studentId, + "studentIdNorm": token.studentIdNorm, + "iss": token.iss, + "idToken": token.idToken, + "accessToken": token.accessToken, + "refreshToken": token.refreshToken, + "expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000) + ] + if let tokenVersion = token.effectiveTokenVersion { + tokenData["tokenVersion"] = tokenVersion + } + tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000) + + WCSession.default.sendMessage( + ["action": "receiveTokenFromWatch", "token": tokenData], + replyHandler: { response in + DispatchQueue.main.async { + if let success = response["success"] as? Bool, success { + print("[Watch] iPhone accepted our token!") + self.syncStatus = .success + + DataStore.shared.clearError() + + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + self.onTokenReceived?() + } + } else if let error = response["error"] as? String { + print("[Watch] iPhone rejected our token: \(error)") + self.syncStatus = .failed + } else { + self.syncStatus = .failed + } + } + }, + errorHandler: { error in + DispatchQueue.main.async { + print("[Watch] Failed to send token to iPhone: \(error)") + self.syncStatus = .failed + } + } + ) + } + + private func processAuthData(_ authDict: [String: Any]) { + do { + func parseInt64(_ value: Any?) -> Int64? { + if let value = value as? Int64 { return value } + if let value = value as? Int { return Int64(value) } + if let value = value as? Double { return Int64(value) } + if let value = value as? String, let parsed = Int64(value) { return parsed } + return nil + } + + let incomingSentAtMs = parseInt64(authDict["sentAtMs"]) ?? 0 + let jsonData = try JSONSerialization.data(withJSONObject: authDict) + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let timestamp = try container.decode(Int64.self) + return Date(timeIntervalSince1970: Double(timestamp) / 1000.0) + } + + let token = try decoder.decode(WatchToken.self, from: jsonData) + let currentToken = TokenManager.shared.loadToken() + let shouldForceAccountSwitch: Bool + if incomingSentAtMs > 0, + let currentToken, + !token.isSameAccount(as: currentToken) { + shouldForceAccountSwitch = true + } else { + shouldForceAccountSwitch = false + } + + try TokenManager.shared.saveToken( + token, + syncToSharedKeychain: false, + forceAccountSwitch: shouldForceAccountSwitch + ) + + DataStore.shared.checkTokenState() + DataStore.shared.clearError() + + print("[Watch] Token saved via reauth sync") + } catch { + print("[Watch] Failed to process auth data: \(error)") + } + } +} + +#Preview { + ReauthRequiredView() +} diff --git a/firka/ios/FirkaWatch Watch App/Views/SettingsView.swift b/firka/ios/FirkaWatch Watch App/Views/SettingsView.swift new file mode 100644 index 00000000..9e498d25 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/SettingsView.swift @@ -0,0 +1,78 @@ +import SwiftUI + +struct SettingsView: View { + @AppStorage("refreshInterval") private var refreshInterval: Int = 0 + @State private var l10n = WatchL10n.shared + + var body: some View { + List { + Section("language".localized) { + Toggle("sync_with_iphone".localized, isOn: Binding( + get: { l10n.syncWithiPhone }, + set: { l10n.syncWithiPhone = $0 } + )) + + if !l10n.syncWithiPhone { + Picker("language".localized, selection: Binding( + get: { l10n.currentLanguage }, + set: { l10n.setLanguage($0) } + )) { + ForEach(WatchLanguage.allCases, id: \.self) { lang in + HStack { + Text(lang.flag) + Text(lang.displayName) + } + .tag(lang) + } + } + } + } + + Section("refresh".localized) { + Picker("refresh_interval".localized, selection: $refreshInterval) { + Text("auto".localized).tag(0) + Text("15_minutes".localized).tag(15) + Text("30_minutes".localized).tag(30) + Text("1_hour".localized).tag(60) + } + } + + Section { + Button("clear_cache".localized) { + clearCache() + } + + Button("logout".localized, role: .destructive) { + logout() + } + } + + Section { + HStack { + Text("version".localized) + Spacer() + Text(appVersion) + .foregroundColor(.secondary) + } + } + } + .navigationTitle("settings".localized) + } + + private var appVersion: String { + Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0" + } + + private func clearCache() { + DataStore.shared.clearCache() + } + + private func logout() { + TokenManager.shared.deleteToken() + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: false, + activeStudentIdNorm: nil + ) + DataStore.shared.clearAll() + } +} diff --git a/firka/ios/FirkaWatch Watch App/Views/TimetableView.swift b/firka/ios/FirkaWatch Watch App/Views/TimetableView.swift new file mode 100644 index 00000000..3cb473f4 --- /dev/null +++ b/firka/ios/FirkaWatch Watch App/Views/TimetableView.swift @@ -0,0 +1,369 @@ +import SwiftUI + +struct TimetableView: View { + let dataStore: DataStore + + @State private var selectedDay: Int = 0 + @State private var weekOffset: Int = 0 + + private var dayLabels: [String] { + [ + "day_mon".localized, + "day_tue".localized, + "day_wed".localized, + "day_thu".localized, + "day_fri".localized + ] + } + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + daySelector + + Divider() + .padding(.vertical, 4) + + lessonsContent + } + .onAppear { + updateWeekAndDay() + } + } + } + + private func updateWeekAndDay() { + let calendar = Calendar.current + let now = Date() + + if shouldShowNextWeek() { + weekOffset = 1 + selectedDay = findFirstSchoolDay(weekOffset: 1) + return + } + + weekOffset = 0 + let weekday = calendar.component(.weekday, from: now) + let todayIndex = weekday - 2 + + if todayIndex < 0 || todayIndex > 4 { + selectedDay = findFirstSchoolDay(weekOffset: 0) + return + } + + if areTodayLessonsDone(dayIndex: todayIndex) { + if let nextDay = findNextSchoolDay(after: todayIndex) { + selectedDay = nextDay + } else { + selectedDay = todayIndex + } + } else { + selectedDay = todayIndex + } + } + + private func areTodayLessonsDone(dayIndex: Int) -> Bool { + let todayLessons = lessonsForDay(dayIndex) + guard !todayLessons.isEmpty else { return true } + + let now = Date() + let lastLesson = todayLessons.sorted { $0.end > $1.end }.first + return lastLesson.map { now > $0.end } ?? true + } + + private func findNextSchoolDay(after dayIndex: Int) -> Int? { + for day in (dayIndex + 1)...4 { + if !lessonsForDay(day).isEmpty { + return day + } + } + return nil + } + + private func findFirstSchoolDay(weekOffset: Int) -> Int { + let oldOffset = self.weekOffset + for day in 0...4 { + let lessons = lessonsForDayWithOffset(day, weekOffset: weekOffset) + if !lessons.isEmpty { + return day + } + } + return 0 + } + + private func lessonsForDayWithOffset(_ day: Int, weekOffset: Int) -> [WidgetLesson] { + guard let data = dataStore.data else { return [] } + + let allLessons: [WidgetLesson] + if let all = data.timetable.allLessons, !all.isEmpty { + allLessons = all + } else { + return [] + } + + let targetDateStr = getDateStringForDayWithOffset(day, weekOffset: weekOffset) + return allLessons.filter { $0.date == targetDateStr } + } + + private func getDateStringForDayWithOffset(_ day: Int, weekOffset: Int) -> String { + let calendar = Calendar.current + let now = Date() + + let weekday = calendar.component(.weekday, from: now) + let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday) + + guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now) else { + return "" + } + + let totalDaysToAdd = day + (weekOffset * 7) + guard let targetDate = calendar.date(byAdding: .day, value: totalDaysToAdd, to: monday) else { + return "" + } + + return formatDate(targetDate) + } + + private func shouldShowNextWeek() -> Bool { + guard let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty else { + return false + } + + let now = Date() + let calendar = Calendar.current + + let weekday = calendar.component(.weekday, from: now) + let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday) + guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now), + let friday = calendar.date(byAdding: .day, value: 4, to: monday) else { + return false + } + let fridayString = formatDate(friday) + let mondayString = formatDate(monday) + + let currentWeekLessons = allLessons.filter { lesson in + lesson.date >= mondayString && lesson.date <= fridayString + } + + guard !currentWeekLessons.isEmpty else { + return false + } + + let lastLesson = currentWeekLessons + .sorted { $0.date > $1.date || ($0.date == $1.date && $0.end > $1.end) } + .first + + guard let last = lastLesson else { + return false + } + + return now > last.end + } + + // MARK: - Day Selector + + private var daySelector: some View { + HStack(spacing: 6) { + ForEach(0..<5, id: \.self) { day in + Button(action: { selectedDay = day }) { + Text(dayLabels[day]) + .font(.system(size: 14, weight: .semibold)) + .frame(maxWidth: .infinity) + .frame(height: 32) + .foregroundColor(selectedDay == day ? .white : .primary) + .background(selectedDay == day ? Color.blue : Color.clear) + .cornerRadius(8) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(isToday(day) && selectedDay != day ? Color.blue : Color.clear, lineWidth: 2) + ) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + } + + private func isToday(_ day: Int) -> Bool { + guard weekOffset == 0 else { return false } + let weekday = Calendar.current.component(.weekday, from: Date()) + return day == weekday - 2 + } + + // MARK: - Lessons Content + + @ViewBuilder + private var lessonsContent: some View { + let lessons = lessonsForDay(selectedDay) + + if lessons.isEmpty { + freeDayView + } else { + ScrollView { + VStack(spacing: 6) { + ForEach(lessons) { lesson in + NavigationLink { + LessonDetailView(lesson: lesson) + } label: { + lessonRow(lesson) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + } + } + } + + private func lessonsForDay(_ day: Int) -> [WidgetLesson] { + guard let data = dataStore.data else { return [] } + + let allLessons: [WidgetLesson] + if let all = data.timetable.allLessons, !all.isEmpty { + allLessons = all + } else { + var combined: [WidgetLesson] = [] + combined.append(contentsOf: data.timetable.today) + combined.append(contentsOf: data.timetable.tomorrow) + if let nextSchoolDay = data.timetable.nextSchoolDay { + combined.append(contentsOf: nextSchoolDay) + } + allLessons = combined + } + + let targetDateStr = getDateStringForDay(day) + + let uniqueDates = Set(allLessons.map { $0.date }).sorted() + print("[Watch] lessonsForDay: day=\(day), weekOffset=\(weekOffset), targetDate=\(targetDateStr), lessons=\(allLessons.count)") + print("[Watch] Unique dates in lessons: \(uniqueDates)") + + if let first = allLessons.first { + let cal = Calendar.current + let comp = cal.dateComponents([.year, .month, .day, .hour, .minute], from: first.start) + print("[Watch] First lesson: date=\(first.date), start=\(comp.year!)-\(comp.month!)-\(comp.day!) \(comp.hour!):\(comp.minute!)") + } + + let filtered = allLessons.filter { $0.date == targetDateStr } + print("[Watch] Filtered lessons: \(filtered.count) for \(targetDateStr)") + + return filtered.sorted { ($0.lessonNumber ?? 0) < ($1.lessonNumber ?? 0) } + } + + private func getDateStringForDay(_ day: Int) -> String { + let calendar = Calendar.current + let now = Date() + + let weekday = calendar.component(.weekday, from: now) + let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday) + + guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now) else { + return "" + } + + let totalDaysToAdd = day + (weekOffset * 7) + guard let targetDate = calendar.date(byAdding: .day, value: totalDaysToAdd, to: monday) else { + return "" + } + + return formatDate(targetDate) + } + + private func formatDate(_ date: Date) -> String { + let calendar = Calendar.current + let components = calendar.dateComponents([.year, .month, .day], from: date) + return String(format: "%04d-%02d-%02d", + components.year ?? 0, + components.month ?? 0, + components.day ?? 0) + } + + private var freeDayView: some View { + VStack(spacing: 12) { + Image(systemName: "sun.max.fill") + .font(.system(size: 40)) + .foregroundColor(.yellow) + + Text("free_day".localized) + .font(.headline) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() + } + + // MARK: - Lesson Row + + @ViewBuilder + private func lessonRow(_ lesson: WidgetLesson) -> some View { + FirkaCard(isHighlighted: lesson.isCurrentlyActive) { + HStack(alignment: .top, spacing: 8) { + if let number = lesson.lessonNumber { + Text("\(number).") + .font(.subheadline) + .fontWeight(.bold) + .foregroundColor(.blue) + .frame(width: 24, alignment: .leading) + } + + VStack(alignment: .leading, spacing: 4) { + HStack { + HStack(spacing: 4) { + Text(lesson.displayName) + .font(.subheadline) + .fontWeight(.medium) + .lineLimit(1) + + if let statusIcon = lessonStatusIconName(for: lesson) { + Image(systemName: statusIcon) + .font(.caption2) + .foregroundColor(lessonStatusColor(for: lesson)) + } + } + + Spacer() + + Text(lesson.start, style: .time) + .font(.caption) + .foregroundColor(.secondary) + } + + HStack(spacing: 4) { + if let teacher = lesson.teacher { + Text(teacher) + .lineLimit(1) + } + if let room = lesson.roomName { + Text("•") + Text(room) + } + } + .font(.caption2) + .foregroundColor(.secondary) + } + } + } + } + + private func lessonStatusIconName(for lesson: WidgetLesson) -> String? { + if lesson.isCancelled { + return "xmark.circle.fill" + } + if lesson.isSubstitution { + return "exclamationmark.circle.fill" + } + return nil + } + + private func lessonStatusColor(for lesson: WidgetLesson) -> Color { + lesson.isCancelled ? .red : .yellow + } +} + +#if DEBUG +struct TimetableView_Previews: PreviewProvider { + static var previews: some View { + TimetableView(dataStore: DataStore.shared) + } +} +#endif diff --git a/firka/ios/FirkaWatchComplications/Assets.xcassets/AccentColor.colorset/Contents.json b/firka/ios/FirkaWatchComplications/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatchComplications/Assets.xcassets/AppIcon.appiconset/Contents.json b/firka/ios/FirkaWatchComplications/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..49c81cd8 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "watchos", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatchComplications/Assets.xcassets/Contents.json b/firka/ios/FirkaWatchComplications/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatchComplications/Assets.xcassets/WidgetBackground.colorset/Contents.json b/firka/ios/FirkaWatchComplications/Assets.xcassets/WidgetBackground.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/Assets.xcassets/WidgetBackground.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/FirkaWatchComplications/FirkaComplications.swift b/firka/ios/FirkaWatchComplications/FirkaComplications.swift new file mode 100644 index 00000000..67f8c320 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/FirkaComplications.swift @@ -0,0 +1,369 @@ +#if os(watchOS) +import WidgetKit +import SwiftUI + +// MARK: - Complication Localization Helper + +private struct ComplicationL10n { + private static let appGroupID = "group.app.firkaa.legacy" + + enum Language: String { + case hungarian = "hu" + case english = "en" + case german = "de" + } + + static var currentLanguage: Language { + guard let defaults = UserDefaults(suiteName: appGroupID) else { + return .hungarian + } + let code = defaults.string(forKey: "watch_language") ?? "hu" + return Language(rawValue: code) ?? .hungarian + } + + static func string(_ key: String) -> String { + switch currentLanguage { + case .hungarian: return hungarianStrings[key] ?? key + case .english: return englishStrings[key] ?? key + case .german: return germanStrings[key] ?? key + } + } + + private static let hungarianStrings: [String: String] = [ + "current_lesson": "Jelenlegi óra", + "next": "Következő", + "no_more_lessons": "Nincs több óra", + "average_abbrev": "Átl", + "next_lesson_title": "Következő óra", + "average_title": "Átlag", + "lesson_inline": "Óra (inline)" + ] + + private static let englishStrings: [String: String] = [ + "current_lesson": "Current Lesson", + "next": "Next", + "no_more_lessons": "No more lessons", + "average_abbrev": "Avg", + "next_lesson_title": "Next Lesson", + "average_title": "Average", + "lesson_inline": "Lesson (inline)" + ] + + private static let germanStrings: [String: String] = [ + "current_lesson": "Aktuelle Stunde", + "next": "Nächste", + "no_more_lessons": "Keine Stunden mehr", + "average_abbrev": "Ø", + "next_lesson_title": "Nächste Stunde", + "average_title": "Durchschnitt", + "lesson_inline": "Stunde (inline)" + ] +} + +// MARK: - Watch Cache Loader + +private struct WatchCacheLoader { + private static let appGroupID = "group.app.firkaa.legacy" + private static let cacheFileName = "watch_data.json" + + static func loadWidgetData() -> WidgetData? { + guard let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: appGroupID + ) else { + print("[WatchComplication] No App Group container") + return nil + } + + let fileURL = containerURL.appendingPathComponent(cacheFileName) + + guard FileManager.default.fileExists(atPath: fileURL.path) else { + print("[WatchComplication] Cache file not found: \(fileURL.path)") + return nil + } + + guard let data = try? Data(contentsOf: fileURL) else { + print("[WatchComplication] Could not read cache file") + return nil + } + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + + struct CachedWatchData: Codable { + let widgetData: WidgetData + let lastUpdated: Date + } + + do { + let cached = try decoder.decode(CachedWatchData.self, from: data) + print("[WatchComplication] Loaded cache from \(cached.lastUpdated)") + return cached.widgetData + } catch { + print("[WatchComplication] Failed to decode: \(error)") + return nil + } + } +} + +// MARK: - Timeline Entry + +struct FirkaTimelineEntry: TimelineEntry { + let date: Date + let data: WidgetData? +} + +// MARK: - Timeline Provider + +struct FirkaTimelineProvider: TimelineProvider { + func placeholder(in context: Context) -> FirkaTimelineEntry { + FirkaTimelineEntry(date: Date(), data: nil) + } + + func getSnapshot(in context: Context, completion: @escaping (FirkaTimelineEntry) -> Void) { + let data = WatchCacheLoader.loadWidgetData() + completion(FirkaTimelineEntry(date: Date(), data: data)) + } + + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + let data = WatchCacheLoader.loadWidgetData() + let entry = FirkaTimelineEntry(date: Date(), data: data) + + let calendar = Calendar.current + let now = Date() + let hour = calendar.component(.hour, from: now) + let weekday = calendar.component(.weekday, from: now) + let isSchoolHours = (weekday >= 2 && weekday <= 6) && (hour >= 6 && hour <= 16) + + let refreshInterval: TimeInterval = isSchoolHours ? 15 * 60 : 60 * 60 + let nextRefresh = now.addingTimeInterval(refreshInterval) + + let timeline = Timeline(entries: [entry], policy: .after(nextRefresh)) + completion(timeline) + } +} + +// MARK: - Next Lesson Complication (accessoryRectangular) + +struct NextLessonComplication: Widget { + let kind = "NextLessonComplication" + + var body: some WidgetConfiguration { + StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in + NextLessonView(entry: entry) + .containerBackground(.fill.tertiary, for: .widget) + } + .configurationDisplayName(ComplicationL10n.string("next_lesson_title")) + .description("Shows the current or next lesson.") + .supportedFamilies([.accessoryRectangular]) + } +} + +private struct NextLessonView: View { + let entry: FirkaTimelineEntry + + private var now: Date { Date() } + + private var todayLessons: [WidgetLesson] { + (entry.data?.timetable.today ?? []).sorted { $0.start < $1.start } + } + + private var currentLesson: WidgetLesson? { + todayLessons.first { now >= $0.start && now <= $0.end } + } + + private var nextLesson: WidgetLesson? { + todayLessons.first { $0.start > now } + } + + var body: some View { + if let breakInfo = entry.data?.timetable.currentBreak { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 4) { + Image(systemName: SeasonalIconHelper.iconName(for: breakInfo.nameKey, season: nil)) + .font(.caption) + Text(breakInfo.name) + .font(.headline) + .lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if let lesson = currentLesson { + VStack(alignment: .leading, spacing: 2) { + Text(ComplicationL10n.string("current_lesson")) + .font(.caption2) + .foregroundStyle(.secondary) + Text(lesson.displayName) + .font(.headline) + .lineLimit(1) + HStack(spacing: 4) { + if let room = lesson.roomName { + Image(systemName: "door.right.hand.closed") + .font(.caption2) + Text(room) + .font(.caption2) + } + Text("→ \(lesson.end, formatter: Self.timeFormatter)") + .font(.caption2) + } + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if let lesson = nextLesson { + VStack(alignment: .leading, spacing: 2) { + Text(ComplicationL10n.string("next")) + .font(.caption2) + .foregroundStyle(.secondary) + Text(lesson.displayName) + .font(.headline) + .lineLimit(1) + HStack(spacing: 4) { + if let room = lesson.roomName { + Image(systemName: "door.right.hand.closed") + .font(.caption2) + Text(room) + .font(.caption2) + } + Text(lesson.start, formatter: Self.timeFormatter) + .font(.caption2) + } + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if entry.data != nil { + VStack(alignment: .leading, spacing: 2) { + Image(systemName: "checkmark.circle.fill") + .font(.title3) + .foregroundStyle(.green) + Text(ComplicationL10n.string("no_more_lessons")) + .font(.headline) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + VStack(alignment: .leading, spacing: 2) { + Image(systemName: "book.fill") + .font(.title3) + Text("Firka") + .font(.headline) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private static let timeFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm" + return f + }() +} + +// MARK: - Average Complication (accessoryCircular) + +struct AverageComplication: Widget { + let kind = "AverageComplication" + + var body: some WidgetConfiguration { + StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in + AverageView(entry: entry) + .containerBackground(.fill.tertiary, for: .widget) + } + .configurationDisplayName(ComplicationL10n.string("average_title")) + .description("Shows the overall grade average.") + .supportedFamilies([.accessoryCircular]) + } +} + +private struct AverageView: View { + let entry: FirkaTimelineEntry + + private var averageColor: Color { + guard let avg = entry.data?.averages.overall else { return .gray } + switch avg { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } + + var body: some View { + if let average = entry.data?.averages.overall { + Gauge(value: average, in: 1...5) { + Text(ComplicationL10n.string("average_abbrev")) + } currentValueLabel: { + Text(String(format: "%.1f", average)) + .font(.system(.body, design: .rounded, weight: .bold)) + } + .gaugeStyle(.accessoryCircular) + .tint(averageColor) + } else { + ZStack { + AccessoryWidgetBackground() + Text("—") + .font(.title3) + .fontWeight(.bold) + } + } + } +} + +// MARK: - Inline Complication (accessoryInline) + +struct InlineComplication: Widget { + let kind = "InlineComplication" + + var body: some WidgetConfiguration { + StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in + InlineView(entry: entry) + .containerBackground(.fill.tertiary, for: .widget) + } + .configurationDisplayName(ComplicationL10n.string("lesson_inline")) + .description("One-line summary of the next lesson.") + .supportedFamilies([.accessoryInline]) + } +} + +private struct InlineView: View { + let entry: FirkaTimelineEntry + + private var now: Date { Date() } + + private var todayLessons: [WidgetLesson] { + (entry.data?.timetable.today ?? []).sorted { $0.start < $1.start } + } + + private var currentOrNextLesson: WidgetLesson? { + todayLessons.first { now >= $0.start && now <= $0.end } + ?? todayLessons.first { $0.start > now } + } + + var body: some View { + if let breakInfo = entry.data?.timetable.currentBreak { + Text(breakInfo.name) + } else if let lesson = currentOrNextLesson { + Text("\(lesson.displayName) \(lesson.start, formatter: Self.timeFormatter)") + } else if entry.data != nil { + Text(ComplicationL10n.string("no_more_lessons")) + } else { + Text("Firka") + } + } + + private static let timeFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm" + return f + }() +} + +// MARK: - Widget Bundle + +@main +struct FirkaWatchWidgets: WidgetBundle { + var body: some Widget { + NextLessonComplication() + AverageComplication() + InlineComplication() + } +} +#endif diff --git a/firka/ios/FirkaWatchComplications/Info.plist b/firka/ios/FirkaWatchComplications/Info.plist new file mode 100644 index 00000000..0f118fb7 --- /dev/null +++ b/firka/ios/FirkaWatchComplications/Info.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/firka/ios/FirkaWatchComplicationsExtension.entitlements b/firka/ios/FirkaWatchComplicationsExtension.entitlements new file mode 100644 index 00000000..487d6b1e --- /dev/null +++ b/firka/ios/FirkaWatchComplicationsExtension.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.ubiquity-kvstore-identifier + $(TeamIdentifierPrefix)app.firkaa.legacy + com.apple.security.application-groups + + group.app.firkaa.legacy + + + diff --git a/firka/ios/Flutter/AppFrameworkInfo.plist b/firka/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 00000000..0d140800 --- /dev/null +++ b/firka/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 15.0 + + diff --git a/firka/ios/Flutter/Debug.xcconfig b/firka/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..ec97fc6f --- /dev/null +++ b/firka/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/firka/ios/Flutter/Release.xcconfig b/firka/ios/Flutter/Release.xcconfig new file mode 100644 index 00000000..c4855bfe --- /dev/null +++ b/firka/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/firka/ios/Flutter/WidgetExtension.xcconfig b/firka/ios/Flutter/WidgetExtension.xcconfig new file mode 100644 index 00000000..e3ebc25e --- /dev/null +++ b/firka/ios/Flutter/WidgetExtension.xcconfig @@ -0,0 +1,2 @@ +// Extensions take the version from Flutter so it matches the app. +#include "Generated.xcconfig" diff --git a/firka/ios/HomeWidgetsExtension.entitlements b/firka/ios/HomeWidgetsExtension.entitlements new file mode 100644 index 00000000..0361bd84 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.ubiquity-kvstore-identifier + $(TeamIdentifierPrefix)$(CFBundleIdentifier) + com.apple.security.application-groups + + group.app.firkaa.legacy + + + diff --git a/firka/ios/HomeWidgetsExtension/Assets.xcassets/AccentColor.colorset/Contents.json b/firka/ios/HomeWidgetsExtension/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/HomeWidgetsExtension/Assets.xcassets/AppIcon.appiconset/Contents.json b/firka/ios/HomeWidgetsExtension/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..23058801 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,35 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/HomeWidgetsExtension/Assets.xcassets/Contents.json b/firka/ios/HomeWidgetsExtension/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/HomeWidgetsExtension/Assets.xcassets/WidgetBackground.colorset/Contents.json b/firka/ios/HomeWidgetsExtension/Assets.xcassets/WidgetBackground.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Assets.xcassets/WidgetBackground.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/HomeWidgetsExtension/AveragesWidget.swift b/firka/ios/HomeWidgetsExtension/AveragesWidget.swift new file mode 100644 index 00000000..99dbfc48 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/AveragesWidget.swift @@ -0,0 +1,45 @@ +import WidgetKit +import SwiftUI + +struct AveragesWidget: Widget { + let kind: String = "AveragesWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: AveragesWidgetIntent.self, + provider: AveragesProvider() + ) { entry in + AveragesWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_averages_title", defaultValue: "Averages")) + .description(LocalizedStringResource("widget_averages_description", defaultValue: "Shows subject averages")) + .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) + } +} + +struct AveragesWidgetView: View { + @Environment(\.widgetFamily) var family + let entry: AveragesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var body: some View { + Group { + switch family { + case .systemSmall: + AveragesSmallView(entry: entry, localization: localization) + case .systemMedium: + AveragesMediumView(entry: entry, localization: localization) + case .systemLarge: + AveragesLargeView(entry: entry, localization: localization) + default: + AveragesMediumView(entry: entry, localization: localization) + } + } + .widgetURL(URL(string: "firka://widget/grades")) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Controls/AppControls.swift b/firka/ios/HomeWidgetsExtension/Controls/AppControls.swift new file mode 100644 index 00000000..7361e012 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Controls/AppControls.swift @@ -0,0 +1,94 @@ +import WidgetKit +import SwiftUI +import AppIntents + +private let appGroup = "group.app.firkaa.legacy" + +// MARK: - Navigation Intents (iOS 16+, used by Controls and Shortcuts) + +@available(iOS 16.0, *) +struct OpenHomeIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("control_home_title", defaultValue: "Firka Home") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("control_home_description", defaultValue: "Open Firka home screen")) + static var openAppWhenRun: Bool = true + + func perform() async throws -> some IntentResult { + UserDefaults(suiteName: appGroup)?.set("home", forKey: "controlNavigation") + return .result() + } +} + +@available(iOS 16.0, *) +struct OpenGradesIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("control_grades_title", defaultValue: "Firka Grades") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("control_grades_description", defaultValue: "Open Firka grades")) + static var openAppWhenRun: Bool = true + + func perform() async throws -> some IntentResult { + UserDefaults(suiteName: appGroup)?.set("grades", forKey: "controlNavigation") + return .result() + } +} + +@available(iOS 16.0, *) +struct OpenTimetableIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("control_timetable_title", defaultValue: "Firka Timetable") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("control_timetable_description", defaultValue: "Open Firka timetable")) + static var openAppWhenRun: Bool = true + + func perform() async throws -> some IntentResult { + UserDefaults(suiteName: appGroup)?.set("timetable", forKey: "controlNavigation") + return .result() + } +} + +// MARK: - Home Control (iOS 18+) + +@available(iOS 18.0, *) +struct HomeControl: ControlWidget { + static let kind = "app.firkaa.legacy.control.home" + + var body: some ControlWidgetConfiguration { + StaticControlConfiguration(kind: Self.kind) { + ControlWidgetButton(action: OpenHomeIntent()) { + Label(LocalizedStringResource("control_home_label", defaultValue: "Home"), systemImage: "house.fill") + } + } + .displayName(LocalizedStringResource("control_home_display", defaultValue: "Firka - Home")) + .description(LocalizedStringResource("control_home_description", defaultValue: "Open Firka home screen")) + } +} + +// MARK: - Grades Control (iOS 18+) + +@available(iOS 18.0, *) +struct GradesControl: ControlWidget { + static let kind = "app.firkaa.legacy.control.grades" + + var body: some ControlWidgetConfiguration { + StaticControlConfiguration(kind: Self.kind) { + ControlWidgetButton(action: OpenGradesIntent()) { + Label(LocalizedStringResource("control_grades_label", defaultValue: "Grades"), systemImage: "star.fill") + } + } + .displayName(LocalizedStringResource("control_grades_display", defaultValue: "Firka - Grades")) + .description(LocalizedStringResource("control_grades_description", defaultValue: "Open Firka grades")) + } +} + +// MARK: - Timetable Control (iOS 18+) + +@available(iOS 18.0, *) +struct TimetableControl: ControlWidget { + static let kind = "app.firkaa.legacy.control.timetable" + + var body: some ControlWidgetConfiguration { + StaticControlConfiguration(kind: Self.kind) { + ControlWidgetButton(action: OpenTimetableIntent()) { + Label(LocalizedStringResource("control_timetable_label", defaultValue: "Timetable"), systemImage: "calendar") + } + } + .displayName(LocalizedStringResource("control_timetable_display", defaultValue: "Firka - Timetable")) + .description(LocalizedStringResource("control_timetable_description", defaultValue: "Open Firka timetable")) + } +} diff --git a/firka/ios/HomeWidgetsExtension/GradesWidget.swift b/firka/ios/HomeWidgetsExtension/GradesWidget.swift new file mode 100644 index 00000000..7b55be15 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/GradesWidget.swift @@ -0,0 +1,45 @@ +import WidgetKit +import SwiftUI + +struct GradesWidget: Widget { + let kind: String = "GradesWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: GradesWidgetIntent.self, + provider: GradesProvider() + ) { entry in + GradesWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_grades_title", defaultValue: "Recent Grades")) + .description(LocalizedStringResource("widget_grades_description", defaultValue: "Shows your recent grades")) + .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) + } +} + +struct GradesWidgetView: View { + @Environment(\.widgetFamily) var family + let entry: GradesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var body: some View { + Group { + switch family { + case .systemSmall: + GradesSmallView(entry: entry, localization: localization) + case .systemMedium: + GradesMediumView(entry: entry, localization: localization) + case .systemLarge: + GradesLargeView(entry: entry, localization: localization) + default: + GradesMediumView(entry: entry, localization: localization) + } + } + .widgetURL(URL(string: "firka://widget/grades")) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Helpers/Localization.swift b/firka/ios/HomeWidgetsExtension/Helpers/Localization.swift new file mode 100644 index 00000000..33e4838a --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Helpers/Localization.swift @@ -0,0 +1,273 @@ +import Foundation + +struct WidgetLocalization { + let locale: String + + init(locale: String = "hu") { + self.locale = locale + } + + private var translations: [String: [String: String]] { + [ + "today_timetable": [ + "hu": "Mai órarend", + "en": "Today's timetable", + "de": "Stundenplan heute" + ], + "tomorrow_timetable": [ + "hu": "Holnapi órarend", + "en": "Tomorrow's timetable", + "de": "Stundenplan morgen" + ], + "next_school_day_timetable": [ + "hu": "Következő órarend (%@)", + "en": "Next timetable (%@)", + "de": "Nächster Stundenplan (%@)" + ], + "no_lessons_ahead": [ + "hu": "Nincs óra a héten", + "en": "No lessons this week", + "de": "Kein Unterricht diese Woche" + ], + "current_lesson": [ + "hu": "Jelenlegi óra", + "en": "Current lesson", + "de": "Aktuelle Stunde" + ], + "next_lesson": [ + "hu": "Következő óra", + "en": "Next lesson", + "de": "Nächste Stunde" + ], + "recent_grades": [ + "hu": "Legutóbbi jegyek", + "en": "Recent grades", + "de": "Letzte Noten" + ], + "subject_averages": [ + "hu": "Tantárgyi átlagok", + "en": "Subject averages", + "de": "Fachdurchschnitte" + ], + "overall_average": [ + "hu": "Tanulmányi átlag", + "en": "Overall average", + "de": "Gesamtdurchschnitt" + ], + "no_lessons": [ + "hu": "Nincs több óra ma", + "en": "No more lessons today", + "de": "Keine Stunden mehr heute" + ], + "no_grades": [ + "hu": "Még nincsenek jegyeid", + "en": "No grades yet", + "de": "Noch keine Noten" + ], + "no_averages": [ + "hu": "Még nincsenek átlagok", + "en": "No averages yet", + "de": "Noch keine Durchschnitte" + ], + "login_required": [ + "hu": "Jelentkezz be újra", + "en": "Please log in again", + "de": "Bitte erneut anmelden" + ], + "timetable_unavailable": [ + "hu": "Az órarend még nem elérhető", + "en": "Timetable not available yet", + "de": "Stundenplan noch nicht verfügbar" + ], + "happy_break": [ + "hu": "Kellemes %@ szünetet!", + "en": "Happy %@ break!", + "de": "Schöne %@ Ferien!" + ], + "days_remaining": [ + "hu": "Még %d nap", + "en": "%d days left", + "de": "Noch %d Tage" + ], + "break_autumn": [ + "hu": "őszi", + "en": "autumn", + "de": "Herbst" + ], + "break_winter": [ + "hu": "téli", + "en": "winter", + "de": "Winter" + ], + "break_spring": [ + "hu": "tavaszi", + "en": "spring", + "de": "Frühlings" + ], + "break_summer": [ + "hu": "nyári", + "en": "summer", + "de": "Sommer" + ], + "room": [ + "hu": "Terem", + "en": "Room", + "de": "Raum" + ], + "until": [ + "hu": "eddig:", + "en": "until", + "de": "bis" + ], + "no_more_lessons_today": [ + "hu": "Ma már nincs több óra", + "en": "No more lessons today", + "de": "Keine Stunden mehr heute" + ], + "tomorrow": [ + "hu": "Holnap", + "en": "Tomorrow", + "de": "Morgen" + ], + "tomorrow_short": [ + "hu": "holnap", + "en": "tmrw", + "de": "morgen" + ], + "next": [ + "hu": "Következő", + "en": "Next", + "de": "Nächste" + ], + "minutes_short": [ + "hu": "perc", + "en": "min", + "de": "Min" + ], + "lesson_short": [ + "hu": "óra", + "en": "lesson", + "de": "Std" + ], + "break_between": [ + "hu": "Szünet", + "en": "Break", + "de": "Pause" + ], + "in_minutes": [ + "hu": "%d perc múlva", + "en": "in %d min", + "de": "in %d Min" + ], + "today_new_grades": [ + "hu": "Ma: %d új jegy", + "en": "Today: %d new", + "de": "Heute: %d neue" + ], + "latest": [ + "hu": "Legutóbbi", + "en": "Latest", + "de": "Letzte" + ], + "today_grades": [ + "hu": "Mai jegyek", + "en": "Today's grades", + "de": "Heutige Noten" + ], + "pieces": [ + "hu": "%d db", + "en": "%d pcs", + "de": "%d Stk" + ], + "latest_grade": [ + "hu": "Legutóbbi jegy", + "en": "Latest grade", + "de": "Letzte Note" + ], + "average_short": [ + "hu": "Átlag", + "en": "Avg", + "de": "Durchschn." + ], + "overall_average_title": [ + "hu": "Összesített átlag", + "en": "Overall average", + "de": "Gesamtdurchschnitt" + ], + "subjects_count": [ + "hu": "%d tárgy", + "en": "%d subjects", + "de": "%d Fächer" + ], + "subject_averages_title": [ + "hu": "Tantárgy átlagok", + "en": "Subject averages", + "de": "Fachdurchschnitte" + ], + "subject_short": [ + "hu": "tárgy", + "en": "subj", + "de": "Fächer" + ], + "minutes_abbrev": [ + "hu": "p", + "en": "min", + "de": "Min" + ], + "hours_abbrev": [ + "hu": "óra", + "en": "h", + "de": "Std" + ], + "in_hours": [ + "hu": "%d óra múlva", + "en": "in %d h", + "de": "in %d Std" + ] + ] + } + + func string(_ key: String) -> String { + translations[key]?[locale] ?? translations[key]?["hu"] ?? key + } + + func string(_ key: String, _ arg: String) -> String { + let template = string(key) + return template.replacingOccurrences(of: "%@", with: arg) + } + + func string(_ key: String, _ arg: Int) -> String { + let template = string(key) + return template.replacingOccurrences(of: "%d", with: "\(arg)") + } + + static func formatShortDate(_ isoString: String?, locale: String = "hu") -> String { + guard let isoString = isoString else { return "" } + + let isoFormatter = ISO8601DateFormatter() + isoFormatter.formatOptions = [.withInternetDateTime] + + let shortFormatter = DateFormatter() + shortFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" + shortFormatter.locale = Locale(identifier: "en_US_POSIX") + + let date: Date? + if let d = isoFormatter.date(from: isoString) { + date = d + } else if let d = shortFormatter.date(from: isoString) { + date = d + } else { + let simple = DateFormatter() + simple.dateFormat = "yyyy-MM-dd" + simple.locale = Locale(identifier: "en_US_POSIX") + date = simple.date(from: String(isoString.prefix(10))) + } + + guard let date = date else { return "" } + + let displayFormatter = DateFormatter() + displayFormatter.locale = Locale(identifier: locale == "de" ? "de_DE" : locale == "en" ? "en_US" : "hu_HU") + displayFormatter.dateFormat = locale == "hu" ? "MMM d." : "MMM d" + return displayFormatter.string(from: date) + } +} diff --git a/firka/ios/HomeWidgetsExtension/HomeWidgetsBundle.swift b/firka/ios/HomeWidgetsExtension/HomeWidgetsBundle.swift new file mode 100644 index 00000000..d7535634 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/HomeWidgetsBundle.swift @@ -0,0 +1,29 @@ +import WidgetKit +import SwiftUI + +@main +struct HomeWidgetsBundle: WidgetBundle { + var body: some Widget { + // Home Screen Widgets + TimetableWidget() + GradesWidget() + AveragesWidget() + + // Lock Screen Widgets (circular & rectangular) + TimetableLockScreenWidget() + GradesLockScreenWidget() + AveragesLockScreenWidget() + + // Inline Widgets (above the clock) + TimetableInlineWidget() + GradesInlineWidget() + AveragesInlineWidget() + + // Control Widgets (iOS 18+ Control Center & Lock Screen buttons) + if #available(iOS 18.0, *) { + HomeControl() + GradesControl() + TimetableControl() + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/Info.plist b/firka/ios/HomeWidgetsExtension/Info.plist new file mode 100644 index 00000000..0f118fb7 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Info.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/firka/ios/HomeWidgetsExtension/Intents/AveragesIntent.swift b/firka/ios/HomeWidgetsExtension/Intents/AveragesIntent.swift new file mode 100644 index 00000000..531b2712 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Intents/AveragesIntent.swift @@ -0,0 +1,13 @@ +import AppIntents +import WidgetKit + +struct AveragesWidgetIntent: WidgetConfigurationIntent { + static var title: LocalizedStringResource = LocalizedStringResource("widget_averages_title", defaultValue: "Averages") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("widget_averages_description", defaultValue: "Shows subject averages")) + + @Parameter(title: LocalizedStringResource("param_style", defaultValue: "Style"), default: .liquidGlass) + var style: WidgetStyle? + + @Parameter(title: LocalizedStringResource("param_subjects", defaultValue: "Subjects")) + var selectedSubjects: [SubjectEntity]? +} diff --git a/firka/ios/HomeWidgetsExtension/Intents/GradesIntent.swift b/firka/ios/HomeWidgetsExtension/Intents/GradesIntent.swift new file mode 100644 index 00000000..6cb4b1fe --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Intents/GradesIntent.swift @@ -0,0 +1,10 @@ +import AppIntents +import WidgetKit + +struct GradesWidgetIntent: WidgetConfigurationIntent { + static var title: LocalizedStringResource = LocalizedStringResource("widget_grades_title", defaultValue: "Recent Grades") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("widget_grades_description", defaultValue: "Shows your recent grades")) + + @Parameter(title: LocalizedStringResource("param_style", defaultValue: "Style"), default: .liquidGlass) + var style: WidgetStyle? +} diff --git a/firka/ios/HomeWidgetsExtension/Intents/TimetableIntent.swift b/firka/ios/HomeWidgetsExtension/Intents/TimetableIntent.swift new file mode 100644 index 00000000..513f2fdd --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Intents/TimetableIntent.swift @@ -0,0 +1,45 @@ +import AppIntents +import WidgetKit + +enum TimetableDisplayMode: String, AppEnum { + case current = "current" + case next = "next" + + static var typeDisplayRepresentation: TypeDisplayRepresentation { + TypeDisplayRepresentation(name: LocalizedStringResource("display_mode_type", defaultValue: "Display Mode")) + } + + static var caseDisplayRepresentations: [TimetableDisplayMode: DisplayRepresentation] { + [ + .current: DisplayRepresentation(title: LocalizedStringResource("display_mode_current", defaultValue: "Current Lesson")), + .next: DisplayRepresentation(title: LocalizedStringResource("display_mode_next", defaultValue: "Next Lesson")) + ] + } +} + +enum WidgetStyle: String, AppEnum { + case liquidGlass = "liquid_glass" + case appTheme = "app_theme" + + static var typeDisplayRepresentation: TypeDisplayRepresentation { + TypeDisplayRepresentation(name: LocalizedStringResource("style_type", defaultValue: "Style")) + } + + static var caseDisplayRepresentations: [WidgetStyle: DisplayRepresentation] { + [ + .liquidGlass: DisplayRepresentation(title: LocalizedStringResource("style_liquid_glass", defaultValue: "Liquid Glass")), + .appTheme: DisplayRepresentation(title: LocalizedStringResource("style_app_theme", defaultValue: "App Theme")) + ] + } +} + +struct TimetableWidgetIntent: WidgetConfigurationIntent { + static var title: LocalizedStringResource = LocalizedStringResource("widget_timetable_title", defaultValue: "Timetable") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("widget_timetable_description", defaultValue: "Shows your daily timetable")) + + @Parameter(title: LocalizedStringResource("param_style", defaultValue: "Style"), default: .liquidGlass) + var style: WidgetStyle? + + @Parameter(title: LocalizedStringResource("param_display_mode_small", defaultValue: "Small Widget Display"), default: .current) + var displayMode: TimetableDisplayMode? +} diff --git a/firka/ios/HomeWidgetsExtension/LockScreen/AveragesLockScreenWidget.swift b/firka/ios/HomeWidgetsExtension/LockScreen/AveragesLockScreenWidget.swift new file mode 100644 index 00000000..2a364315 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/LockScreen/AveragesLockScreenWidget.swift @@ -0,0 +1,180 @@ +import WidgetKit +import SwiftUI + +// MARK: - Lock Screen Averages Widget + +struct AveragesLockScreenWidget: Widget { + let kind: String = "AveragesLockScreenWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: AveragesWidgetIntent.self, + provider: AveragesProvider() + ) { entry in + AveragesLockScreenView(entry: entry) + } + .configurationDisplayName(LocalizedStringResource("widget_averages_title", defaultValue: "Averages")) + .description(LocalizedStringResource("widget_averages_lockscreen_description", defaultValue: "Shows your averages on lock screen")) + .supportedFamilies([.accessoryCircular, .accessoryRectangular]) + } +} + +// MARK: - Lock Screen View + +struct AveragesLockScreenView: View { + @Environment(\.widgetFamily) var family + let entry: AveragesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var body: some View { + Group { + switch family { + case .accessoryInline: + AveragesInlineView(entry: entry, localization: localization) + case .accessoryCircular: + AveragesCircularView(entry: entry, localization: localization) + case .accessoryRectangular: + AveragesRectangularView(entry: entry, localization: localization) + default: + Text("--") + } + } + .containerBackground(.clear, for: .widget) + } +} + +// MARK: - Inline View + +struct AveragesInlineView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + + var body: some View { + if let overall = entry.overallAverage { + Text("\(localization.string("average_short")): \(String(format: "%.2f", overall))") + } else if let first = entry.subjectAverages.first { + Text("\(first.name): \(String(format: "%.2f", first.average))") + } else { + Text(localization.string("no_averages")) + } + } +} + +// MARK: - Circular View + +struct AveragesCircularView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + + var body: some View { + if let overall = entry.overallAverage { + Gauge(value: overall, in: 1...5) { + Text("") + } currentValueLabel: { + Text(String(format: "%.1f", overall)) + .font(.system(.title2, design: .rounded, weight: .bold)) + .foregroundStyle(averageColor(overall)) + } + .gaugeStyle(.accessoryCircularCapacity) + .tint(averageColor(overall)) + } else if let first = entry.subjectAverages.first { + ZStack { + AccessoryWidgetBackground() + VStack(spacing: 0) { + Text(String(format: "%.1f", first.average)) + .font(.system(.title2, design: .rounded, weight: .bold)) + .foregroundStyle(averageColor(first.average)) + Text(String(first.name.prefix(4))) + .font(.system(.caption2)) + .foregroundStyle(.secondary) + } + } + } else { + ZStack { + AccessoryWidgetBackground() + Image(systemName: "chart.bar") + .font(.title2) + } + } + } + + private func averageColor(_ value: Double) -> Color { + switch value { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} + +// MARK: - Rectangular View + +struct AveragesRectangularView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + + var body: some View { + if let overall = entry.overallAverage { + HStack(spacing: 8) { + Text(String(format: "%.2f", overall)) + .font(.system(.title, design: .rounded, weight: .bold)) + .foregroundStyle(averageColor(overall)) + .fixedSize() + + VStack(alignment: .leading, spacing: 0) { + Text(localization.string("average_short")) + .font(.caption) + .foregroundStyle(.secondary) + Text(localization.string("subjects_count", entry.subjectAverages.count)) + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if !entry.subjectAverages.isEmpty { + VStack(alignment: .leading, spacing: 2) { + Text(localization.string("subject_averages_title")) + .font(.caption) + .foregroundStyle(.secondary) + HStack(spacing: 8) { + ForEach(entry.subjectAverages.prefix(3), id: \.uid) { subject in + VStack(alignment: .leading, spacing: 0) { + Text(String(format: "%.1f", subject.average)) + .font(.system(.subheadline, design: .rounded, weight: .bold)) + .foregroundStyle(averageColor(subject.average)) + Text(String(subject.name.prefix(5))) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + Spacer() + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + VStack(alignment: .leading) { + Label(localization.string("no_averages"), systemImage: "chart.bar") + .font(.headline) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private func averageColor(_ value: Double) -> Color { + switch value { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/LockScreen/GradesLockScreenWidget.swift b/firka/ios/HomeWidgetsExtension/LockScreen/GradesLockScreenWidget.swift new file mode 100644 index 00000000..8081a12d --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/LockScreen/GradesLockScreenWidget.swift @@ -0,0 +1,232 @@ +import WidgetKit +import SwiftUI + +// MARK: - Lock Screen Grades Widget + +struct GradesLockScreenWidget: Widget { + let kind: String = "GradesLockScreenWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: GradesWidgetIntent.self, + provider: GradesProvider() + ) { entry in + GradesLockScreenView(entry: entry) + } + .configurationDisplayName(LocalizedStringResource("widget_grades_title", defaultValue: "Recent Grades")) + .description(LocalizedStringResource("widget_grades_lockscreen_description", defaultValue: "Shows recent grades on lock screen")) + .supportedFamilies([.accessoryCircular, .accessoryRectangular]) + } +} + +// MARK: - Lock Screen View + +struct GradesLockScreenView: View { + @Environment(\.widgetFamily) var family + let entry: GradesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var body: some View { + Group { + switch family { + case .accessoryInline: + GradesInlineView(entry: entry, localization: localization) + case .accessoryCircular: + GradesCircularView(entry: entry, localization: localization) + case .accessoryRectangular: + GradesRectangularView(entry: entry, localization: localization) + default: + Text("--") + } + } + .containerBackground(.clear, for: .widget) + } +} + +// MARK: - Inline View + +struct GradesInlineView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var todayGrades: [WidgetGrade] { + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + return entry.grades.filter { calendar.startOfDay(for: $0.recordDate) == today } + } + + var body: some View { + if let latest = entry.grades.first { + if todayGrades.count > 0 { + Text(localization.string("today_new_grades", todayGrades.count)) + } else { + Text("\(localization.string("latest")): \(latest.displayValue) \(latest.subject.name)") + } + } else { + Text(localization.string("no_grades")) + } + } +} + +// MARK: - Circular View + +struct GradesCircularView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var todayGradesCount: Int { + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + return entry.grades.filter { calendar.startOfDay(for: $0.recordDate) == today }.count + } + + var body: some View { + if let latest = entry.grades.first { + ZStack { + AccessoryWidgetBackground() + Text(latest.displayValue) + .font(.system(.title, design: .rounded, weight: .bold)) + .foregroundStyle(gradeColor(latest.numericValue)) + } + } else { + ZStack { + AccessoryWidgetBackground() + Image(systemName: "graduationcap") + .font(.title2) + } + } + } + + private func gradeColor(_ value: Int?) -> Color { + guard let value = value else { return .primary } + switch value { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + case 1: return .red + default: return .primary + } + } +} + +// MARK: - Rectangular View + +struct GradesRectangularView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var todayGrades: [WidgetGrade] { + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + return entry.grades.filter { calendar.startOfDay(for: $0.recordDate) == today } + } + + var body: some View { + if !entry.grades.isEmpty { + VStack(alignment: .leading, spacing: 2) { + if todayGrades.count > 0 { + HStack { + Text(localization.string("today_grades")) + .font(.caption) + .foregroundStyle(.secondary) + Spacer() + Text(localization.string("pieces", todayGrades.count)) + .font(.caption) + .foregroundStyle(.secondary) + } + HStack(spacing: 4) { + ForEach(todayGrades.prefix(5), id: \.uid) { grade in + GradeBadge(grade: grade) + } + if todayGrades.count > 5 { + Text("+\(todayGrades.count - 5)") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + } + } else if let latest = entry.grades.first { + HStack { + Text(localization.string("latest_grade")) + .font(.caption) + .foregroundStyle(.secondary) + Spacer() + Text(formatDate(latest.recordDate)) + .font(.caption) + .foregroundStyle(.secondary) + } + HStack { + Text(latest.displayValue) + .font(.title2) + .fontWeight(.bold) + .foregroundStyle(gradeColor(latest.numericValue)) + Text(latest.subject.name) + .font(.subheadline) + .lineLimit(1) + Spacer() + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + VStack(alignment: .leading) { + Label(localization.string("no_grades"), systemImage: "graduationcap") + .font(.headline) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private func formatDate(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "MMM d." + return formatter.string(from: date) + } + + private func gradeColor(_ value: Int?) -> Color { + guard let value = value else { return .primary } + switch value { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + case 1: return .red + default: return .primary + } + } +} + +// MARK: - Grade Badge + +struct GradeBadge: View { + let grade: WidgetGrade + + var body: some View { + Text(grade.displayValue) + .font(.system(.caption, design: .rounded, weight: .bold)) + .foregroundStyle(gradeColor(grade.numericValue)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 4) + .fill(gradeColor(grade.numericValue).opacity(0.2)) + ) + } + + private func gradeColor(_ value: Int?) -> Color { + guard let value = value else { return .primary } + switch value { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + case 1: return .red + default: return .primary + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/LockScreen/InlineWidgets.swift b/firka/ios/HomeWidgetsExtension/LockScreen/InlineWidgets.swift new file mode 100644 index 00000000..8843cd9b --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/LockScreen/InlineWidgets.swift @@ -0,0 +1,154 @@ +import WidgetKit +import SwiftUI + +// MARK: - Timetable Inline Widget + +struct TimetableInlineWidget: Widget { + let kind: String = "TimetableInlineWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: TimetableWidgetIntent.self, + provider: TimetableProvider() + ) { entry in + TimetableInlineWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_timetable_title", defaultValue: "Timetable")) + .description(LocalizedStringResource("widget_timetable_inline_description", defaultValue: "Shows next lesson above the clock")) + .supportedFamilies([.accessoryInline]) + } +} + +struct TimetableInlineWidgetView: View { + let entry: TimetableEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.data?.locale ?? "hu") + } + + var body: some View { + if entry.state == .onBreak, let breakInfo = entry.breakInfo { + Text(localization.string(breakInfo.nameKey)) + } else if let current = entry.currentLesson { + let remaining = minutesRemaining(until: current.end) + Text("\(current.subject.name) · \(remaining) \(localization.string("minutes_abbrev"))") + } else if entry.isNextSchoolDay { + if let first = entry.lessons.first { + let dateStr = WidgetLocalization.formatShortDate(entry.nextSchoolDayDateString, locale: localization.locale) + let lessonNum = first.lessonNumber ?? 1 + Text("\(dateStr): \(lessonNum). \(first.subject.name)") + } else { + Text(localization.string("no_lessons_ahead")) + } + } else if entry.isNextDay { + if let first = entry.lessons.first { + let lessonNum = first.lessonNumber ?? 1 + Text("\(localization.string("tomorrow")): \(lessonNum). \(first.subject.name)") + } else { + Text(localization.string("no_lessons_ahead")) + } + } else if let next = entry.nextLesson { + let until = minutesRemaining(until: next.start) + if until <= 0 { + Text("→ \(next.subject.name)") + } else if until > 60 { + let hours = until / 60 + Text("→ \(next.subject.name) · \(hours) \(localization.string("hours_abbrev"))") + } else { + Text("→ \(next.subject.name) · \(until) \(localization.string("minutes_abbrev"))") + } + } else { + Text(localization.string("no_lessons_ahead")) + } + } + + private func minutesRemaining(until date: Date) -> Int { + let diff = date.timeIntervalSince(entry.date) + return max(0, Int(ceil(diff / 60))) + } +} + +// MARK: - Grades Inline Widget + +struct GradesInlineWidget: Widget { + let kind: String = "GradesInlineWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: GradesWidgetIntent.self, + provider: GradesProvider() + ) { entry in + GradesInlineWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_grades_title", defaultValue: "Grades")) + .description(LocalizedStringResource("widget_grades_inline_description", defaultValue: "Shows recent grades above the clock")) + .supportedFamilies([.accessoryInline]) + } +} + +struct GradesInlineWidgetView: View { + let entry: GradesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var todayGrades: [WidgetGrade] { + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + return entry.grades.filter { calendar.startOfDay(for: $0.recordDate) == today } + } + + var body: some View { + if todayGrades.count > 0 { + Text("📝 \(localization.string("today_new_grades", todayGrades.count))") + } else if let latest = entry.grades.first { + // No grades today - show latest + Text("\(localization.string("latest")): \(latest.displayValue) \(latest.subject.name)") + } else { + Text(localization.string("no_grades")) + } + } +} + +// MARK: - Averages Inline Widget + +struct AveragesInlineWidget: Widget { + let kind: String = "AveragesInlineWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: AveragesWidgetIntent.self, + provider: AveragesProvider() + ) { entry in + AveragesInlineWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_averages_title", defaultValue: "Averages")) + .description(LocalizedStringResource("widget_averages_inline_description", defaultValue: "Shows your average above the clock")) + .supportedFamilies([.accessoryInline]) + } +} + +struct AveragesInlineWidgetView: View { + let entry: AveragesEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.locale) + } + + var body: some View { + if let overall = entry.overallAverage { + Text("\(localization.string("average_short")): \(String(format: "%.2f", overall)) · \(entry.subjectAverages.count) \(localization.string("subject_short"))") + } else if let first = entry.subjectAverages.first { + Text("\(first.name): \(String(format: "%.2f", first.average))") + } else { + Text(localization.string("no_averages")) + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/LockScreen/TimetableLockScreenWidget.swift b/firka/ios/HomeWidgetsExtension/LockScreen/TimetableLockScreenWidget.swift new file mode 100644 index 00000000..e389492e --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/LockScreen/TimetableLockScreenWidget.swift @@ -0,0 +1,301 @@ +import WidgetKit +import SwiftUI + +// MARK: - Lock Screen Timetable Widget + +struct TimetableLockScreenWidget: Widget { + let kind: String = "TimetableLockScreenWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: TimetableWidgetIntent.self, + provider: TimetableProvider() + ) { entry in + TimetableLockScreenView(entry: entry) + } + .configurationDisplayName(LocalizedStringResource("widget_timetable_title", defaultValue: "Timetable")) + .description(LocalizedStringResource("widget_timetable_lockscreen_description", defaultValue: "Shows current lesson on lock screen")) + .supportedFamilies([.accessoryCircular, .accessoryRectangular]) + } +} + +// MARK: - Lock Screen View + +struct TimetableLockScreenView: View { + @Environment(\.widgetFamily) var family + let entry: TimetableEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.data?.locale ?? "hu") + } + + var body: some View { + Group { + switch family { + case .accessoryInline: + TimetableInlineView(entry: entry, localization: localization) + case .accessoryCircular: + TimetableCircularView(entry: entry, localization: localization) + case .accessoryRectangular: + TimetableRectangularView(entry: entry, localization: localization) + default: + Text("--") + } + } + .containerBackground(.clear, for: .widget) + } +} + +// MARK: - Inline View (single line next to date) + +struct TimetableInlineView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + + var body: some View { + if entry.state == .onBreak, let breakInfo = entry.breakInfo { + Text("🏖️ \(localization.string(breakInfo.nameKey))") + } else if let current = entry.currentLesson { + let remaining = minutesRemaining(until: current.end) + Text("\(current.subject.name) - \(remaining) \(localization.string("minutes_short"))") + } else if entry.isNextSchoolDay { + if let first = entry.lessons.first { + let dateStr = WidgetLocalization.formatShortDate(entry.nextSchoolDayDateString, locale: localization.locale) + let lessonNum = first.lessonNumber ?? 1 + Text("\(dateStr): \(lessonNum). \(first.subject.name)") + } else { + Text(localization.string("no_lessons_ahead")) + } + } else if entry.isNextDay { + if let first = entry.lessons.first { + let lessonNum = first.lessonNumber ?? 1 + Text("\(localization.string("tomorrow")): \(lessonNum). \(first.subject.name)") + } else { + Text(localization.string("no_lessons_ahead")) + } + } else if let next = entry.nextLesson { + let until = minutesRemaining(until: next.start) + if until <= 0 { + Text("\(localization.string("next")): \(next.subject.name)") + } else if until > 60 { + let hours = until / 60 + Text("\(next.subject.name) \(localization.string("in_hours", hours))") + } else { + Text("\(next.subject.name) \(localization.string("in_minutes", until))") + } + } else { + Text(localization.string("no_lessons_ahead")) + } + } + + private func minutesRemaining(until date: Date) -> Int { + let diff = date.timeIntervalSince(entry.date) + return max(0, Int(ceil(diff / 60))) + } +} + +// MARK: - Circular View (small circle) + +struct TimetableCircularView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + + var body: some View { + if entry.state == .onBreak { + ZStack { + AccessoryWidgetBackground() + Image(systemName: "sun.max.fill") + .font(.title2) + } + } else if let current = entry.currentLesson { + let remaining = minutesRemaining(until: current.end) + Gauge(value: Double(remaining), in: 0...45) { + Text("") + } currentValueLabel: { + Text("\(remaining)") + .font(.system(.title2, design: .rounded, weight: .bold)) + } + .gaugeStyle(.accessoryCircularCapacity) + } else if entry.isNextSchoolDay || entry.isNextDay { + let lessonCount = entry.lessons.count + if lessonCount > 0 { + ZStack { + AccessoryWidgetBackground() + VStack(spacing: 0) { + Text("\(lessonCount)") + .font(.system(.title2, design: .rounded, weight: .bold)) + Text(localization.string("lesson_short")) + .font(.system(.caption2)) + .foregroundStyle(.secondary) + } + } + } else { + ZStack { + AccessoryWidgetBackground() + Image(systemName: "calendar.badge.checkmark") + .font(.title2) + } + } + } else if let next = entry.nextLesson { + let until = minutesRemaining(until: next.start) + ZStack { + AccessoryWidgetBackground() + VStack(spacing: 0) { + if until > 60 { + let hours = until / 60 + Text("\(hours)") + .font(.system(.title2, design: .rounded, weight: .bold)) + Text(localization.string("hours_abbrev")) + .font(.system(.caption2)) + .foregroundStyle(.secondary) + } else { + Text("\(until)") + .font(.system(.title2, design: .rounded, weight: .bold)) + Text(localization.string("minutes_abbrev")) + .font(.system(.caption2)) + .foregroundStyle(.secondary) + } + } + } + } else if let lesson = entry.lessons.first, let lessonNum = lesson.lessonNumber { + ZStack { + AccessoryWidgetBackground() + VStack(spacing: 0) { + Text("\(lessonNum).") + .font(.system(.title2, design: .rounded, weight: .bold)) + Text(localization.string("lesson_short")) + .font(.system(.caption2)) + .foregroundStyle(.secondary) + } + } + } else { + ZStack { + AccessoryWidgetBackground() + Image(systemName: "calendar.badge.checkmark") + .font(.title2) + } + } + } + + private func minutesRemaining(until date: Date) -> Int { + let diff = date.timeIntervalSince(entry.date) + return max(0, Int(ceil(diff / 60))) + } +} + +// MARK: - Rectangular View (medium rectangle) + +struct TimetableRectangularView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + + var body: some View { + if entry.state == .onBreak, let breakInfo = entry.breakInfo { + VStack(alignment: .leading, spacing: 2) { + Label(localization.string(breakInfo.nameKey), systemImage: "sun.max.fill") + .font(.headline) + Text(localization.string("until") + " " + formatDate(breakInfo.endDate)) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if let current = entry.currentLesson { + let remaining = minutesRemaining(until: current.end) + let lessonNum = current.lessonNumber ?? 0 + VStack(alignment: .leading, spacing: 2) { + HStack { + Text("\(lessonNum). \(current.subject.name)") + .font(.headline) + .lineLimit(1) + Spacer() + Text("\(remaining)'") + .font(.subheadline) + .foregroundStyle(.secondary) + } + HStack { + if let room = current.roomName { + Label(room, systemImage: "mappin") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Text(formatTimeRange(current.start, current.end)) + .font(.caption) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if let next = entry.nextLesson { + let until = minutesRemaining(until: next.start) + let isFutureDay = entry.isNextDay || entry.isNextSchoolDay + VStack(alignment: .leading, spacing: 2) { + HStack { + if entry.isNextSchoolDay { + let dateStr = WidgetLocalization.formatShortDate(entry.nextSchoolDayDateString, locale: localization.locale) + Text(dateStr) + .font(.caption) + .foregroundStyle(.secondary) + } else { + Text(entry.isNextDay ? localization.string("tomorrow") : localization.string("next")) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if until > 0 && !isFutureDay { + if until > 60 { + Text(localization.string("in_hours", until / 60)) + .font(.caption) + .foregroundStyle(.secondary) + } else { + Text(localization.string("in_minutes", until)) + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + Text("\(next.lessonNumber ?? 0). \(next.subject.name)") + .font(.headline) + .lineLimit(1) + HStack { + if let room = next.roomName { + Label(room, systemImage: "mappin") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + Text(formatTimeRange(next.start, next.end)) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + VStack(alignment: .leading) { + Label(localization.string("no_lessons"), systemImage: "checkmark.circle") + .font(.headline) + Text(localization.string("no_more_lessons_today")) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private func minutesRemaining(until date: Date) -> Int { + let diff = date.timeIntervalSince(entry.date) + return max(0, Int(ceil(diff / 60))) + } + + private func formatTimeRange(_ start: Date, _ end: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return "\(formatter.string(from: start)) - \(formatter.string(from: end))" + } + + private func formatDate(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "MMM d." + return formatter.string(from: date) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Providers/AveragesProvider.swift b/firka/ios/HomeWidgetsExtension/Providers/AveragesProvider.swift new file mode 100644 index 00000000..5f92eedd --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Providers/AveragesProvider.swift @@ -0,0 +1,60 @@ +import WidgetKit +import SwiftUI + +struct AveragesEntry: TimelineEntry { + let date: Date + let configuration: AveragesWidgetIntent + let overallAverage: Double? + let subjectAverages: [SubjectAverage] + let locale: String + let isFiltered: Bool +} + +struct AveragesProvider: AppIntentTimelineProvider { + typealias Entry = AveragesEntry + typealias Intent = AveragesWidgetIntent + + func placeholder(in context: Context) -> AveragesEntry { + AveragesEntry( + date: Date(), + configuration: AveragesWidgetIntent(), + overallAverage: nil, + subjectAverages: [], + locale: "hu", + isFiltered: false + ) + } + + func snapshot(for configuration: AveragesWidgetIntent, in context: Context) async -> AveragesEntry { + createEntry(for: configuration) + } + + func timeline(for configuration: AveragesWidgetIntent, in context: Context) async -> Timeline { + let entry = createEntry(for: configuration) + + // Refresh every 30 minutes + let refreshDate = Date().addingTimeInterval(30 * 60) + return Timeline(entries: [entry], policy: .after(refreshDate)) + } + + private func createEntry(for configuration: AveragesWidgetIntent) -> AveragesEntry { + let data = WidgetData.load() + + var subjectAverages = data?.averages.subjects ?? [] + let isFiltered = configuration.selectedSubjects?.isEmpty == false + + if isFiltered { + let selectedIds = Set(configuration.selectedSubjects!.map { $0.id }) + subjectAverages = subjectAverages.filter { selectedIds.contains($0.uid) } + } + + return AveragesEntry( + date: Date(), + configuration: configuration, + overallAverage: data?.averages.overall, + subjectAverages: subjectAverages, + locale: data?.locale ?? "hu", + isFiltered: isFiltered + ) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Providers/GradesProvider.swift b/firka/ios/HomeWidgetsExtension/Providers/GradesProvider.swift new file mode 100644 index 00000000..3b81dd8a --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Providers/GradesProvider.swift @@ -0,0 +1,41 @@ +import WidgetKit +import SwiftUI + +struct GradesEntry: TimelineEntry { + let date: Date + let configuration: GradesWidgetIntent + let grades: [WidgetGrade] + let locale: String +} + +struct GradesProvider: AppIntentTimelineProvider { + typealias Entry = GradesEntry + typealias Intent = GradesWidgetIntent + + func placeholder(in context: Context) -> GradesEntry { + GradesEntry(date: Date(), configuration: GradesWidgetIntent(), grades: [], locale: "hu") + } + + func snapshot(for configuration: GradesWidgetIntent, in context: Context) async -> GradesEntry { + let data = WidgetData.load() + return GradesEntry( + date: Date(), + configuration: configuration, + grades: data?.grades ?? [], + locale: data?.locale ?? "hu" + ) + } + + func timeline(for configuration: GradesWidgetIntent, in context: Context) async -> Timeline { + let data = WidgetData.load() + let entry = GradesEntry( + date: Date(), + configuration: configuration, + grades: data?.grades ?? [], + locale: data?.locale ?? "hu" + ) + + let refreshDate = Date().addingTimeInterval(30 * 60) + return Timeline(entries: [entry], policy: .after(refreshDate)) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Providers/TimetableProvider.swift b/firka/ios/HomeWidgetsExtension/Providers/TimetableProvider.swift new file mode 100644 index 00000000..90018a14 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Providers/TimetableProvider.swift @@ -0,0 +1,384 @@ +import WidgetKit +import SwiftUI + +struct TimetableEntry: TimelineEntry { + let date: Date + let configuration: TimetableWidgetIntent + let data: WidgetData? + let lessons: [WidgetLesson] + let currentLesson: WidgetLesson? + let nextLesson: WidgetLesson? + let isNextDay: Bool + let isNextSchoolDay: Bool + let nextSchoolDayDateString: String? + let breakInfo: BreakInfo? + let state: TimetableState + let debugInfo: String +} + +enum TimetableState { + case normal + case noMoreLessons + case onBreak + case loginRequired + case unavailable +} + +struct TimetableProvider: AppIntentTimelineProvider { + typealias Entry = TimetableEntry + typealias Intent = TimetableWidgetIntent + + private struct LessonCandidate { + let lessons: [WidgetLesson] + let day: Date + } + + private static let dateFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd" + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone.current + return formatter + }() + + private static let isoFormatterWithFractional: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + }() + + private static let isoFormatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime] + return formatter + }() + + private func parseNextSchoolDayDate(_ dateString: String?) -> Date? { + guard let dateString = dateString else { return nil } + if let date = Self.isoFormatterWithFractional.date(from: dateString) { + return date + } + if let date = Self.isoFormatter.date(from: dateString) { + return date + } + if let date = Self.dateFormatter.date(from: dateString) { + return date + } + + let trimmed = String(dateString.prefix(10)) + return Self.dateFormatter.date(from: trimmed) + } + + private func startOfDay(for lessons: [WidgetLesson], calendar: Calendar) -> Date? { + guard let first = lessons.first else { return nil } + return calendar.startOfDay(for: first.start) + } + + private func nextSchoolDay(from data: WidgetData, calendar: Calendar) -> Date? { + if let firstNextLesson = data.timetable.nextSchoolDay?.first { + return calendar.startOfDay(for: firstNextLesson.start) + } + + if let parsedDate = parseNextSchoolDayDate(data.timetable.nextSchoolDayDate) { + return calendar.startOfDay(for: parsedDate) + } + + return nil + } + + func placeholder(in context: Context) -> TimetableEntry { + TimetableEntry( + date: Date(), + configuration: TimetableWidgetIntent(), + data: nil, + lessons: [], + currentLesson: nil, + nextLesson: nil, + isNextDay: false, + isNextSchoolDay: false, + nextSchoolDayDateString: nil, + breakInfo: nil, + state: .normal, + debugInfo: "placeholder" + ) + } + + func snapshot(for configuration: TimetableWidgetIntent, in context: Context) async -> TimetableEntry { + createEntry(for: configuration, date: Date()) + } + + func timeline(for configuration: TimetableWidgetIntent, in context: Context) async -> Timeline { + var entries: [TimetableEntry] = [] + let now = Date() + let calendar = Calendar.current + + let data = WidgetData.load() + + // If on break, create single entry + if let breakInfo = data?.timetable.currentBreak { + let entry = TimetableEntry( + date: now, + configuration: configuration, + data: data, + lessons: [], + currentLesson: nil, + nextLesson: nil, + isNextDay: false, + isNextSchoolDay: false, + nextSchoolDayDateString: nil, + breakInfo: breakInfo, + state: .onBreak, + debugInfo: WidgetData.lastError + ) + entries.append(entry) + return Timeline(entries: entries, policy: .after(calendar.startOfDay(for: now.addingTimeInterval(86400)))) + } + + let todayLessons = data?.timetable.today ?? [] + + entries.append(createEntry(for: configuration, date: now)) + + let currentLesson = todayLessons.first { now >= $0.start && now <= $0.end } + let nextLesson = todayLessons.first { $0.start > now } + + let isLockScreenWidget = context.family == .accessoryInline || + context.family == .accessoryCircular || + context.family == .accessoryRectangular + + if isLockScreenWidget { + var minuteEntries: [Date] = [] + + if let current = currentLesson { + var time = now.addingTimeInterval(60) + while time <= current.end && minuteEntries.count < 60 { + minuteEntries.append(time) + time = time.addingTimeInterval(60) + } + minuteEntries.append(current.end.addingTimeInterval(1)) + } + + if let next = nextLesson { + let minutesUntilNext = next.start.timeIntervalSince(now) / 60 + + if minutesUntilNext <= 60 { + var time = currentLesson?.end.addingTimeInterval(60) ?? now.addingTimeInterval(60) + while time < next.start && minuteEntries.count < 120 { + minuteEntries.append(time) + time = time.addingTimeInterval(60) + } + } else { + let sixtyMinutesBefore = next.start.addingTimeInterval(-60 * 60) + if sixtyMinutesBefore > now { + minuteEntries.append(sixtyMinutesBefore) + } + } + minuteEntries.append(next.start) + + var nextLessonTime = next.start.addingTimeInterval(60) + while nextLessonTime <= next.end && minuteEntries.count < 180 { + minuteEntries.append(nextLessonTime) + nextLessonTime = nextLessonTime.addingTimeInterval(60) + } + minuteEntries.append(next.end.addingTimeInterval(1)) + } + + for time in minuteEntries { + if time > now { + entries.append(createEntry(for: configuration, date: time)) + } + } + } + + for lesson in todayLessons { + if lesson.start > now { + entries.append(createEntry(for: configuration, date: lesson.start)) + } + if lesson.end > now { + entries.append(createEntry(for: configuration, date: lesson.end.addingTimeInterval(1))) + } + } + + let tomorrowLessons = data?.timetable.tomorrow ?? [] + for lesson in tomorrowLessons { + if lesson.start > now { + entries.append(createEntry(for: configuration, date: lesson.start)) + } + if lesson.end > now { + entries.append(createEntry(for: configuration, date: lesson.end.addingTimeInterval(1))) + } + } + + let nextSchoolDayLessons = data?.timetable.nextSchoolDay ?? [] + for lesson in nextSchoolDayLessons { + if lesson.start > now { + entries.append(createEntry(for: configuration, date: lesson.start)) + } + if lesson.end > now { + entries.append(createEntry(for: configuration, date: lesson.end.addingTimeInterval(1))) + } + } + + let midnight = calendar.startOfDay(for: now.addingTimeInterval(86400)) + entries.append(createEntry(for: configuration, date: midnight)) + + if let data = data, + let nextSchoolDay = nextSchoolDay(from: data, calendar: calendar) { + let dayBeforeNextSchoolDay = calendar.date(byAdding: .day, value: -1, to: nextSchoolDay)! + + if dayBeforeNextSchoolDay > now { + entries.append(createEntry(for: configuration, date: dayBeforeNextSchoolDay)) + } + + if nextSchoolDay > now { + entries.append(createEntry(for: configuration, date: nextSchoolDay)) + } + } + + let uniqueDates = Set(entries.map { $0.date }) + entries = uniqueDates.map { date in + entries.first { $0.date == date }! + } + entries.sort { $0.date < $1.date } + + if isLockScreenWidget { + var refreshDate: Date + if let current = currentLesson { + refreshDate = current.end.addingTimeInterval(1) + } else if let next = nextLesson { + refreshDate = next.end.addingTimeInterval(1) + } else { + refreshDate = midnight + } + return Timeline(entries: entries, policy: .after(refreshDate)) + } + + return Timeline(entries: entries, policy: .atEnd) + } + + private func createEntry(for configuration: TimetableWidgetIntent, date: Date) -> TimetableEntry { + let data = WidgetData.load() + let calendar = Calendar.current + + guard let data = data else { + return TimetableEntry( + date: date, + configuration: configuration, + data: nil, + lessons: [], + currentLesson: nil, + nextLesson: nil, + isNextDay: false, + isNextSchoolDay: false, + nextSchoolDayDateString: nil, + breakInfo: nil, + state: .loginRequired, + debugInfo: WidgetData.lastError + ) + } + + if let breakInfo = data.timetable.currentBreak { + return TimetableEntry( + date: date, + configuration: configuration, + data: data, + lessons: [], + currentLesson: nil, + nextLesson: nil, + isNextDay: false, + isNextSchoolDay: false, + nextSchoolDayDateString: nil, + breakInfo: breakInfo, + state: .onBreak, + debugInfo: WidgetData.lastError + ) + } + + let entryDay = calendar.startOfDay(for: date) + let tomorrowOfEntryDay = calendar.date(byAdding: .day, value: 1, to: entryDay)! + + let todayLessons = data.timetable.today + let tomorrowLessons = data.timetable.tomorrow + let nextSchoolDayLessons = data.timetable.nextSchoolDay ?? [] + + var candidates: [LessonCandidate] = [] + + if let todayDay = startOfDay(for: todayLessons, calendar: calendar), !todayLessons.isEmpty { + candidates.append(LessonCandidate(lessons: todayLessons, day: todayDay)) + } + + if let tomorrowDay = startOfDay(for: tomorrowLessons, calendar: calendar), !tomorrowLessons.isEmpty { + candidates.append(LessonCandidate(lessons: tomorrowLessons, day: tomorrowDay)) + } + + if !nextSchoolDayLessons.isEmpty, + let resolvedNextSchoolDay = nextSchoolDay(from: data, calendar: calendar) + ?? startOfDay(for: nextSchoolDayLessons, calendar: calendar) { + candidates.append(LessonCandidate(lessons: nextSchoolDayLessons, day: resolvedNextSchoolDay)) + } + + candidates.sort { $0.day < $1.day } + + // Pick the closest candidate that still has lessons ahead relative to this entry date. + let selectedCandidate = candidates.first { candidate in + if candidate.day > entryDay { + return true + } + + if candidate.day == entryDay, let lastLesson = candidate.lessons.last { + return date <= lastLesson.end + } + + return false + } + + guard let selectedCandidate = selectedCandidate else { + let hadLessonsTodayButFinished = candidates.contains { candidate in + guard candidate.day == entryDay, let lastLesson = candidate.lessons.last else { return false } + return date > lastLesson.end + } + + return TimetableEntry( + date: date, + configuration: configuration, + data: data, + lessons: [], + currentLesson: nil, + nextLesson: nil, + isNextDay: false, + isNextSchoolDay: false, + nextSchoolDayDateString: nil, + breakInfo: nil, + state: hadLessonsTodayButFinished ? .noMoreLessons : .unavailable, + debugInfo: WidgetData.lastError + ) + } + + let lessons = selectedCandidate.lessons + let isToday = selectedCandidate.day == entryDay + let isNextDay = selectedCandidate.day == tomorrowOfEntryDay + let isNextSchoolDay = !isToday && !isNextDay + let nextSchoolDayDateString = isNextSchoolDay + ? (data.timetable.nextSchoolDayDate ?? Self.dateFormatter.string(from: selectedCandidate.day)) + : nil + + let currentLesson = lessons.first { lesson in + return date >= lesson.start && date <= lesson.end + } + let nextLesson = lessons.first { $0.start > date } + + return TimetableEntry( + date: date, + configuration: configuration, + data: data, + lessons: lessons, + currentLesson: currentLesson, + nextLesson: nextLesson, + isNextDay: isNextDay, + isNextSchoolDay: isNextSchoolDay, + nextSchoolDayDateString: nextSchoolDayDateString, + breakInfo: nil, + state: .normal, + debugInfo: WidgetData.lastError + ) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/AverageEntity.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/AverageEntity.swift new file mode 100644 index 00000000..390dbf9f --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/AverageEntity.swift @@ -0,0 +1,55 @@ +import AppIntents +import Foundation + +@available(iOS 16.0, *) +struct AverageEntity: AppEntity { + static var typeDisplayRepresentation = TypeDisplayRepresentation(name: LocalizedStringResource("entity_average", defaultValue: "Average")) + static var defaultQuery = AverageEntityQuery() + + var id: String + + @Property(title: LocalizedStringResource("entity_prop_subject", defaultValue: "Subject")) + var subjectName: String + + @Property(title: LocalizedStringResource("entity_prop_average", defaultValue: "Average")) + var average: Double + + @Property(title: LocalizedStringResource("entity_prop_grade_count", defaultValue: "Grade count")) + var gradeCount: Int + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation( + title: "\(subjectName)", + subtitle: "\(String(format: "%.2f", average)) (\(gradeCount))" + ) + } + + init(from avg: SubjectAverage) { + self.id = avg.uid + self.subjectName = avg.name + self.average = avg.average + self.gradeCount = avg.gradeCount + } + + init(id: String, subjectName: String, average: Double, gradeCount: Int) { + self.id = id + self.subjectName = subjectName + self.average = average + self.gradeCount = gradeCount + } +} + +@available(iOS 16.0, *) +struct AverageEntityQuery: EntityQuery { + func entities(for identifiers: [String]) async throws -> [AverageEntity] { + guard let data = WidgetData.load() else { return [] } + return data.averages.subjects + .filter { identifiers.contains($0.uid) } + .map { AverageEntity(from: $0) } + } + + func suggestedEntities() async throws -> [AverageEntity] { + guard let data = WidgetData.load() else { return [] } + return data.averages.subjects.map { AverageEntity(from: $0) } + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/GradeEntity.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/GradeEntity.swift new file mode 100644 index 00000000..b189a16e --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/GradeEntity.swift @@ -0,0 +1,80 @@ +import AppIntents +import Foundation + +@available(iOS 16.0, *) +struct GradeEntity: AppEntity { + static var typeDisplayRepresentation = TypeDisplayRepresentation(name: LocalizedStringResource("entity_grade", defaultValue: "Grade")) + static var defaultQuery = GradeEntityQuery() + + var id: String + + @Property(title: LocalizedStringResource("entity_prop_subject", defaultValue: "Subject")) + var subject: String + + @Property(title: LocalizedStringResource("entity_prop_value", defaultValue: "Value")) + var numericValue: Int + + @Property(title: LocalizedStringResource("entity_prop_grade", defaultValue: "Grade")) + var strValue: String + + @Property(title: LocalizedStringResource("entity_prop_topic", defaultValue: "Topic")) + var topic: String + + @Property(title: LocalizedStringResource("entity_prop_type", defaultValue: "Type")) + var type: String + + @Property(title: LocalizedStringResource("entity_prop_teacher", defaultValue: "Teacher")) + var teacher: String + + @Property(title: LocalizedStringResource("entity_prop_date", defaultValue: "Date")) + var date: Date + + @Property(title: LocalizedStringResource("entity_prop_weight", defaultValue: "Weight")) + var weight: Int + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation( + title: "\(subject): \(strValue)", + subtitle: "\(topic)" + ) + } + + init(from grade: WidgetGrade) { + self.id = grade.uid + self.subject = grade.subject.name + self.numericValue = grade.numericValue ?? 0 + self.strValue = grade.displayValue + self.topic = grade.topic ?? "" + self.type = grade.type.name + self.teacher = grade.subject.teacherName ?? "" + self.date = grade.recordDate + self.weight = grade.weightPercentage ?? 100 + } + + init(id: String, subject: String, numericValue: Int, strValue: String, topic: String, type: String, teacher: String, date: Date, weight: Int) { + self.id = id + self.subject = subject + self.numericValue = numericValue + self.strValue = strValue + self.topic = topic + self.type = type + self.teacher = teacher + self.date = date + self.weight = weight + } +} + +@available(iOS 16.0, *) +struct GradeEntityQuery: EntityQuery { + func entities(for identifiers: [String]) async throws -> [GradeEntity] { + guard let data = WidgetData.load() else { return [] } + return data.grades + .filter { identifiers.contains($0.uid) } + .map { GradeEntity(from: $0) } + } + + func suggestedEntities() async throws -> [GradeEntity] { + guard let data = WidgetData.load() else { return [] } + return data.grades.prefix(10).map { GradeEntity(from: $0) } + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/LessonEntity.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/LessonEntity.swift new file mode 100644 index 00000000..5cdb0f70 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/LessonEntity.swift @@ -0,0 +1,86 @@ +import AppIntents +import Foundation + +@available(iOS 16.0, *) +struct LessonEntity: AppEntity { + static var typeDisplayRepresentation = TypeDisplayRepresentation(name: LocalizedStringResource("entity_lesson", defaultValue: "Lesson")) + static var defaultQuery = LessonEntityQuery() + + var id: String + + @Property(title: LocalizedStringResource("entity_prop_name", defaultValue: "Name")) + var name: String + + @Property(title: LocalizedStringResource("entity_prop_teacher", defaultValue: "Teacher")) + var teacher: String + + @Property(title: LocalizedStringResource("entity_prop_room", defaultValue: "Room")) + var room: String + + @Property(title: LocalizedStringResource("entity_prop_start_time", defaultValue: "Start time")) + var startTime: Date + + @Property(title: LocalizedStringResource("entity_prop_end_time", defaultValue: "End time")) + var endTime: Date + + @Property(title: LocalizedStringResource("entity_prop_lesson_number", defaultValue: "Lesson number")) + var lessonNumber: Int + + @Property(title: LocalizedStringResource("entity_prop_cancelled", defaultValue: "Cancelled")) + var isCancelled: Bool + + @Property(title: LocalizedStringResource("entity_prop_substitution", defaultValue: "Substitution")) + var isSubstitution: Bool + + @Property(title: LocalizedStringResource("entity_prop_theme", defaultValue: "Theme")) + var theme: String + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation( + title: "\(name)", + subtitle: "\(lessonNumber). \(room) - \(teacher)" + ) + } + + init(from lesson: WidgetLesson) { + self.id = lesson.uid + self.name = lesson.subject.name + self.teacher = lesson.teacher ?? "" + self.room = lesson.roomName ?? "" + self.startTime = lesson.start + self.endTime = lesson.end + self.lessonNumber = lesson.lessonNumber ?? 0 + self.isCancelled = lesson.isCancelled + self.isSubstitution = lesson.isSubstitution + self.theme = lesson.theme ?? "" + } + + init(id: String, name: String, teacher: String, room: String, startTime: Date, endTime: Date, lessonNumber: Int, isCancelled: Bool, isSubstitution: Bool, theme: String) { + self.id = id + self.name = name + self.teacher = teacher + self.room = room + self.startTime = startTime + self.endTime = endTime + self.lessonNumber = lessonNumber + self.isCancelled = isCancelled + self.isSubstitution = isSubstitution + self.theme = theme + } +} + +@available(iOS 16.0, *) +struct LessonEntityQuery: EntityQuery { + func entities(for identifiers: [String]) async throws -> [LessonEntity] { + guard let data = WidgetData.load() else { return [] } + let allLessons = data.timetable.today + data.timetable.tomorrow + (data.timetable.nextSchoolDay ?? []) + return allLessons + .filter { identifiers.contains($0.uid) } + .map { LessonEntity(from: $0) } + } + + func suggestedEntities() async throws -> [LessonEntity] { + guard let data = WidgetData.load() else { return [] } + return data.timetable.today.map { LessonEntity(from: $0) } + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/SubjectEntity.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/SubjectEntity.swift new file mode 100644 index 00000000..aca45708 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Entities/SubjectEntity.swift @@ -0,0 +1,37 @@ +import AppIntents + +@available(iOS 16.0, *) +struct SubjectEntity: AppEntity { + let id: String + let name: String + + static var typeDisplayRepresentation: TypeDisplayRepresentation { + TypeDisplayRepresentation(name: LocalizedStringResource("subjects_type", defaultValue: "Subjects")) + } + + static var defaultQuery = SubjectQuery() + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation(title: "\(name)") + } +} + +@available(iOS 16.0, *) +struct SubjectQuery: EntityQuery { + func entities(for identifiers: [String]) async throws -> [SubjectEntity] { + let data = WidgetData.load() + return data?.averages.subjects + .filter { identifiers.contains($0.uid) } + .map { SubjectEntity(id: $0.uid, name: $0.name) } ?? [] + } + + func suggestedEntities() async throws -> [SubjectEntity] { + let data = WidgetData.load() + return data?.averages.subjects + .map { SubjectEntity(id: $0.uid, name: $0.name) } ?? [] + } + + func defaultResult() async -> SubjectEntity? { + try? await suggestedEntities().first + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/FirkaShortcuts.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/FirkaShortcuts.swift new file mode 100644 index 00000000..10a55720 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/FirkaShortcuts.swift @@ -0,0 +1,52 @@ +import AppIntents + +@available(iOS 16.0, *) +struct FirkaShortcuts: AppShortcutsProvider { + static var appShortcuts: [AppShortcut] { + AppShortcut( + intent: GetNextLessonIntent(), + phrases: [ + "Next lesson \(.applicationName)", + "What is my next lesson \(.applicationName)" + ], + shortTitle: LocalizedStringResource("shortcut_short_next_lesson", defaultValue: "Next lesson"), + systemImageName: "calendar" + ) + AppShortcut( + intent: GetClosestLessonIntent(), + phrases: [ + "Closest lesson \(.applicationName)", + "When is my next lesson \(.applicationName)" + ], + shortTitle: LocalizedStringResource("shortcut_short_closest_lesson", defaultValue: "Closest lesson"), + systemImageName: "forward" + ) + AppShortcut( + intent: GetTodayTimetableIntent(), + phrases: [ + "Today's timetable \(.applicationName)", + "What lessons do I have today \(.applicationName)" + ], + shortTitle: LocalizedStringResource("shortcut_short_today_timetable", defaultValue: "Today's timetable"), + systemImageName: "clock" + ) + AppShortcut( + intent: GetClosestTimetableIntent(), + phrases: [ + "Closest timetable \(.applicationName)", + "When are my next lessons \(.applicationName)" + ], + shortTitle: LocalizedStringResource("shortcut_short_closest_timetable", defaultValue: "Closest timetable"), + systemImageName: "forward.fill" + ) + AppShortcut( + intent: GetOverallAverageIntent(), + phrases: [ + "My average \(.applicationName)", + "What is my average \(.applicationName)" + ], + shortTitle: LocalizedStringResource("shortcut_short_overall_average", defaultValue: "My average"), + systemImageName: "chart.bar" + ) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestLessonIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestLessonIntent.swift new file mode 100644 index 00000000..2809b2df --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestLessonIntent.swift @@ -0,0 +1,32 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetClosestLessonIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_closest_lesson_title", defaultValue: "Closest lesson") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_closest_lesson_description", defaultValue: "Get the closest lesson (today, tomorrow, or next school day)")) + + func perform() async throws -> some ReturnsValue & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + let now = Date() + + if let lesson = data.timetable.today.first(where: { $0.start > now }) + ?? data.timetable.today.first(where: { $0.end > now }) { + let entity = LessonEntity(from: lesson) + return .result(value: entity, dialog: "\(entity.name) - \(entity.room)") + } + + if let lesson = data.timetable.tomorrow.first { + let entity = LessonEntity(from: lesson) + return .result(value: entity, dialog: "\(entity.name) - \(entity.room)") + } + + if let lesson = data.timetable.nextSchoolDay?.first { + let entity = LessonEntity(from: lesson) + return .result(value: entity, dialog: "\(entity.name) - \(entity.room)") + } + + throw ShortcutError.noUpcomingLesson + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestTimetableIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestTimetableIntent.swift new file mode 100644 index 00000000..40f3555a --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetClosestTimetableIntent.swift @@ -0,0 +1,35 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetClosestTimetableIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_closest_timetable_title", defaultValue: "Closest timetable") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_closest_timetable_description", defaultValue: "Get the closest school day's timetable (today, tomorrow, or next school day)")) + + func perform() async throws -> some ReturnsValue<[LessonEntity]> & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + let now = Date() + + let remaining = data.timetable.today.filter { $0.end > now } + if !remaining.isEmpty { + let entities = remaining.map { LessonEntity(from: $0) } + let summary = entities.map { "\($0.lessonNumber). \($0.name)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } + + if !data.timetable.tomorrow.isEmpty { + let entities = data.timetable.tomorrow.map { LessonEntity(from: $0) } + let summary = entities.map { "\($0.lessonNumber). \($0.name)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } + + if let nextDay = data.timetable.nextSchoolDay, !nextDay.isEmpty { + let entities = nextDay.map { LessonEntity(from: $0) } + let summary = entities.map { "\($0.lessonNumber). \($0.name)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } + + throw ShortcutError.noUpcomingLesson + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetNextLessonIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetNextLessonIntent.swift new file mode 100644 index 00000000..2e211957 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetNextLessonIntent.swift @@ -0,0 +1,21 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetNextLessonIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_next_lesson_title", defaultValue: "Next lesson") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_next_lesson_description", defaultValue: "Get the next lesson details")) + + func perform() async throws -> some ReturnsValue & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + let now = Date() + let upcoming = data.timetable.today.first { $0.start > now } + ?? data.timetable.today.first { $0.end > now } + guard let lesson = upcoming else { + throw ShortcutError.noUpcomingLesson + } + let entity = LessonEntity(from: lesson) + return .result(value: entity, dialog: "\(entity.name) - \(entity.room)") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetOverallAverageIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetOverallAverageIntent.swift new file mode 100644 index 00000000..3439dff4 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetOverallAverageIntent.swift @@ -0,0 +1,18 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetOverallAverageIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_overall_average_title", defaultValue: "Overall average") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_overall_average_description", defaultValue: "Get the overall academic average")) + + func perform() async throws -> some ReturnsValue & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + guard let overall = data.averages.overall else { + throw ShortcutError.noData + } + let rounded = (overall * 100).rounded() / 100 + return .result(value: rounded, dialog: "\(String(format: "%.2f", rounded))") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetRecentGradesIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetRecentGradesIntent.swift new file mode 100644 index 00000000..b4d8f4e8 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetRecentGradesIntent.swift @@ -0,0 +1,20 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetRecentGradesIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_recent_grades_title", defaultValue: "Recent grades") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_recent_grades_description", defaultValue: "Get the most recent grades")) + + @Parameter(title: LocalizedStringResource("shortcut_param_count", defaultValue: "Count"), default: 5) + var count: Int + + func perform() async throws -> some ReturnsValue<[GradeEntity]> & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + let grades = Array(data.grades.prefix(count)) + let entities = grades.map { GradeEntity(from: $0) } + let summary = entities.map { "\($0.subject): \($0.strValue)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetSubjectAverageIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetSubjectAverageIntent.swift new file mode 100644 index 00000000..43e7d926 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetSubjectAverageIntent.swift @@ -0,0 +1,21 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetSubjectAverageIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_subject_average_title", defaultValue: "Subject average") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_subject_average_description", defaultValue: "Get the average for a subject")) + + @Parameter(title: LocalizedStringResource("shortcut_param_subject", defaultValue: "Subject")) + var subject: SubjectEntity + + func perform() async throws -> some ReturnsValue & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + guard let avg = data.averages.subjects.first(where: { $0.uid == subject.id }) else { + throw ShortcutError.subjectNotFound + } + let entity = AverageEntity(from: avg) + return .result(value: entity, dialog: "\(entity.subjectName): \(String(format: "%.2f", entity.average))") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTodayTimetableIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTodayTimetableIntent.swift new file mode 100644 index 00000000..1fb7aabe --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTodayTimetableIntent.swift @@ -0,0 +1,19 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetTodayTimetableIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_today_timetable_title", defaultValue: "Today's timetable") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_today_timetable_description", defaultValue: "Get today's full timetable")) + + func perform() async throws -> some ReturnsValue<[LessonEntity]> & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + guard !data.timetable.today.isEmpty else { + throw ShortcutError.noLessonsToday + } + let entities = data.timetable.today.map { LessonEntity(from: $0) } + let summary = entities.map { "\($0.lessonNumber). \($0.name)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTomorrowTimetableIntent.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTomorrowTimetableIntent.swift new file mode 100644 index 00000000..272932a4 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/Intents/GetTomorrowTimetableIntent.swift @@ -0,0 +1,19 @@ +import AppIntents + +@available(iOS 16.0, *) +struct GetTomorrowTimetableIntent: AppIntent { + static var title: LocalizedStringResource = LocalizedStringResource("shortcut_tomorrow_timetable_title", defaultValue: "Tomorrow's timetable") + static var description: IntentDescription = IntentDescription(LocalizedStringResource("shortcut_tomorrow_timetable_description", defaultValue: "Get tomorrow's timetable")) + + func perform() async throws -> some ReturnsValue<[LessonEntity]> & ProvidesDialog { + guard let data = WidgetData.load() else { + throw ShortcutError.noData + } + guard !data.timetable.tomorrow.isEmpty else { + throw ShortcutError.noLessonsTomorrow + } + let entities = data.timetable.tomorrow.map { LessonEntity(from: $0) } + let summary = entities.map { "\($0.lessonNumber). \($0.name)" }.joined(separator: ", ") + return .result(value: entities, dialog: "\(summary)") + } +} diff --git a/firka/ios/HomeWidgetsExtension/Shortcuts/ShortcutError.swift b/firka/ios/HomeWidgetsExtension/Shortcuts/ShortcutError.swift new file mode 100644 index 00000000..8b54af0f --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Shortcuts/ShortcutError.swift @@ -0,0 +1,25 @@ +import Foundation + +@available(iOS 16.0, *) +enum ShortcutError: Error, CustomLocalizedStringResourceConvertible { + case noData + case noUpcomingLesson + case noLessonsToday + case noLessonsTomorrow + case subjectNotFound + + var localizedStringResource: LocalizedStringResource { + switch self { + case .noData: + return LocalizedStringResource("shortcut_error_no_data", defaultValue: "No data available. Open the Firka app to refresh.") + case .noUpcomingLesson: + return LocalizedStringResource("shortcut_error_no_upcoming_lesson", defaultValue: "No more lessons today.") + case .noLessonsToday: + return LocalizedStringResource("shortcut_error_no_lessons_today", defaultValue: "No lessons today.") + case .noLessonsTomorrow: + return LocalizedStringResource("shortcut_error_no_lessons_tomorrow", defaultValue: "No lessons tomorrow.") + case .subjectNotFound: + return LocalizedStringResource("shortcut_error_subject_not_found", defaultValue: "Subject not found.") + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/TimetableWidget.swift b/firka/ios/HomeWidgetsExtension/TimetableWidget.swift new file mode 100644 index 00000000..73bb6ad9 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/TimetableWidget.swift @@ -0,0 +1,60 @@ +import WidgetKit +import SwiftUI + +struct TimetableWidget: Widget { + let kind: String = "TimetableWidget" + + var body: some WidgetConfiguration { + AppIntentConfiguration( + kind: kind, + intent: TimetableWidgetIntent.self, + provider: TimetableProvider() + ) { entry in + TimetableWidgetView(entry: entry) + .containerBackground(.clear, for: .widget) + } + .configurationDisplayName(LocalizedStringResource("widget_timetable_title", defaultValue: "Timetable")) + .description(LocalizedStringResource("widget_timetable_description", defaultValue: "Shows your daily timetable")) + .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) + } +} + +struct TimetableWidgetView: View { + @Environment(\.widgetFamily) var family + let entry: TimetableEntry + + var localization: WidgetLocalization { + WidgetLocalization(locale: entry.data?.locale ?? "hu") + } + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var body: some View { + Group { + switch entry.state { + case .onBreak: + if let breakInfo = entry.breakInfo { + BreakView(breakInfo: breakInfo, localization: localization, style: style) + } + case .loginRequired: + EmptyStateView(message: localization.string("login_required"), style: style) + case .unavailable: + EmptyStateView(message: localization.string("timetable_unavailable"), style: style) + case .noMoreLessons, .normal: + switch family { + case .systemSmall: + TimetableSmallView(entry: entry, localization: localization) + case .systemMedium: + TimetableMediumView(entry: entry, localization: localization) + case .systemLarge: + TimetableLargeView(entry: entry, localization: localization) + default: + TimetableMediumView(entry: entry, localization: localization) + } + } + } + .widgetURL(URL(string: "firka://widget/timetable")) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Views/AveragesViews.swift b/firka/ios/HomeWidgetsExtension/Views/AveragesViews.swift new file mode 100644 index 00000000..40ef7631 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Views/AveragesViews.swift @@ -0,0 +1,234 @@ +import SwiftUI +import WidgetKit + +struct AveragesSmallView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(spacing: 8) { + Text(localization.string("overall_average")) + .font(.caption) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + if let average = entry.overallAverage { + Text(String(format: "%.2f", average)) + .font(.system(size: 36, weight: .bold)) + .minimumScaleFactor(0.5) + .foregroundStyle(averageColor(for: average)) + } else { + Text("-") + .font(.system(size: 36, weight: .bold)) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + } + .padding() + } + } + + func averageColor(for value: Double) -> Color { + switch value { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} + +struct AveragesMediumView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + private let maxVisible = 4 + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var totalCount: Int { + entry.subjectAverages.count + } + + var showingCount: Int { + min(totalCount, maxVisible) + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(localization.string("subject_averages")) + .font(.caption) + .fontWeight(.semibold) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + Spacer() + + if entry.isFiltered && totalCount > maxVisible { + Text("\(showingCount)/\(totalCount)") + .font(.caption2) + .fontWeight(.medium) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule() + .fill(Color.secondary.opacity(0.2)) + ) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + if let overall = entry.overallAverage { + Text(String(format: "%.2f", overall)) + .font(.subheadline) + .fontWeight(.bold) + .foregroundStyle(averageColor(for: overall)) + } + } + + if entry.subjectAverages.isEmpty { + Spacer() + Text(localization.string("no_averages")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + Spacer() + } else { + Spacer(minLength: 0) + ForEach(entry.subjectAverages.prefix(maxVisible)) { subject in + AverageRow(subject: subject, style: style, compact: true) + } + Spacer(minLength: 0) + } + } + .padding() + } + } + + func averageColor(for value: Double) -> Color { + switch value { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} + +struct AveragesLargeView: View { + let entry: AveragesEntry + let localization: WidgetLocalization + private let maxVisible = 9 + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var totalCount: Int { + entry.subjectAverages.count + } + + var showingCount: Int { + min(totalCount, maxVisible) + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(localization.string("subject_averages")) + .font(.headline) + .fontWeight(.bold) + .widgetTextStyle(style, colors: nil) + + Spacer() + + if entry.isFiltered && totalCount > maxVisible { + Text("\(showingCount)/\(totalCount)") + .font(.caption) + .fontWeight(.medium) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule() + .fill(Color.secondary.opacity(0.2)) + ) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + if let overall = entry.overallAverage { + Text(String(format: "%.2f", overall)) + .font(.headline) + .fontWeight(.bold) + .foregroundStyle(averageColor(for: overall)) + } + } + + if entry.subjectAverages.isEmpty { + Spacer() + Text(localization.string("no_averages")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + Spacer() + } else { + ForEach(entry.subjectAverages.prefix(maxVisible)) { subject in + AverageRow(subject: subject, style: style, showGradeCount: true) + } + Spacer() + } + } + .padding() + } + } + + func averageColor(for value: Double) -> Color { + switch value { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } +} + +struct AverageRow: View { + let subject: SubjectAverage + let style: WidgetStyleType + var showGradeCount: Bool = false + var compact: Bool = false + + var body: some View { + HStack(spacing: 12) { + Text(subject.name) + .font(compact ? .footnote : .subheadline) + .widgetTextStyle(style, colors: nil) + .lineLimit(1) + + Spacer() + + if showGradeCount { + Text("(\(subject.gradeCount))") + .font(.caption2) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + Text(subject.formattedAverage) + .font(compact ? .footnote : .subheadline) + .fontWeight(.bold) + .foregroundStyle(subject.averageColor) + } + .padding(.vertical, compact ? 2 : 4) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Views/GradesViews.swift b/firka/ios/HomeWidgetsExtension/Views/GradesViews.swift new file mode 100644 index 00000000..27b7f78e --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Views/GradesViews.swift @@ -0,0 +1,173 @@ +import SwiftUI +import WidgetKit + +struct GradesSmallView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 4) { + Text(localization.string("recent_grades")) + .font(.caption) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + if let grade = entry.grades.first { + Spacer() + + HStack { + Text(grade.displayValue) + .font(.system(size: 48, weight: .bold)) + .foregroundStyle(grade.gradeColor) + + Spacer() + } + + Text(grade.subjectNameWithWeight) + .font(.subheadline) + .fontWeight(.medium) + .widgetTextStyle(style, colors: nil) + .lineLimit(1) + + Text(grade.dateString) + .font(.caption) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } else { + Spacer() + Text(localization.string("no_grades")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + Spacer() + } + .padding() + } + } +} + +struct GradesMediumView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 6) { + Text(localization.string("recent_grades")) + .font(.caption) + .fontWeight(.semibold) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + if entry.grades.isEmpty { + Spacer() + Text(localization.string("no_grades")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + Spacer() + } else { + Spacer(minLength: 0) + ForEach(entry.grades.prefix(3)) { grade in + GradeRow(grade: grade, style: style, showTeacher: true, compact: true) + } + Spacer(minLength: 0) + } + } + .padding() + } + .clipped() + } +} + +struct GradesLargeView: View { + let entry: GradesEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 8) { + Text(localization.string("recent_grades")) + .font(.headline) + .fontWeight(.semibold) + .widgetTextStyle(style, colors: nil) + + if entry.grades.isEmpty { + Spacer() + Text(localization.string("no_grades")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + Spacer() + } else { + ForEach(entry.grades.prefix(6)) { grade in + GradeRow(grade: grade, style: style, showTeacher: true, showTopic: true) + } + } + } + .padding() + } + .clipped() + } +} + +struct GradeRow: View { + let grade: WidgetGrade + let style: WidgetStyleType + var showTeacher: Bool = false + var showTopic: Bool = false + var compact: Bool = false + + var body: some View { + HStack(spacing: 12) { + Text(grade.displayValue) + .font(compact ? .title3 : .title2) + .fontWeight(.bold) + .foregroundStyle(grade.gradeColor) + .frame(width: 32) + + VStack(alignment: .leading, spacing: compact ? 1 : 2) { + Text(grade.subjectNameWithWeight) + .font(compact ? .footnote : .subheadline) + .fontWeight(.medium) + .widgetTextStyle(style, colors: nil) + .lineLimit(1) + + HStack(spacing: 4) { + if showTeacher, let teacher = grade.teacherName { + Text(teacher) + .font(.caption2) + .widgetTextStyle(style, colors: nil, isPrimary: false) + .lineLimit(1) + + Text("•") + .font(.caption2) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + Text(grade.dateString) + .font(.caption2) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + } + + Spacer() + } + .padding(.vertical, compact ? 2 : 4) + } +} diff --git a/firka/ios/HomeWidgetsExtension/Views/TimetableViews.swift b/firka/ios/HomeWidgetsExtension/Views/TimetableViews.swift new file mode 100644 index 00000000..cfbb9f24 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Views/TimetableViews.swift @@ -0,0 +1,454 @@ +import SwiftUI +import WidgetKit + +struct TimetableSmallView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + @Environment(\.colorScheme) var colorScheme + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + var displayLesson: WidgetLesson? { + let mode = entry.configuration.displayMode ?? .current + if mode == .current { + return entry.currentLesson ?? entry.nextLesson + } else { + return entry.nextLesson + } + } + + var isShowingNextLesson: Bool { + let mode = entry.configuration.displayMode ?? .current + if mode == .current { + return entry.currentLesson == nil && entry.nextLesson != nil + } + return true + } + + var liquidGlassPrimary: Color { + colorScheme == .dark ? .white : .black + } + + var liquidGlassSecondary: Color { + colorScheme == .dark ? .white.opacity(0.7) : .black.opacity(0.6) + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(alignment: .leading, spacing: 4) { + Text(isShowingNextLesson ? + localization.string("next_lesson") : + localization.string("current_lesson")) + .font(.caption) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + if let lesson = displayLesson { + if entry.isNextSchoolDay { + let dateStr = WidgetLocalization.formatShortDate(entry.nextSchoolDayDateString, locale: localization.locale) + Text(dateStr) + .font(.caption2) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + Text(lesson.displayName) + .font(.subheadline) + .fontWeight(.semibold) + .foregroundColor(lesson.isCancelled ? .red : + lesson.isSubstitution ? .orange : + (style == .liquidGlass ? liquidGlassPrimary : .primary)) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) + + Text(lesson.timeString) + .font(.subheadline) + .foregroundColor(lesson.isCancelled ? .red.opacity(0.8) : + lesson.isSubstitution ? .orange.opacity(0.8) : + (style == .liquidGlass ? liquidGlassSecondary : .secondary)) + + if let room = lesson.roomName { + Text(room) + .font(.caption2) + .lineLimit(2) + .minimumScaleFactor(0.8) + .foregroundColor(lesson.isCancelled ? .red.opacity(0.7) : + lesson.isSubstitution ? .orange.opacity(0.7) : + (style == .liquidGlass ? liquidGlassSecondary : .secondary)) + } + } else { + Text(localization.string("no_lessons_ahead")) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + + Spacer() + } + .padding() + } + } +} + +struct TimetableMediumView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + func isLessonActive(_ lesson: WidgetLesson) -> Bool { + let checkDate = entry.date + return checkDate >= lesson.start && checkDate <= lesson.end + } + + var currentLessonIndex: Int { + let checkDate = entry.date + if let index = entry.lessons.firstIndex(where: { checkDate >= $0.start && checkDate <= $0.end }) { + return index + } + if let index = entry.lessons.firstIndex(where: { $0.start > checkDate }) { + return index + } + return max(0, entry.lessons.count - 1) + } + + var hasActiveBreak: Bool { + let checkDate = entry.date + for (currentLesson, nextLesson) in zip(entry.lessons, entry.lessons.dropFirst()) { + if checkDate > currentLesson.end && checkDate < nextLesson.start { + return true + } + } + return false + } + + var visibleLessons: [WidgetLesson] { + let totalLessons = entry.lessons.count + let maxVisible = hasActiveBreak ? 3 : 4 + + if totalLessons <= maxVisible { + return Array(entry.lessons) + } + + var startIndex = max(0, currentLessonIndex - 1) + + startIndex = min(startIndex, totalLessons - maxVisible) + + let endIndex = min(startIndex + maxVisible, totalLessons) + return Array(entry.lessons[startIndex.. lesson.end && entry.date < nextLesson.start + if isInBreak { + let totalBreakMinutes = Int(ceil(nextLesson.start.timeIntervalSince(lesson.end) / 60)) + BreakIndicatorRow(minutesLeft: totalBreakMinutes, localization: localization, style: style, compact: true) + } + } + } + Spacer(minLength: 0) + } + .padding() + } + .clipped() + } +} + +struct TimetableLargeView: View { + let entry: TimetableEntry + let localization: WidgetLocalization + + var style: WidgetStyleType { + (entry.configuration.style ?? .appTheme) == .liquidGlass ? .liquidGlass : .appTheme + } + + func isLessonActive(_ lesson: WidgetLesson) -> Bool { + let checkDate = entry.date + return checkDate >= lesson.start && checkDate <= lesson.end + } + + var currentLessonIndex: Int { + let checkDate = entry.date + if let index = entry.lessons.firstIndex(where: { checkDate >= $0.start && checkDate <= $0.end }) { + return index + } + if let index = entry.lessons.firstIndex(where: { $0.start > checkDate }) { + return index + } + return max(0, entry.lessons.count - 1) + } + + var hasActiveBreak: Bool { + let checkDate = entry.date + for (currentLesson, nextLesson) in zip(entry.lessons, entry.lessons.dropFirst()) { + if checkDate > currentLesson.end && checkDate < nextLesson.start { + return true + } + } + return false + } + + var visibleLessons: [WidgetLesson] { + let totalLessons = entry.lessons.count + let maxVisible = hasActiveBreak ? 6 : 7 + + if totalLessons <= maxVisible { + return Array(entry.lessons) + } + + var startIndex = max(0, currentLessonIndex - 1) + startIndex = min(startIndex, totalLessons - maxVisible) + + let endIndex = min(startIndex + maxVisible, totalLessons) + return Array(entry.lessons[startIndex.. lesson.end && entry.date < nextLesson.start + if isInBreak { + let totalBreakMinutes = Int(ceil(nextLesson.start.timeIntervalSince(lesson.end) / 60)) + BreakIndicatorRow(minutesLeft: totalBreakMinutes, localization: localization, style: style) + } + } + } + } + .padding() + } + .clipped() + } +} + +struct BreakIndicatorRow: View { + let minutesLeft: Int + let localization: WidgetLocalization + let style: WidgetStyleType + var compact: Bool = false + @Environment(\.colorScheme) var colorScheme + + var liquidGlassPrimary: Color { + colorScheme == .dark ? .white : .black + } + + var liquidGlassSecondary: Color { + colorScheme == .dark ? .white.opacity(0.7) : .black.opacity(0.6) + } + + var body: some View { + HStack(spacing: 12) { + Text("–") + .font(.caption) + .fontWeight(.bold) + .frame(width: 24, height: 24) + .background( + Circle() + .fill(Color.green.opacity(0.3)) + ) + .foregroundColor(style == .liquidGlass ? liquidGlassPrimary : .primary) + + Text(localization.string("break_between")) + .font(.subheadline) + .fontWeight(.semibold) + .foregroundColor(style == .liquidGlass ? liquidGlassPrimary : .primary) + + Spacer() + + Text("\(minutesLeft) \(localization.string("minutes_abbrev"))") + .font(.caption) + .foregroundColor(style == .liquidGlass ? liquidGlassSecondary : .secondary) + } + .padding(.vertical, compact ? 2 : 4) + .padding(.horizontal, 8) + .currentLessonGlow(isActive: true) + } +} + +struct LessonRow: View { + let lesson: WidgetLesson + let isActive: Bool + let style: WidgetStyleType + var showRoom: Bool = false + var compact: Bool = false + @Environment(\.colorScheme) var colorScheme + + var lessonTextColor: Color? { + if lesson.isCancelled { + return .red + } else if lesson.isSubstitution { + return .orange + } + return nil + } + + var liquidGlassPrimary: Color { + colorScheme == .dark ? .white : .black + } + + var liquidGlassSecondary: Color { + colorScheme == .dark ? .white.opacity(0.7) : .black.opacity(0.6) + } + + var numberBackgroundColor: Color { + if lesson.isCancelled { + return Color.red.opacity(0.3) + } else if lesson.isSubstitution { + return Color.orange.opacity(0.3) + } else if isActive { + return Color.green.opacity(0.3) + } + return Color.secondary.opacity(0.2) + } + + var body: some View { + HStack(spacing: 12) { + if let number = lesson.lessonNumber { + Text("\(number)") + .font(.caption) + .fontWeight(.bold) + .frame(width: 24, height: 24) + .background( + Circle() + .fill(numberBackgroundColor) + ) + .foregroundColor(lessonTextColor ?? (style == .liquidGlass ? liquidGlassPrimary : .primary)) + } + + Text(lesson.displayName) + .font(.subheadline) + .fontWeight(isActive ? .semibold : .regular) + .foregroundColor(lessonTextColor ?? (style == .liquidGlass ? liquidGlassPrimary : .primary)) + .lineLimit(1) + + Spacer() + + Text(lesson.timeString) + .font(.caption) + .foregroundColor(lessonTextColor?.opacity(0.8) ?? (style == .liquidGlass ? liquidGlassSecondary : .secondary)) + + if showRoom, let room = lesson.roomName { + Text(room) + .font(.caption2) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule() + .fill(lesson.isCancelled ? Color.red.opacity(0.2) : + lesson.isSubstitution ? Color.orange.opacity(0.2) : + Color.secondary.opacity(0.2)) + ) + .foregroundColor(lessonTextColor?.opacity(0.8) ?? (style == .liquidGlass ? liquidGlassSecondary : .secondary)) + } + } + .padding(.vertical, compact ? 2 : 4) + .padding(.horizontal, 8) + .currentLessonGlow(isActive: isActive) + } +} + +struct BreakView: View { + let breakInfo: BreakInfo + let localization: WidgetLocalization + let style: WidgetStyleType + + var daysRemaining: Int { + Calendar.current.dateComponents([.day], from: Date(), to: breakInfo.endDate).day ?? 0 + } + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(spacing: 12) { + Image(systemName: "snowflake") + .font(.largeTitle) + .widgetTextStyle(style, colors: nil) + + Text(localization.string("happy_break", localization.string(breakInfo.nameKey))) + .font(.headline) + .multilineTextAlignment(.center) + .widgetTextStyle(style, colors: nil) + + Text(localization.string("days_remaining", daysRemaining)) + .font(.subheadline) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + .padding() + } + } +} + +struct EmptyStateView: View { + let message: String + let style: WidgetStyleType + + var body: some View { + ZStack { + WidgetBackground(style: style, colors: nil) + + VStack(spacing: 8) { + Image(systemName: "calendar.badge.exclamationmark") + .font(.largeTitle) + .widgetTextStyle(style, colors: nil, isPrimary: false) + + Text(message) + .font(.subheadline) + .multilineTextAlignment(.center) + .widgetTextStyle(style, colors: nil, isPrimary: false) + } + .padding() + } + } +} diff --git a/firka/ios/HomeWidgetsExtension/Views/WidgetStyles.swift b/firka/ios/HomeWidgetsExtension/Views/WidgetStyles.swift new file mode 100644 index 00000000..8062dc97 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/Views/WidgetStyles.swift @@ -0,0 +1,102 @@ +import SwiftUI +import WidgetKit + +enum WidgetStyleType: String, Codable, CaseIterable { + case liquidGlass = "liquid_glass" + case appTheme = "app_theme" + + var displayName: String { + switch self { + case .liquidGlass: return "Liquid Glass" + case .appTheme: return "App Theme" + } + } +} + +struct WidgetBackground: View { + let style: WidgetStyleType + let colors: WidgetColors? + + @Environment(\.colorScheme) var colorScheme + + var body: some View { + switch style { + case .liquidGlass: + if #available(iOS 26.0, *) { + Color.clear + } else { + Rectangle() + .fill(.ultraThinMaterial) + } + case .appTheme: + if let colors = colors { + Rectangle() + .fill(colors.backgroundColor) + } else { + Rectangle() + .fill(Color(.systemBackground)) + } + } + } +} + +struct WidgetTextStyle: ViewModifier { + let style: WidgetStyleType + let colors: WidgetColors? + let isPrimary: Bool + + @Environment(\.colorScheme) var colorScheme + @Environment(\.widgetRenderingMode) var renderingMode + + func body(content: Content) -> some View { + switch style { + case .liquidGlass: + if renderingMode == .accented { + content + } else { + content.foregroundStyle(isPrimary ? + (colorScheme == .dark ? .white : .black) : + (colorScheme == .dark ? .white.opacity(0.7) : .black.opacity(0.6))) + } + case .appTheme: + if let colors = colors { + content.foregroundStyle(isPrimary ? colors.textPrimaryColor : colors.textSecondaryColor) + } else { + content.foregroundStyle(isPrimary ? .primary : .secondary) + } + } + } +} + +extension View { + func widgetTextStyle(_ style: WidgetStyleType, colors: WidgetColors?, isPrimary: Bool = true) -> some View { + modifier(WidgetTextStyle(style: style, colors: colors, isPrimary: isPrimary)) + } +} + +struct GlowEffect: ViewModifier { + let isActive: Bool + let color: Color + + func body(content: Content) -> some View { + if isActive { + content + .background( + RoundedRectangle(cornerRadius: 12) + .fill(color.opacity(0.15)) + ) + .overlay( + RoundedRectangle(cornerRadius: 12) + .stroke(color.opacity(0.3), lineWidth: 1) + ) + } else { + content + } + } +} + +extension View { + func currentLessonGlow(isActive: Bool, color: Color = .green) -> some View { + modifier(GlowEffect(isActive: isActive, color: color)) + } +} diff --git a/firka/ios/HomeWidgetsExtension/de.lproj/AppShortcuts.strings b/firka/ios/HomeWidgetsExtension/de.lproj/AppShortcuts.strings new file mode 100644 index 00000000..6bd2adfa --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/de.lproj/AppShortcuts.strings @@ -0,0 +1,11 @@ +/* Siri Phrases - German */ +"Next lesson ${applicationName}" = "Nächste Stunde ${applicationName}"; +"What is my next lesson ${applicationName}" = "Was ist meine nächste Stunde ${applicationName}"; +"Closest lesson ${applicationName}" = "Nächste anstehende Stunde ${applicationName}"; +"When is my next lesson ${applicationName}" = "Wann ist meine nächste Stunde ${applicationName}"; +"Today's timetable ${applicationName}" = "Stundenplan heute ${applicationName}"; +"What lessons do I have today ${applicationName}" = "Welche Stunden habe ich heute ${applicationName}"; +"Closest timetable ${applicationName}" = "Nächster Stundenplan ${applicationName}"; +"When are my next lessons ${applicationName}" = "Wann sind meine nächsten Stunden ${applicationName}"; +"My average ${applicationName}" = "Mein Durchschnitt ${applicationName}"; +"What is my average ${applicationName}" = "Wie ist mein Durchschnitt ${applicationName}"; diff --git a/firka/ios/HomeWidgetsExtension/de.lproj/Localizable.strings b/firka/ios/HomeWidgetsExtension/de.lproj/Localizable.strings new file mode 100644 index 00000000..c698858b --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/de.lproj/Localizable.strings @@ -0,0 +1,120 @@ +/* Widget Titles */ +"widget_timetable_title" = "Stundenplan"; +"widget_grades_title" = "Letzte Noten"; +"widget_averages_title" = "Durchschnitte"; + +/* Widget Descriptions */ +"widget_timetable_description" = "Zeigt deinen täglichen Stundenplan"; +"widget_grades_description" = "Zeigt deine letzten Noten"; +"widget_averages_description" = "Zeigt Fachdurchschnitte"; + +/* Lock Screen Widget Descriptions */ +"widget_timetable_lockscreen_description" = "Stundenplan auf dem Sperrbildschirm"; +"widget_grades_lockscreen_description" = "Noten auf dem Sperrbildschirm"; +"widget_averages_lockscreen_description" = "Durchschnitte auf dem Sperrbildschirm"; + +/* Parameter Titles */ +"param_style" = "Stil"; +"param_display_mode_small" = "Anzeige (kleines Widget)"; +"param_subjects" = "Fächer"; + +/* Style Options */ +"style_type" = "Stil"; +"style_liquid_glass" = "Liquid Glass"; +"style_app_theme" = "App-Design"; + +/* Display Mode Options */ +"display_mode_type" = "Anzeigemodus"; +"display_mode_current" = "Aktuelle Stunde"; +"display_mode_next" = "Nächste Stunde"; + +/* Subject Selection */ +"subjects_type" = "Fächer"; +"no_subjects_available" = "Keine Fächer verfügbar"; + +/* Control Widget Titles */ +"control_home_title" = "Firka Startseite"; +"control_home_label" = "Startseite"; +"control_home_display" = "Firka - Startseite"; +"control_home_description" = "Firka Startseite öffnen"; +"control_grades_title" = "Firka Noten"; +"control_grades_label" = "Noten"; +"control_grades_display" = "Firka - Noten"; +"control_grades_description" = "Firka Noten öffnen"; +"control_timetable_title" = "Firka Stundenplan"; +"control_timetable_label" = "Stundenplan"; +"control_timetable_display" = "Firka - Stundenplan"; +"control_timetable_description" = "Firka Stundenplan öffnen"; + +/* Shortcut Intent Titles & Descriptions */ +"shortcut_next_lesson_title" = "Nächste Stunde"; +"shortcut_next_lesson_description" = "Details zur nächsten Stunde"; +"shortcut_closest_lesson_title" = "Nächste anstehende Stunde"; +"shortcut_closest_lesson_description" = "Nächste anstehende Stunde (heute, morgen oder nächster Schultag)"; +"shortcut_today_timetable_title" = "Stundenplan heute"; +"shortcut_today_timetable_description" = "Der vollständige Stundenplan für heute"; +"shortcut_tomorrow_timetable_title" = "Stundenplan morgen"; +"shortcut_tomorrow_timetable_description" = "Der Stundenplan für morgen"; +"shortcut_closest_timetable_title" = "Nächster Stundenplan"; +"shortcut_closest_timetable_description" = "Stundenplan des nächsten Schultags (heute, morgen oder nächster Schultag)"; +"shortcut_recent_grades_title" = "Letzte Noten"; +"shortcut_recent_grades_description" = "Die letzten Noten"; +"shortcut_subject_average_title" = "Fachdurchschnitt"; +"shortcut_subject_average_description" = "Durchschnitt eines Fachs"; +"shortcut_overall_average_title" = "Gesamtdurchschnitt"; +"shortcut_overall_average_description" = "Der Gesamtdurchschnitt"; + +/* Shortcut Parameters */ +"shortcut_param_count" = "Anzahl"; +"shortcut_param_subject" = "Fach"; + +/* Shortcut Phrases */ +"shortcut_phrase_next_lesson" = "Nächste Stunde"; +"shortcut_phrase_next_lesson_question" = "Was ist meine nächste Stunde"; +"shortcut_phrase_closest_lesson" = "Nächste anstehende Stunde"; +"shortcut_phrase_closest_lesson_question" = "Wann ist meine nächste Stunde"; +"shortcut_phrase_today_timetable" = "Stundenplan heute"; +"shortcut_phrase_today_timetable_question" = "Welche Stunden habe ich heute"; +"shortcut_phrase_closest_timetable" = "Nächster Stundenplan"; +"shortcut_phrase_closest_timetable_question" = "Wann sind meine nächsten Stunden"; +"shortcut_phrase_overall_average" = "Mein Durchschnitt"; +"shortcut_phrase_overall_average_question" = "Wie ist mein Durchschnitt"; + +/* Shortcut Short Titles */ +"shortcut_short_next_lesson" = "Nächste Stunde"; +"shortcut_short_closest_lesson" = "Nächste anstehende"; +"shortcut_short_today_timetable" = "Stundenplan heute"; +"shortcut_short_closest_timetable" = "Nächster Stundenplan"; +"shortcut_short_overall_average" = "Mein Durchschnitt"; + +/* Shortcut Errors */ +"shortcut_error_no_data" = "Keine Daten verfügbar. Öffne die Firka App zum Aktualisieren."; +"shortcut_error_no_upcoming_lesson" = "Heute keine weiteren Stunden."; +"shortcut_error_no_lessons_today" = "Heute keine Stunden."; +"shortcut_error_no_lessons_tomorrow" = "Morgen keine Stunden."; +"shortcut_error_subject_not_found" = "Fach nicht gefunden."; + +/* Entity Type Names */ +"entity_lesson" = "Stunde"; +"entity_grade" = "Note"; +"entity_average" = "Durchschnitt"; + +/* Entity Property Names */ +"entity_prop_name" = "Name"; +"entity_prop_teacher" = "Lehrer"; +"entity_prop_room" = "Raum"; +"entity_prop_start_time" = "Startzeit"; +"entity_prop_end_time" = "Endzeit"; +"entity_prop_lesson_number" = "Stundennummer"; +"entity_prop_cancelled" = "Entfällt"; +"entity_prop_substitution" = "Vertretung"; +"entity_prop_theme" = "Thema"; +"entity_prop_subject" = "Fach"; +"entity_prop_value" = "Wert"; +"entity_prop_grade" = "Note"; +"entity_prop_topic" = "Thema"; +"entity_prop_type" = "Typ"; +"entity_prop_date" = "Datum"; +"entity_prop_weight" = "Gewicht"; +"entity_prop_average" = "Durchschnitt"; +"entity_prop_grade_count" = "Notenanzahl"; diff --git a/firka/ios/HomeWidgetsExtension/en.lproj/AppShortcuts.strings b/firka/ios/HomeWidgetsExtension/en.lproj/AppShortcuts.strings new file mode 100644 index 00000000..064cecc5 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/en.lproj/AppShortcuts.strings @@ -0,0 +1,11 @@ +/* Siri Phrases - English */ +"Next lesson ${applicationName}" = "Next lesson ${applicationName}"; +"What is my next lesson ${applicationName}" = "What is my next lesson ${applicationName}"; +"Closest lesson ${applicationName}" = "Closest lesson ${applicationName}"; +"When is my next lesson ${applicationName}" = "When is my next lesson ${applicationName}"; +"Today's timetable ${applicationName}" = "Today's timetable ${applicationName}"; +"What lessons do I have today ${applicationName}" = "What lessons do I have today ${applicationName}"; +"Closest timetable ${applicationName}" = "Closest timetable ${applicationName}"; +"When are my next lessons ${applicationName}" = "When are my next lessons ${applicationName}"; +"My average ${applicationName}" = "My average ${applicationName}"; +"What is my average ${applicationName}" = "What is my average ${applicationName}"; diff --git a/firka/ios/HomeWidgetsExtension/en.lproj/Localizable.strings b/firka/ios/HomeWidgetsExtension/en.lproj/Localizable.strings new file mode 100644 index 00000000..694b021d --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/en.lproj/Localizable.strings @@ -0,0 +1,120 @@ +/* Widget Titles */ +"widget_timetable_title" = "Timetable"; +"widget_grades_title" = "Recent Grades"; +"widget_averages_title" = "Averages"; + +/* Widget Descriptions */ +"widget_timetable_description" = "Shows your daily timetable"; +"widget_grades_description" = "Shows your recent grades"; +"widget_averages_description" = "Shows subject averages"; + +/* Lock Screen Widget Descriptions */ +"widget_timetable_lockscreen_description" = "Timetable on lock screen"; +"widget_grades_lockscreen_description" = "Grades on lock screen"; +"widget_averages_lockscreen_description" = "Averages on lock screen"; + +/* Parameter Titles */ +"param_style" = "Style"; +"param_display_mode_small" = "Display (small widget)"; +"param_subjects" = "Subjects"; + +/* Style Options */ +"style_type" = "Style"; +"style_liquid_glass" = "Liquid Glass"; +"style_app_theme" = "App Theme"; + +/* Display Mode Options */ +"display_mode_type" = "Display Mode"; +"display_mode_current" = "Current Lesson"; +"display_mode_next" = "Next Lesson"; + +/* Subject Selection */ +"subjects_type" = "Subjects"; +"no_subjects_available" = "No subjects available"; + +/* Control Widget Titles */ +"control_home_title" = "Firka Home"; +"control_home_label" = "Home"; +"control_home_display" = "Firka - Home"; +"control_home_description" = "Open Firka home screen"; +"control_grades_title" = "Firka Grades"; +"control_grades_label" = "Grades"; +"control_grades_display" = "Firka - Grades"; +"control_grades_description" = "Open Firka grades"; +"control_timetable_title" = "Firka Timetable"; +"control_timetable_label" = "Timetable"; +"control_timetable_display" = "Firka - Timetable"; +"control_timetable_description" = "Open Firka timetable"; + +/* Shortcut Intent Titles & Descriptions */ +"shortcut_next_lesson_title" = "Next lesson"; +"shortcut_next_lesson_description" = "Get the next lesson details"; +"shortcut_closest_lesson_title" = "Closest lesson"; +"shortcut_closest_lesson_description" = "Get the closest lesson (today, tomorrow, or next school day)"; +"shortcut_today_timetable_title" = "Today's timetable"; +"shortcut_today_timetable_description" = "Get today's full timetable"; +"shortcut_tomorrow_timetable_title" = "Tomorrow's timetable"; +"shortcut_tomorrow_timetable_description" = "Get tomorrow's timetable"; +"shortcut_closest_timetable_title" = "Closest timetable"; +"shortcut_closest_timetable_description" = "Get the closest school day's timetable (today, tomorrow, or next school day)"; +"shortcut_recent_grades_title" = "Recent grades"; +"shortcut_recent_grades_description" = "Get the most recent grades"; +"shortcut_subject_average_title" = "Subject average"; +"shortcut_subject_average_description" = "Get the average for a subject"; +"shortcut_overall_average_title" = "Overall average"; +"shortcut_overall_average_description" = "Get the overall academic average"; + +/* Shortcut Parameters */ +"shortcut_param_count" = "Count"; +"shortcut_param_subject" = "Subject"; + +/* Shortcut Phrases */ +"shortcut_phrase_next_lesson" = "Next lesson"; +"shortcut_phrase_next_lesson_question" = "What is my next lesson"; +"shortcut_phrase_closest_lesson" = "Closest lesson"; +"shortcut_phrase_closest_lesson_question" = "When is my next lesson"; +"shortcut_phrase_today_timetable" = "Today's timetable"; +"shortcut_phrase_today_timetable_question" = "What lessons do I have today"; +"shortcut_phrase_closest_timetable" = "Closest timetable"; +"shortcut_phrase_closest_timetable_question" = "When are my next lessons"; +"shortcut_phrase_overall_average" = "My average"; +"shortcut_phrase_overall_average_question" = "What is my average"; + +/* Shortcut Short Titles */ +"shortcut_short_next_lesson" = "Next lesson"; +"shortcut_short_closest_lesson" = "Closest lesson"; +"shortcut_short_today_timetable" = "Today's timetable"; +"shortcut_short_closest_timetable" = "Closest timetable"; +"shortcut_short_overall_average" = "My average"; + +/* Shortcut Errors */ +"shortcut_error_no_data" = "No data available. Open the Firka app to refresh."; +"shortcut_error_no_upcoming_lesson" = "No more lessons today."; +"shortcut_error_no_lessons_today" = "No lessons today."; +"shortcut_error_no_lessons_tomorrow" = "No lessons tomorrow."; +"shortcut_error_subject_not_found" = "Subject not found."; + +/* Entity Type Names */ +"entity_lesson" = "Lesson"; +"entity_grade" = "Grade"; +"entity_average" = "Average"; + +/* Entity Property Names */ +"entity_prop_name" = "Name"; +"entity_prop_teacher" = "Teacher"; +"entity_prop_room" = "Room"; +"entity_prop_start_time" = "Start time"; +"entity_prop_end_time" = "End time"; +"entity_prop_lesson_number" = "Lesson number"; +"entity_prop_cancelled" = "Cancelled"; +"entity_prop_substitution" = "Substitution"; +"entity_prop_theme" = "Theme"; +"entity_prop_subject" = "Subject"; +"entity_prop_value" = "Value"; +"entity_prop_grade" = "Grade"; +"entity_prop_topic" = "Topic"; +"entity_prop_type" = "Type"; +"entity_prop_date" = "Date"; +"entity_prop_weight" = "Weight"; +"entity_prop_average" = "Average"; +"entity_prop_grade_count" = "Grade count"; diff --git a/firka/ios/HomeWidgetsExtension/hu.lproj/AppShortcuts.strings b/firka/ios/HomeWidgetsExtension/hu.lproj/AppShortcuts.strings new file mode 100644 index 00000000..76500a93 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/hu.lproj/AppShortcuts.strings @@ -0,0 +1,11 @@ +/* Siri Phrases - Hungarian */ +"Next lesson ${applicationName}" = "Következő óra ${applicationName}"; +"What is my next lesson ${applicationName}" = "Mi a következő órám ${applicationName}"; +"Closest lesson ${applicationName}" = "Legközelebbi óra ${applicationName}"; +"When is my next lesson ${applicationName}" = "Mikor lesz órám ${applicationName}"; +"Today's timetable ${applicationName}" = "Mai órarend ${applicationName}"; +"What lessons do I have today ${applicationName}" = "Milyen óráim vannak ma ${applicationName}"; +"Closest timetable ${applicationName}" = "Legközelebbi órarend ${applicationName}"; +"When are my next lessons ${applicationName}" = "Mikor lesznek óráim ${applicationName}"; +"My average ${applicationName}" = "Átlagom ${applicationName}"; +"What is my average ${applicationName}" = "Mennyi az átlagom ${applicationName}"; diff --git a/firka/ios/HomeWidgetsExtension/hu.lproj/Localizable.strings b/firka/ios/HomeWidgetsExtension/hu.lproj/Localizable.strings new file mode 100644 index 00000000..273c0400 --- /dev/null +++ b/firka/ios/HomeWidgetsExtension/hu.lproj/Localizable.strings @@ -0,0 +1,120 @@ +/* Widget Titles */ +"widget_timetable_title" = "Órarend"; +"widget_grades_title" = "Legutóbbi jegyek"; +"widget_averages_title" = "Átlagok"; + +/* Widget Descriptions */ +"widget_timetable_description" = "A napi órarendet mutatja"; +"widget_grades_description" = "A legutóbbi jegyeidet mutatja"; +"widget_averages_description" = "A tantárgyi átlagokat mutatja"; + +/* Lock Screen Widget Descriptions */ +"widget_timetable_lockscreen_description" = "Órarend a zárolt képernyőn"; +"widget_grades_lockscreen_description" = "Jegyek a zárolt képernyőn"; +"widget_averages_lockscreen_description" = "Átlagok a zárolt képernyőn"; + +/* Parameter Titles */ +"param_style" = "Stílus"; +"param_display_mode_small" = "Megjelenítés (kis widget)"; +"param_subjects" = "Tantárgyak"; + +/* Style Options */ +"style_type" = "Stílus"; +"style_liquid_glass" = "Liquid Glass"; +"style_app_theme" = "Alkalmazás témája"; + +/* Display Mode Options */ +"display_mode_type" = "Megjelenítési mód"; +"display_mode_current" = "Jelenlegi óra"; +"display_mode_next" = "Következő óra"; + +/* Subject Selection */ +"subjects_type" = "Tantárgyak"; +"no_subjects_available" = "Nincsenek tantárgyak"; + +/* Control Widget Titles */ +"control_home_title" = "Firka Főoldal"; +"control_home_label" = "Főoldal"; +"control_home_display" = "Firka - Főoldal"; +"control_home_description" = "Firka app főoldal megnyitása"; +"control_grades_title" = "Firka Jegyek"; +"control_grades_label" = "Jegyek"; +"control_grades_display" = "Firka - Jegyek"; +"control_grades_description" = "Firka app jegyek megnyitása"; +"control_timetable_title" = "Firka Órarend"; +"control_timetable_label" = "Órarend"; +"control_timetable_display" = "Firka - Órarend"; +"control_timetable_description" = "Firka app órarend megnyitása"; + +/* Shortcut Intent Titles & Descriptions */ +"shortcut_next_lesson_title" = "Következő óra"; +"shortcut_next_lesson_description" = "A következő óra adatai"; +"shortcut_closest_lesson_title" = "Legközelebbi óra"; +"shortcut_closest_lesson_description" = "A legközelebbi óra adatai (ma, holnap, vagy a következő tanítási nap)"; +"shortcut_today_timetable_title" = "Mai órarend"; +"shortcut_today_timetable_description" = "A mai nap teljes órarendje"; +"shortcut_tomorrow_timetable_title" = "Holnapi órarend"; +"shortcut_tomorrow_timetable_description" = "A holnapi nap órarendje"; +"shortcut_closest_timetable_title" = "Legközelebbi órarend"; +"shortcut_closest_timetable_description" = "A legközelebbi tanítási nap órarendje (ma, holnap, vagy a következő tanítási nap)"; +"shortcut_recent_grades_title" = "Legutóbbi jegyek"; +"shortcut_recent_grades_description" = "A legutóbbi jegyek listája"; +"shortcut_subject_average_title" = "Tantárgyi átlag"; +"shortcut_subject_average_description" = "Egy tantárgy átlaga"; +"shortcut_overall_average_title" = "Összesített átlag"; +"shortcut_overall_average_description" = "Az összesített tanulmányi átlag"; + +/* Shortcut Parameters */ +"shortcut_param_count" = "Darabszám"; +"shortcut_param_subject" = "Tantárgy"; + +/* Shortcut Phrases */ +"shortcut_phrase_next_lesson" = "Következő óra"; +"shortcut_phrase_next_lesson_question" = "Mi a következő órám"; +"shortcut_phrase_closest_lesson" = "Legközelebbi óra"; +"shortcut_phrase_closest_lesson_question" = "Mikor lesz órám"; +"shortcut_phrase_today_timetable" = "Mai órarend"; +"shortcut_phrase_today_timetable_question" = "Milyen óráim vannak ma"; +"shortcut_phrase_closest_timetable" = "Legközelebbi órarend"; +"shortcut_phrase_closest_timetable_question" = "Mikor lesznek óráim"; +"shortcut_phrase_overall_average" = "Átlagom"; +"shortcut_phrase_overall_average_question" = "Mennyi az átlagom"; + +/* Shortcut Short Titles */ +"shortcut_short_next_lesson" = "Következő óra"; +"shortcut_short_closest_lesson" = "Legközelebbi óra"; +"shortcut_short_today_timetable" = "Mai órarend"; +"shortcut_short_closest_timetable" = "Legközelebbi órarend"; +"shortcut_short_overall_average" = "Átlagom"; + +/* Shortcut Errors */ +"shortcut_error_no_data" = "Nincs elérhető adat. Nyisd meg a Firka appot az adatok frissítéséhez."; +"shortcut_error_no_upcoming_lesson" = "Ma nincs több órád."; +"shortcut_error_no_lessons_today" = "Ma nincs órád."; +"shortcut_error_no_lessons_tomorrow" = "Holnap nincs órád."; +"shortcut_error_subject_not_found" = "A tantárgy nem található."; + +/* Entity Type Names */ +"entity_lesson" = "Óra"; +"entity_grade" = "Jegy"; +"entity_average" = "Átlag"; + +/* Entity Property Names */ +"entity_prop_name" = "Név"; +"entity_prop_teacher" = "Tanár"; +"entity_prop_room" = "Terem"; +"entity_prop_start_time" = "Kezdés"; +"entity_prop_end_time" = "Vége"; +"entity_prop_lesson_number" = "Óraszám"; +"entity_prop_cancelled" = "Elmarad"; +"entity_prop_substitution" = "Helyettesítés"; +"entity_prop_theme" = "Téma"; +"entity_prop_subject" = "Tantárgy"; +"entity_prop_value" = "Érték"; +"entity_prop_grade" = "Jegy"; +"entity_prop_topic" = "Téma"; +"entity_prop_type" = "Típus"; +"entity_prop_date" = "Dátum"; +"entity_prop_weight" = "Súly"; +"entity_prop_average" = "Átlag"; +"entity_prop_grade_count" = "Jegyek száma"; diff --git a/firka/ios/LiveActivityWidget.entitlements b/firka/ios/LiveActivityWidget.entitlements new file mode 100644 index 00000000..b16f8cff --- /dev/null +++ b/firka/ios/LiveActivityWidget.entitlements @@ -0,0 +1,14 @@ + + + + + aps-environment + development + com.apple.developer.ubiquity-kvstore-identifier + $(TeamIdentifierPrefix)$(CFBundleIdentifier) + com.apple.security.application-groups + + group.app.firkaa.legacy + + + diff --git a/firka/ios/LiveActivityWidget/ActivityAttributes.swift b/firka/ios/LiveActivityWidget/ActivityAttributes.swift new file mode 100644 index 00000000..6d5f18ea --- /dev/null +++ b/firka/ios/LiveActivityWidget/ActivityAttributes.swift @@ -0,0 +1,412 @@ +import ActivityKit +import Foundation + +struct TimetableActivityAttributes: ActivityAttributes { + public struct ContentState: Codable, Hashable { + var isBreak: Bool + var lessonName: String + var lessonTheme: String? + var roomName: String? + var teacherName: String? + var startTime: Date + var endTime: Date + var lessonNumber: Int? + + var mode: String? // "lesson" | "break" | "seasonalBreak" | "xmas" | "newYearEve" | "newYearDay" + var message: String? + var season: String? + + var nextLessonName: String? + var nextRoomName: String? + var nextStartTime: Date? + + var isSubstitution: Bool + var isCancelled: Bool + var substituteTeacher: String? + + var currentTime: Date + + var labels: Labels? + var tokenExpirationWarning: String? + var tokenExpired: Bool? + var compactTimerText: String? + var lessonIcon: String? + + struct Labels: Codable, Hashable { + var title: String? + var timerLabel: String? + var cancelledText: String? + var substitutionText: String? + var roomLabel: String? + var teacherLabel: String? + var themeLabel: String? + var nextLabel: String? + var firstLessonLabel: String? + var startTimeLabel: String? + var lessonNumberLabel: String? + var nextRoomLabel: String? + var remainingLabel: String? + } + + enum CodingKeys: String, CodingKey { + case isBreak + case lessonName + case lessonTheme + case roomName + case teacherName + case startTime + case endTime + case lessonNumber + case mode + case message + case season + case nextLessonName + case nextRoomName + case nextStartTime + case isSubstitution + case isCancelled + case substituteTeacher + case currentTime + case labels + case tokenExpirationWarning + case tokenExpired + case compactTimerText + case lessonIcon + } + + init(isBreak: Bool, lessonName: String, lessonTheme: String?, roomName: String?, teacherName: String?, startTime: Date, endTime: Date, lessonNumber: Int?, mode: String?, message: String?, season: String?, nextLessonName: String?, nextRoomName: String?, nextStartTime: Date?, isSubstitution: Bool, isCancelled: Bool, substituteTeacher: String?, currentTime: Date, labels: Labels? = nil, tokenExpirationWarning: String? = nil, tokenExpired: Bool? = nil, compactTimerText: String? = nil, lessonIcon: String? = nil) { + self.isBreak = isBreak + self.lessonName = lessonName + self.lessonTheme = lessonTheme + self.roomName = roomName + self.teacherName = teacherName + self.startTime = startTime + self.endTime = endTime + self.lessonNumber = lessonNumber + self.mode = mode + self.message = message + self.season = season + self.nextLessonName = nextLessonName + self.nextRoomName = nextRoomName + self.nextStartTime = nextStartTime + self.isSubstitution = isSubstitution + self.isCancelled = isCancelled + self.substituteTeacher = substituteTeacher + self.currentTime = currentTime + self.labels = labels + self.tokenExpirationWarning = tokenExpirationWarning + self.tokenExpired = tokenExpired + self.compactTimerText = compactTimerText + self.lessonIcon = lessonIcon + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let isoFormatter = ISO8601DateFormatter() + isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + isBreak = try container.decode(Bool.self, forKey: .isBreak) + lessonName = try container.decode(String.self, forKey: .lessonName) + lessonTheme = try container.decodeIfPresent(String.self, forKey: .lessonTheme) + roomName = try container.decodeIfPresent(String.self, forKey: .roomName) + teacherName = try container.decodeIfPresent(String.self, forKey: .teacherName) + + let startTimeStr = try container.decode(String.self, forKey: .startTime) + guard let startTimeDate = isoFormatter.date(from: startTimeStr) else { + throw DecodingError.dataCorruptedError(forKey: .startTime, in: container, debugDescription: "Invalid startTime format: \(startTimeStr)") + } + startTime = startTimeDate + + let endTimeStr = try container.decode(String.self, forKey: .endTime) + guard let endTimeDate = isoFormatter.date(from: endTimeStr) else { + throw DecodingError.dataCorruptedError(forKey: .endTime, in: container, debugDescription: "Invalid endTime format: \(endTimeStr)") + } + endTime = endTimeDate + + lessonNumber = try container.decodeIfPresent(Int.self, forKey: .lessonNumber) + mode = try container.decodeIfPresent(String.self, forKey: .mode) + message = try container.decodeIfPresent(String.self, forKey: .message) + season = try container.decodeIfPresent(String.self, forKey: .season) + nextLessonName = try container.decodeIfPresent(String.self, forKey: .nextLessonName) + nextRoomName = try container.decodeIfPresent(String.self, forKey: .nextRoomName) + + if let nextStartTimeStr = try container.decodeIfPresent(String.self, forKey: .nextStartTime) { + nextStartTime = isoFormatter.date(from: nextStartTimeStr) + } else { + nextStartTime = nil + } + + isSubstitution = try container.decode(Bool.self, forKey: .isSubstitution) + isCancelled = try container.decode(Bool.self, forKey: .isCancelled) + substituteTeacher = try container.decodeIfPresent(String.self, forKey: .substituteTeacher) + labels = try container.decodeIfPresent(Labels.self, forKey: .labels) + tokenExpirationWarning = try container.decodeIfPresent(String.self, forKey: .tokenExpirationWarning) + tokenExpired = try container.decodeIfPresent(Bool.self, forKey: .tokenExpired) + compactTimerText = try container.decodeIfPresent(String.self, forKey: .compactTimerText) + lessonIcon = try container.decodeIfPresent(String.self, forKey: .lessonIcon) + + let currentTimeStr = try container.decode(String.self, forKey: .currentTime) + guard let currentTimeDate = isoFormatter.date(from: currentTimeStr) else { + throw DecodingError.dataCorruptedError(forKey: .currentTime, in: container, debugDescription: "Invalid currentTime format: \(currentTimeStr)") + } + currentTime = currentTimeDate + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + let isoFormatter = ISO8601DateFormatter() + isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + try container.encode(isBreak, forKey: .isBreak) + try container.encode(lessonName, forKey: .lessonName) + try container.encodeIfPresent(lessonTheme, forKey: .lessonTheme) + try container.encodeIfPresent(roomName, forKey: .roomName) + try container.encodeIfPresent(teacherName, forKey: .teacherName) + + try container.encode(isoFormatter.string(from: startTime), forKey: .startTime) + try container.encode(isoFormatter.string(from: endTime), forKey: .endTime) + + try container.encodeIfPresent(lessonNumber, forKey: .lessonNumber) + try container.encodeIfPresent(mode, forKey: .mode) + try container.encodeIfPresent(message, forKey: .message) + try container.encodeIfPresent(season, forKey: .season) + try container.encodeIfPresent(nextLessonName, forKey: .nextLessonName) + try container.encodeIfPresent(nextRoomName, forKey: .nextRoomName) + + if let nextStartTime = nextStartTime { + try container.encode(isoFormatter.string(from: nextStartTime), forKey: .nextStartTime) + } + + try container.encode(isSubstitution, forKey: .isSubstitution) + try container.encode(isCancelled, forKey: .isCancelled) + try container.encodeIfPresent(substituteTeacher, forKey: .substituteTeacher) + try container.encodeIfPresent(labels, forKey: .labels) + try container.encodeIfPresent(tokenExpirationWarning, forKey: .tokenExpirationWarning) + try container.encodeIfPresent(tokenExpired, forKey: .tokenExpired) + try container.encodeIfPresent(compactTimerText, forKey: .compactTimerText) + try container.encodeIfPresent(lessonIcon, forKey: .lessonIcon) + + try container.encode(isoFormatter.string(from: currentTime), forKey: .currentTime) + } + } + + var studentName: String + var schoolName: String +} + +extension TimetableActivityAttributes.ContentState { + var timeRemaining: TimeInterval { + return endTime.timeIntervalSince(currentTime) + } + + var isBeforeSchool: Bool { + return currentTime < startTime && !isBreak + } + + var formattedStartTime: String { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + formatter.timeZone = TimeZone(identifier: "Europe/Budapest") + return formatter.string(from: startTime) + } + + var formattedEndTime: String { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + formatter.timeZone = TimeZone(identifier: "Europe/Budapest") + return formatter.string(from: endTime) + } + + var formattedNextStartTime: String { + guard let nextStartTime = nextStartTime else { return "" } + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + formatter.timeZone = TimeZone(identifier: "Europe/Budapest") + return formatter.string(from: nextStartTime) + } + + var timeRemainingText: String { + let remaining = timeRemaining + + if remaining < 0 { + return "0:00" + } + + let hours = Int(remaining) / 3600 + let minutes = (Int(remaining) % 3600) / 60 + let seconds = Int(remaining) % 60 + + if hours > 0 { + return String(format: "%d:%02d:%02d", hours, minutes, seconds) + } else if minutes > 0 { + return String(format: "%d:%02d", minutes, seconds) + } else { + return String(format: "0:%02d", seconds) + } + } + + var seasonalRemainingText: String { + if let remainingLabel = labels?.remainingLabel, let message = message, !message.isEmpty { + return "\(remainingLabel): \(message)" + } + + let remaining = max(0, timeRemaining) + let hours = Int(remaining) / 3600 + if hours >= 24 { + let days = hours / 24 + return "Szünetből hátralévő idő: \(days) nap" + } + return "Szünetből hátralévő idő: \(hours) óra" + } + + var seasonalDisplayValue: String { + if let message = message, !message.isEmpty { + return message + } + + let remaining = max(0, timeRemaining) + let hours = Int(remaining) / 3600 + if hours >= 24 { + let days = hours / 24 + return "\(days) nap" + } + return "\(hours) óra" + } +} + +extension TimetableActivityAttributes.ContentState { + func toJSON() -> [String: Any] { + var json: [String: Any] = [ + "isBreak": isBreak, + "lessonName": lessonName, + "startTime": ISO8601DateFormatter().string(from: startTime), + "endTime": ISO8601DateFormatter().string(from: endTime), + "isSubstitution": isSubstitution, + "isCancelled": isCancelled, + "currentTime": ISO8601DateFormatter().string(from: currentTime) + ] + + if let lessonTheme = lessonTheme { + json["lessonTheme"] = lessonTheme + } + if let roomName = roomName { + json["roomName"] = roomName + } + if let teacherName = teacherName { + json["teacherName"] = teacherName + } + if let lessonNumber = lessonNumber { + json["lessonNumber"] = lessonNumber + } + if let nextLessonName = nextLessonName { + json["nextLessonName"] = nextLessonName + } + if let nextRoomName = nextRoomName { + json["nextRoomName"] = nextRoomName + } + if let nextStartTime = nextStartTime { + json["nextStartTime"] = ISO8601DateFormatter().string(from: nextStartTime) + } + if let substituteTeacher = substituteTeacher { + json["substituteTeacher"] = substituteTeacher + } + if let mode = mode { + json["mode"] = mode + } + if let message = message { + json["message"] = message + } + if let season = season { + json["season"] = season + } + if let tokenExpirationWarning = tokenExpirationWarning { + json["tokenExpirationWarning"] = tokenExpirationWarning + } + if let tokenExpired = tokenExpired { + json["tokenExpired"] = tokenExpired + } + if let compactTimerText = compactTimerText { + json["compactTimerText"] = compactTimerText + } + if let lessonIcon = lessonIcon { + json["lessonIcon"] = lessonIcon + } + + return json + } + + static func fromJSON(_ json: [String: Any]) -> TimetableActivityAttributes.ContentState? { + let isoFormatter = ISO8601DateFormatter() + isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + guard let isBreak = json["isBreak"] as? Bool, + let lessonName = json["lessonName"] as? String, + let startTimeStr = json["startTime"] as? String, + let endTimeStr = json["endTime"] as? String, + let isSubstitution = json["isSubstitution"] as? Bool, + let isCancelled = json["isCancelled"] as? Bool, + let startTime = isoFormatter.date(from: startTimeStr), + let endTime = isoFormatter.date(from: endTimeStr) else { + return nil + } + + let currentTimeStr = json["currentTime"] as? String + let currentTime = currentTimeStr.flatMap { isoFormatter.date(from: $0) } ?? Date() + + let nextStartTime: Date? + if let nextStartTimeStr = json["nextStartTime"] as? String { + nextStartTime = isoFormatter.date(from: nextStartTimeStr) + } else { + nextStartTime = nil + } + + let labels: Labels? + if let labelsDict = json["labels"] as? [String: Any] { + labels = Labels( + title: labelsDict["title"] as? String, + timerLabel: labelsDict["timerLabel"] as? String, + cancelledText: labelsDict["cancelledText"] as? String, + substitutionText: labelsDict["substitutionText"] as? String, + roomLabel: labelsDict["roomLabel"] as? String, + teacherLabel: labelsDict["teacherLabel"] as? String, + themeLabel: labelsDict["themeLabel"] as? String, + nextLabel: labelsDict["nextLabel"] as? String, + firstLessonLabel: labelsDict["firstLessonLabel"] as? String, + startTimeLabel: labelsDict["startTimeLabel"] as? String, + lessonNumberLabel: labelsDict["lessonNumberLabel"] as? String, + nextRoomLabel: labelsDict["nextRoomLabel"] as? String, + remainingLabel: labelsDict["remainingLabel"] as? String + ) + } else { + labels = nil + } + + return TimetableActivityAttributes.ContentState( + isBreak: isBreak, + lessonName: lessonName, + lessonTheme: json["lessonTheme"] as? String, + roomName: json["roomName"] as? String, + teacherName: json["teacherName"] as? String, + startTime: startTime, + endTime: endTime, + lessonNumber: json["lessonNumber"] as? Int, + mode: json["mode"] as? String, + message: json["message"] as? String, + season: json["season"] as? String, + nextLessonName: json["nextLessonName"] as? String, + nextRoomName: json["nextRoomName"] as? String, + nextStartTime: nextStartTime, + isSubstitution: isSubstitution, + isCancelled: isCancelled, + substituteTeacher: json["substituteTeacher"] as? String, + currentTime: currentTime, + labels: labels, + tokenExpirationWarning: json["tokenExpirationWarning"] as? String, + tokenExpired: json["tokenExpired"] as? Bool, + compactTimerText: json["compactTimerText"] as? String, + lessonIcon: json["lessonIcon"] as? String + ) + } +} diff --git a/firka/ios/LiveActivityWidget/ActivityWidgetBundle.swift b/firka/ios/LiveActivityWidget/ActivityWidgetBundle.swift new file mode 100644 index 00000000..3bd64a59 --- /dev/null +++ b/firka/ios/LiveActivityWidget/ActivityWidgetBundle.swift @@ -0,0 +1,18 @@ +import WidgetKit +import SwiftUI + +@main +struct TimetableWidgetBundle: WidgetBundle { + var body: some Widget { + if #available(iOS 18.0, *) { + TimetableLiveActivity() + } + + if #available(iOS 16.2, *), + !ProcessInfo.processInfo.isOperatingSystemAtLeast( + OperatingSystemVersion(majorVersion: 18, minorVersion: 0, patchVersion: 0) + ) { + TimetableLiveActivityLegacy() + } + } +} diff --git a/firka/ios/LiveActivityWidget/Assets.xcassets/AccentColor.colorset/Contents.json b/firka/ios/LiveActivityWidget/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/LiveActivityWidget/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/LiveActivityWidget/Assets.xcassets/AppIcon.appiconset/Contents.json b/firka/ios/LiveActivityWidget/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..23058801 --- /dev/null +++ b/firka/ios/LiveActivityWidget/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,35 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/LiveActivityWidget/Assets.xcassets/Contents.json b/firka/ios/LiveActivityWidget/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/firka/ios/LiveActivityWidget/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/LiveActivityWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/firka/ios/LiveActivityWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/firka/ios/LiveActivityWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/LiveActivityWidget/Info.plist b/firka/ios/LiveActivityWidget/Info.plist new file mode 100644 index 00000000..0f118fb7 --- /dev/null +++ b/firka/ios/LiveActivityWidget/Info.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/firka/ios/LiveActivityWidget/LiveActivity.swift b/firka/ios/LiveActivityWidget/LiveActivity.swift new file mode 100644 index 00000000..84003736 --- /dev/null +++ b/firka/ios/LiveActivityWidget/LiveActivity.swift @@ -0,0 +1,921 @@ +import ActivityKit +import WidgetKit +import SwiftUI + +@available(iOS 18.0, *) +struct TimetableLiveActivity: Widget { + var body: some WidgetConfiguration { + TimetableLiveActivityLegacy.activityConfiguration + .supplementalActivityFamilies([.small]) + } +} + +@available(iOS 16.2, *) +struct TimetableLiveActivityLegacy: Widget { + var body: some WidgetConfiguration { + Self.activityConfiguration + } + + static var activityConfiguration: ActivityConfiguration { + ActivityConfiguration(for: TimetableActivityAttributes.self) { context in + // Lock screen/banner UI + TimetableLiveActivityAdaptiveView(context: context) + .activityBackgroundTint(Color(red: 0.1, green: 0.15, blue: 0.1)) + .activitySystemActionForegroundColor(Color.white) + } dynamicIsland: { context in + let mode = context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + let timeFormatter = DateFormatter() + timeFormatter.dateFormat = "HH:mm" + + return DynamicIsland { + // Expanded UI + DynamicIslandExpandedRegion(.leading) { + EmptyView() + } + + DynamicIslandExpandedRegion(.trailing) { + let beforeSchoolTime = mode == "beforeSchool" ? { + let adjustedDate = context.state.endTime + return timeFormatter.string(from: adjustedDate) + }() : nil + + if SeasonalIconHelper.isSeasonalMode(mode) { + EmptyView() + } else if mode == "beforeSchool", let timeString = beforeSchoolTime { + Text("\(context.state.labels?.startTimeLabel ?? "Kezdés:") \(timeString)") + .font(.system(size: 14, weight: .medium)) + .foregroundColor(.gray) + } else { + Text(context.state.formattedStartTime + " - " + context.state.formattedEndTime) + .font(.system(size: 14, weight: .medium)) + .foregroundColor(.gray) + } + } + + DynamicIslandExpandedRegion(.center) { + let season = context.state.season ?? "" + VStack(spacing: 4) { + if mode == "beforeSchool" { + HStack(alignment: .center, spacing: 6) { + Image(systemName: SeasonalIconHelper.iconName(for: mode, season: season, lessonIcon: context.state.lessonIcon)) + .font(.system(size: 18)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + Text(context.state.labels?.title ?? "Hamarosan suli") + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + } + + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 4) { + Text(context.state.labels?.firstLessonLabel ?? "Első órád:") + .font(.system(size: 12)) + .foregroundColor(.gray) + Text(context.state.lessonName) + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.white) + } + + if let roomName = context.state.roomName { + HStack(spacing: 4) { + Text(context.state.labels?.roomLabel ?? "Terem:") + .font(.system(size: 12)) + .foregroundColor(.gray) + Text(roomName) + .font(.system(size: 12)) + .foregroundColor(.white) + } + } + + if let teacherName = context.state.teacherName { + HStack(spacing: 4) { + Text(context.state.labels?.teacherLabel ?? "Tanár:") + .font(.system(size: 12)) + .foregroundColor(.gray) + Text(teacherName) + .font(.system(size: 12)) + .foregroundColor(.white) + } + } + } + } else if SeasonalIconHelper.isSeasonalMode(mode) { + if mode == "xmas" || mode == "newYearEve" || mode == "newYearDay" { + HStack(alignment: .center, spacing: 6) { + Image(systemName: SeasonalIconHelper.iconName(for: mode, season: season)) + .font(.system(size: 18)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + Text(context.state.message ?? "Szünet") + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + .lineLimit(2) + } + } else { + HStack(alignment: .center, spacing: 6) { + Image(systemName: SeasonalIconHelper.iconName(for: mode, season: season)) + .font(.system(size: 18)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + Text(context.state.labels?.title ?? context.state.lessonName) + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + } + } + } else if context.state.isBreak { + HStack(alignment: .center, spacing: 6) { + Image(systemName: "cup.and.saucer.fill") + .font(.system(size: 18)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + Text(context.state.labels?.title ?? "Szünet") + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + } + + if let nextLessonName = context.state.nextLessonName { + HStack(spacing: 4) { + Text(context.state.labels?.nextLabel ?? "Következő:") + .font(.system(size: 14)) + .foregroundColor(.gray) + Text(nextLessonName) + .font(.system(size: 14, weight: .semibold)) + .foregroundColor(.white) + } + } + + if let nextRoomName = context.state.nextRoomName { + Text("\(context.state.labels?.roomLabel ?? "Terem:") \(nextRoomName)") + .font(.system(size: 12)) + .foregroundColor(.gray) + } + } else { + HStack(alignment: .center, spacing: 6) { + if let lessonNumber = context.state.lessonNumber { + Text("\(lessonNumber).") + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + } + Text(context.state.lessonName) + .font(.system(size: 18, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + } + + if !(context.state.isCancelled ?? false) { + if let lessonTheme = context.state.lessonTheme, !lessonTheme.isEmpty { + Text(lessonTheme) + .font(.system(size: 12)) + .foregroundColor(.gray) + .lineLimit(1) + } + } + + HStack(spacing: 8) { + if let roomName = context.state.roomName { + Label(roomName, systemImage: "door.left.hand.closed") + .font(.system(size: 12)) + .foregroundColor(.gray) + } + + if context.state.isSubstitution ?? false { + Label(context.state.labels?.substitutionText ?? "Helyettesítés", systemImage: "arrow.triangle.2.circlepath") + .font(.system(size: 12)) + .foregroundColor(.orange) + } + } + } + } + } + + DynamicIslandExpandedRegion(.bottom) { + let season = context.state.season ?? "" + VStack(spacing: 4) { + HStack { + Spacer() + if mode == "xmas" || mode == "newYearDay" { + EmptyView() + } else if mode == "beforeSchool" { + if context.state.endTime > context.state.currentTime { + Text(timerInterval: context.state.currentTime...context.state.endTime, countsDown: true) + .font(.system(size: 24, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } else { + Text(context.state.formattedEndTime) + .font(.system(size: 24, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } + } else if mode == "seasonalBreak" { + Text(context.state.seasonalRemainingText) + .font(.system(size: 18, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } else if context.state.isCancelled ?? false { + Text(context.state.labels?.cancelledText ?? "Elmaradt") + .font(.system(size: 20, weight: .bold, design: .rounded)) + .foregroundColor(.red) + .multilineTextAlignment(.center) + } else { + Text(timerInterval: context.state.currentTime...context.state.endTime, countsDown: true) + .font(.system(size: 24, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } + Spacer() + } + + // Token expiration warning (only for specific modes) + let mode3 = context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + let showWarningModes = ["newYearEve", "lesson", "break", "seasonalBreak"] + if let warning = context.state.tokenExpirationWarning, !warning.isEmpty, showWarningModes.contains(mode3) { + let isExpired = context.state.tokenExpired ?? false + let warningColor: Color = isExpired ? .red : .orange + let warningIcon = isExpired ? "exclamationmark.circle.fill" : "exclamationmark.triangle.fill" + + HStack(spacing: 3) { + Image(systemName: warningIcon) + .font(.system(size: 8)) + .foregroundColor(warningColor) + Text(warning) + .font(.system(size: 8, weight: .semibold)) + .foregroundColor(warningColor) + .lineLimit(1) + .minimumScaleFactor(0.6) + } + } + } + } + } compactLeading: { + let season = context.state.season ?? "" + let iconName: String = { + if SeasonalIconHelper.isSeasonalMode(mode) || mode == "beforeSchool" { + return SeasonalIconHelper.iconName(for: mode, season: season, lessonIcon: context.state.lessonIcon) + } else { + return context.state.isBreak ? "cup.and.saucer.fill" : (context.state.lessonIcon ?? "book.fill") + } + }() + Image(systemName: iconName) + .font(.system(size: 14)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + } compactTrailing: { + let season = context.state.season ?? "" + if mode == "xmas" || mode == "newYearDay" { + Text("") + .frame(width: 50) + } else if context.state.isCancelled ?? false { + Text("❌") + .font(.system(size: 12, weight: .semibold)) + .frame(width: 50) + } else if let compactText = context.state.compactTimerText { + Text(compactText) + .font(.system(size: 12, weight: .semibold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .frame(width: 50) + } else { + Text("") + .frame(width: 50) + } + } minimal: { + let season = context.state.season ?? "" + let iconName: String = { + if SeasonalIconHelper.isSeasonalMode(mode) || mode == "beforeSchool" { + return SeasonalIconHelper.iconName(for: mode, season: season, lessonIcon: context.state.lessonIcon) + } else { + return context.state.isBreak ? "cup.and.saucer.fill" : (context.state.lessonIcon ?? "book.fill") + } + }() + Image(systemName: iconName) + .font(.system(size: 12)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + } + } + } + } + +@available(iOS 16.2, *) +struct TimetableLiveActivityAdaptiveView: View { + let context: ActivityViewContext + + var body: some View { + if #available(iOS 18.0, *) { + TimetableLiveActivityFamilyView(context: context) + } else { + TimetableLiveActivityView(context: context) + } + } +} + +@available(iOS 18.0, *) +struct TimetableLiveActivityFamilyView: View { + @Environment(\.activityFamily) private var activityFamily + let context: ActivityViewContext + + var body: some View { + switch activityFamily { + case .small: + SmallActivityView(context: context) + case .medium: + TimetableLiveActivityView(context: context) + @unknown default: + TimetableLiveActivityView(context: context) + } + } +} + +// MARK: - Lock Screen View +@available(iOS 16.2, *) +struct TimetableLiveActivityView: View { + let context: ActivityViewContext + + var body: some View { + let mode = context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + VStack(spacing: 12) { + let season = context.state.season ?? "" + let screenTimeFormatter = DateFormatter() + let _ = { screenTimeFormatter.dateFormat = "HH:mm" }() + + let beforeSchoolTime: String? = mode == "beforeSchool" ? { + let adjustedDate = context.state.endTime + return screenTimeFormatter.string(from: adjustedDate) + }() : nil + let iconName: String = { + if SeasonalIconHelper.isSeasonalMode(mode) || mode == "beforeSchool" { + return SeasonalIconHelper.iconName(for: mode, season: season, lessonIcon: context.state.lessonIcon) + } else { + return context.state.isBreak ? "cup.and.saucer.fill" : (context.state.lessonIcon ?? "book.fill") + } + }() + + // Header + HStack { + Image(systemName: iconName) + .font(.system(size: 24)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + + VStack(alignment: .leading, spacing: 2) { + if mode == "beforeSchool" { + Text(context.state.labels?.title ?? "Hamarosan suli") + .font(.system(size: 20, weight: .bold)) + .foregroundColor(.white) + } else if SeasonalIconHelper.isSeasonalMode(mode) { + if mode == "xmas" || mode == "newYearEve" || mode == "newYearDay" { + Text(context.state.message ?? context.state.lessonName) + .font(.system(size: 20, weight: .bold)) + .foregroundColor(.white) + .lineLimit(2) + } else { + Text(context.state.labels?.title ?? context.state.lessonName) + .font(.system(size: 20, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + } + } else if context.state.isBreak { + Text(context.state.labels?.title ?? "Szünet") + .font(.system(size: 20, weight: .bold)) + .foregroundColor(.white) + if let nextLessonName = context.state.nextLessonName { + Text("\(context.state.labels?.nextLabel ?? "Következő:") \(nextLessonName)") + .font(.system(size: 14)) + .foregroundColor(.gray) + } + } else { + if let lessonNumber = context.state.lessonNumber { + Text("\(lessonNumber)\(context.state.labels?.lessonNumberLabel ?? ". óra")") + .font(.system(size: 12)) + .foregroundColor(.gray) + } + Text(context.state.lessonName) + .font(.system(size: 20, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + } + } + + Spacer() + + VStack(alignment: .trailing, spacing: 2) { + if SeasonalIconHelper.isSeasonalMode(mode) { + EmptyView() + } else if mode == "beforeSchool", let timeString = beforeSchoolTime { + Text("\(context.state.labels?.startTimeLabel ?? "Kezdés:") \(timeString)") + .font(.system(size: 14, weight: .medium)) + .foregroundColor(.white) + } else { + Text(context.state.formattedStartTime + " - " + context.state.formattedEndTime) + .font(.system(size: 14, weight: .medium)) + .foregroundColor(.white) + } + + if SeasonalIconHelper.isSeasonalMode(mode) { + EmptyView() + } else if mode == "beforeSchool" { + EmptyView() + } else if context.state.isBreak { + if let _ = context.state.nextStartTime { + Text("\(context.state.labels?.startTimeLabel ?? "Kezdés:") \(context.state.formattedNextStartTime)") + .font(.system(size: 12)) + .foregroundColor(.gray) + } else { + EmptyView() + } + } else { + if let roomName = context.state.roomName { + HStack(spacing: 4) { + Image(systemName: "door.left.hand.closed") + .font(.system(size: 10)) + Text(roomName) + .font(.system(size: 12)) + } + .foregroundColor(.gray) + } else { + EmptyView() + } + } + } + } + + // Content + let mode2 = context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + if mode2 == "beforeSchool" { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 4) { + Text(context.state.labels?.firstLessonLabel ?? "Első órád:") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.gray) + Text(context.state.lessonName) + .font(.system(size: 12)) + .foregroundColor(.white) + } + + if let roomName = context.state.roomName { + HStack(spacing: 4) { + Text(context.state.labels?.roomLabel ?? "Terem:") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.gray) + Text(roomName) + .font(.system(size: 12)) + .foregroundColor(.white) + } + } + + if let teacherName = context.state.teacherName { + HStack(spacing: 4) { + Text(context.state.labels?.teacherLabel ?? "Tanár:") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.gray) + Text(teacherName) + .font(.system(size: 12)) + .foregroundColor(.white) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if SeasonalIconHelper.isSeasonalMode(mode2) { + EmptyView() + } else if !context.state.isBreak { + VStack(alignment: .leading, spacing: 4) { + if !(context.state.isCancelled ?? false) { + if let lessonTheme = context.state.lessonTheme, !lessonTheme.isEmpty { + HStack { + Text(context.state.labels?.themeLabel ?? "Téma:") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.gray) + Text(lessonTheme) + .font(.system(size: 12)) + .foregroundColor(.white) + .lineLimit(1) + } + } + } + + if context.state.isSubstitution ?? false { + HStack(spacing: 4) { + Image(systemName: "arrow.triangle.2.circlepath") + .font(.system(size: 12)) + Text(context.state.labels?.substitutionText ?? "Helyettesítés") + .font(.system(size: 12, weight: .semibold)) + if let substituteTeacher = context.state.substituteTeacher { + Text("(\(substituteTeacher))") + .font(.system(size: 12)) + } + } + .foregroundColor(.orange) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else if let nextRoomName = context.state.nextRoomName { + HStack { + Image(systemName: "door.left.hand.closed") + .font(.system(size: 12)) + .foregroundColor(.gray) + Text("\(context.state.labels?.nextRoomLabel ?? "Következő terem:") \(nextRoomName)") + .font(.system(size: 12)) + .foregroundColor(.gray) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + // Countdown Timer + HStack { + Spacer() + VStack(spacing: 4) { + let mode3 = context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + if mode3 == "xmas" || mode3 == "newYearDay" { + EmptyView() + } else if mode3 == "beforeSchool" { + Text(context.state.labels?.timerLabel ?? "Első óra kezdése") + .font(.system(size: 10)) + .foregroundColor(.gray) + + if context.state.endTime > context.state.currentTime { + Text(timerInterval: context.state.currentTime...context.state.endTime, countsDown: true) + .font(.system(size: 32, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode3, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } else { + Text(context.state.formattedEndTime) + .font(.system(size: 32, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode3, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } + } else if mode3 == "seasonalBreak" { + Text(context.state.labels?.remainingLabel ?? "Szünetből hátralévő idő") + .font(.system(size: 10)) + .foregroundColor(.gray) + Text(context.state.seasonalDisplayValue) + .font(.system(size: 32, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode3, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } else { + if context.state.isCancelled ?? false { + Text(context.state.labels?.cancelledText ?? "Elmaradt") + .font(.system(size: 32, weight: .bold, design: .rounded)) + .foregroundColor(.red) + .multilineTextAlignment(.center) + } else { + let labelText: String = { + if mode3 == "newYearEve" { + return context.state.labels?.timerLabel ?? "Új év" + } else if mode3 == "beforeSchool" { + return context.state.labels?.timerLabel ?? "Első óra kezdése" + } else if context.state.isBreak { + return context.state.labels?.timerLabel ?? "Szünet vége" + } else { + return context.state.labels?.timerLabel ?? "Óra vége" + } + }() + Text(labelText) + .font(.system(size: 10)) + .foregroundColor(.gray) + Text(timerInterval: context.state.currentTime...context.state.endTime, countsDown: true) + .font(.system(size: 32, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode3, season: season)) + .multilineTextAlignment(.center) + .monospacedDigit() + } + } + } + Spacer() + } + + // Token expiration warning (only for specific modes) + let showWarningModes = ["newYearEve", "lesson", "break", "seasonalBreak"] + if let warning = context.state.tokenExpirationWarning, !warning.isEmpty, showWarningModes.contains(mode) { + let isExpired = context.state.tokenExpired ?? false + let warningColor: Color = isExpired ? .red : .orange + let warningIcon = isExpired ? "exclamationmark.circle.fill" : "exclamationmark.triangle.fill" + + HStack(spacing: 4) { + Image(systemName: warningIcon) + .font(.system(size: 10)) + .foregroundColor(warningColor) + Text(warning) + .font(.system(size: 10, weight: .semibold)) + .foregroundColor(warningColor) + .lineLimit(1) + .minimumScaleFactor(0.7) + } + .padding(.top, 2) + } + } + .padding(16) + } +} + +@available(iOS 18.0, *) +struct SmallActivityView: View { + let context: ActivityViewContext + + private var mode: String { + context.state.mode ?? (context.state.isBreak ? "break" : "lesson") + } + + private var season: String { + context.state.season ?? "" + } + + private var titleText: String { + switch mode { + case "beforeSchool": + return firstNonEmpty([ + trimmedOrNil(context.state.labels?.title), + trimmedOrNil(context.state.lessonName), + trimmedOrNil(context.state.message), + ]) ?? "" + case "xmas", "newYearEve", "newYearDay": + return firstNonEmpty([ + trimmedOrNil(context.state.message), + trimmedOrNil(context.state.lessonName), + trimmedOrNil(context.state.labels?.title), + ]) ?? "" + case "seasonalBreak": + return firstNonEmpty([ + trimmedOrNil(context.state.labels?.title), + trimmedOrNil(context.state.lessonName), + trimmedOrNil(context.state.message), + ]) ?? "" + case "break": + return firstNonEmpty([ + trimmedOrNil(context.state.labels?.title), + trimmedOrNil(context.state.message), + ]) ?? "" + default: + return firstNonEmpty([ + trimmedOrNil(context.state.lessonName), + trimmedOrNil(context.state.labels?.title), + trimmedOrNil(context.state.message), + ]) ?? "" + } + } + + private var iconName: String { + if SeasonalIconHelper.isSeasonalMode(mode) || mode == "beforeSchool" { + return SeasonalIconHelper.iconName(for: mode, season: season, lessonIcon: context.state.lessonIcon) + } + + return context.state.isBreak ? "cup.and.saucer.fill" : (context.state.lessonIcon ?? "book.fill") + } + + private var warningState: (text: String, color: Color, icon: String)? { + let showWarningModes = ["newYearEve", "lesson", "break", "seasonalBreak"] + guard showWarningModes.contains(mode), + let warningText = trimmedOrNil(context.state.tokenExpirationWarning) else { + return nil + } + + let isExpired = context.state.tokenExpired ?? false + return ( + text: warningText, + color: isExpired ? .red : .orange, + icon: isExpired ? "exclamationmark.circle.fill" : "exclamationmark.triangle.fill" + ) + } + + var body: some View { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 5) { + Image(systemName: iconName) + .font(.system(size: 14)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + + if mode == "lesson", let lessonNumber = context.state.lessonNumber { + Text("\(lessonNumber). \(titleText)") + .font(.system(size: 12, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + .minimumScaleFactor(0.65) + .truncationMode(.tail) + } else { + Text(titleText) + .font(.system(size: 12, weight: .bold)) + .foregroundColor(.white) + .lineLimit(1) + .minimumScaleFactor(0.65) + .truncationMode(.tail) + } + + Spacer(minLength: 0) + } + + detailsSection + + Spacer(minLength: 0) + + timerSection + + if let warningState = warningState { + HStack(spacing: 3) { + Image(systemName: warningState.icon) + .font(.system(size: 8)) + .foregroundColor(warningState.color) + + Text(warningState.text) + .font(.system(size: 8, weight: .semibold)) + .foregroundColor(warningState.color) + .lineLimit(1) + .minimumScaleFactor(0.55) + .truncationMode(.tail) + } + .padding(.top, 1) + } + } + .padding(10) + } + + @ViewBuilder + private var detailsSection: some View { + switch mode { + case "beforeSchool": + labeledDetailLine( + label: context.state.labels?.firstLessonLabel, + value: context.state.lessonName, + color: .white, + weight: .semibold + ) + labeledDetailLine( + label: context.state.labels?.teacherLabel, + value: context.state.teacherName, + color: .white, + weight: .semibold + ) + labeledDetailLine( + label: context.state.labels?.roomLabel, + value: context.state.roomName, + color: .white, + weight: .semibold + ) + + case "lesson": + if context.state.isSubstitution ?? false { + if let substitution = trimmedOrNil(context.state.labels?.substitutionText) { + if let substituteTeacher = trimmedOrNil(context.state.substituteTeacher) { + detailLine("\(substitution) (\(substituteTeacher))", color: .orange) + } else { + detailLine(substitution, color: .orange) + } + } + } + + case "break": + labeledDetailLine( + label: context.state.labels?.nextLabel, + value: context.state.nextLessonName, + color: .white, + weight: .semibold + ) + labeledDetailLine( + label: context.state.labels?.roomLabel, + value: context.state.nextRoomName, + color: .white, + weight: .semibold + ) + + case "seasonalBreak": + if let remainingLabel = trimmedOrNil(context.state.labels?.remainingLabel) { + detailLine(remainingLabel) + } + + default: + EmptyView() + } + } + + @ViewBuilder + private var timerSection: some View { + switch mode { + case "xmas", "newYearDay": + EmptyView() + + case "seasonalBreak": + if let remainingLabel = trimmedOrNil(context.state.labels?.remainingLabel) { + timerLabelLine(remainingLabel) + } + timerValueText(context.state.seasonalDisplayValue) + + case "newYearEve", "beforeSchool": + if let timerLabel = trimmedOrNil(context.state.labels?.timerLabel) { + if mode == "beforeSchool" { + timerLabelLine(timerLabel, color: .white, weight: .semibold) + } else { + timerLabelLine(timerLabel) + } + } + countdownValueView() + + case "lesson", "break", "loading": + if context.state.isCancelled ?? false { + if let cancelled = trimmedOrNil(context.state.labels?.cancelledText) { + timerValueText(cancelled, color: .red) + } + } else { + if let timerLabel = trimmedOrNil(context.state.labels?.timerLabel) { + if mode == "lesson" || mode == "break" { + timerLabelLine(timerLabel, color: .white, weight: .semibold) + } else { + timerLabelLine(timerLabel) + } + } + countdownValueView() + } + + default: + countdownValueView() + } + } + + @ViewBuilder + private func labeledDetailLine( + label: String?, + value: String?, + color: Color = .gray, + weight: Font.Weight = .regular + ) -> some View { + if let text = joinedLabelValue(label: label, value: value) { + detailLine(text, color: color, weight: weight) + } + } + + @ViewBuilder + private func countdownValueView() -> some View { + if context.state.endTime > context.state.currentTime { + Text(timerInterval: context.state.currentTime...context.state.endTime, countsDown: true) + .font(.system(size: 16, weight: .bold, design: .rounded)) + .foregroundColor(SeasonalIconHelper.iconColor(for: mode, season: season)) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.75) + .frame(maxWidth: .infinity, alignment: .leading) + } else { + timerValueText(context.state.formattedEndTime) + } + } + + private func detailLine( + _ text: String, + color: Color = .gray, + weight: Font.Weight = .regular + ) -> some View { + Text(text) + .font(.system(size: 9, weight: weight)) + .foregroundColor(color) + .lineLimit(1) + .minimumScaleFactor(0.6) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private func timerLabelLine( + _ text: String, + color: Color = .gray, + weight: Font.Weight = .regular + ) -> some View { + Text(text) + .font(.system(size: 8, weight: weight)) + .foregroundColor(color) + .lineLimit(1) + .minimumScaleFactor(0.65) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private func timerValueText(_ text: String, color: Color? = nil) -> some View { + Text(text) + .font(.system(size: 16, weight: .bold, design: .rounded)) + .foregroundColor(color ?? SeasonalIconHelper.iconColor(for: mode, season: season)) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.75) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private func joinedLabelValue(label: String?, value: String?) -> String? { + guard let value = trimmedOrNil(value) else { return nil } + + if let label = trimmedOrNil(label) { + return "\(label) \(value)" + } + + return value + } + + private func firstNonEmpty(_ values: [String?]) -> String? { + for value in values { + if let value = value, !value.isEmpty { + return value + } + } + return nil + } + + private func trimmedOrNil(_ value: String?) -> String? { + guard let value else { return nil } + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } +} diff --git a/firka/ios/Podfile b/firka/ios/Podfile new file mode 100644 index 00000000..6649374d --- /dev/null +++ b/firka/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +platform :ios, '15.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/firka/ios/Runner.xcodeproj/project.pbxproj b/firka/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..40246cf3 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,2021 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 14578EED4EA309B337AB389E /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A749415A687CBFC3F46FA876 /* Pods_RunnerTests.framework */; }; + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 213F8C0F6B5418B02DE14204 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 035E9CCBCC6585D0F5639031 /* Pods_Runner.framework */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 4F27D4D22F3F2F7700749B9A /* SharedKeychainManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */; }; + 4F27D4D32F3F2F7700749B9A /* SharedKeychainManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */; }; + 4F30C7592E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F30C7582E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift */; }; + 4F30C7672E8FBF9D008BB46C /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7662E8FBF9D008BB46C /* WidgetKit.framework */; }; + 4F30C7692E8FBF9D008BB46C /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7682E8FBF9D008BB46C /* SwiftUI.framework */; }; + 4F30C7782E8FBF9F008BB46C /* LiveActivityWidget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 4F30C7652E8FBF9D008BB46C /* LiveActivityWidget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 4F45A1752F27FA3C0020E6F1 /* HomeWidgetMethodChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F45A1732F27FA3C0020E6F1 /* HomeWidgetMethodChannel.swift */; }; + 4F5824832F3548B800B92EA7 /* WatchToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F5824822F3548B800B92EA7 /* WatchToken.swift */; }; + 4F5824842F3548B800B92EA7 /* WatchToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F5824822F3548B800B92EA7 /* WatchToken.swift */; }; + 4F5965F82F2F0C1600A3DB03 /* WatchSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F5965F72F2F0C1600A3DB03 /* WatchSessionManager.swift */; }; + 4F5965FE2F2F0EAF00A3DB03 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7662E8FBF9D008BB46C /* WidgetKit.framework */; }; + 4F5965FF2F2F0EAF00A3DB03 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7682E8FBF9D008BB46C /* SwiftUI.framework */; }; + 4F59660F2F2F0F3B00A3DB03 /* SeasonalIconHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */; }; + 4F5966102F2F0F4100A3DB03 /* Average.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D02F2EC1AA00B79171 /* Average.swift */; }; + 4F5966112F2F0F4500A3DB03 /* Grade.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D12F2EC1AA00B79171 /* Grade.swift */; }; + 4F5966122F2F0F4900A3DB03 /* Lesson.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D22F2EC1AA00B79171 /* Lesson.swift */; }; + 4F5966132F2F0F4C00A3DB03 /* Subject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D32F2EC1AA00B79171 /* Subject.swift */; }; + 4F5966142F2F0F5100A3DB03 /* WidgetColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */; }; + 4F5966152F2F0F5500A3DB03 /* WidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */; }; + 4F5966172F2F1BBF00A3DB03 /* FirkaWatchComplicationsExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 4F5965FD2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 4F7701D82F2EC1AA00B79171 /* Grade.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D12F2EC1AA00B79171 /* Grade.swift */; }; + 4F7701D92F2EC1AA00B79171 /* WidgetColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */; }; + 4F7701DA2F2EC1AA00B79171 /* Average.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D02F2EC1AA00B79171 /* Average.swift */; }; + 4F7701DB2F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */; }; + 4F7701DC2F2EC1AA00B79171 /* Lesson.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D22F2EC1AA00B79171 /* Lesson.swift */; }; + 4F7701DD2F2EC1AA00B79171 /* Subject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D32F2EC1AA00B79171 /* Subject.swift */; }; + 4F7701DE2F2EC1AA00B79171 /* WidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */; }; + 4F7701DF2F2EC1AA00B79171 /* Grade.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D12F2EC1AA00B79171 /* Grade.swift */; }; + 4F7701E02F2EC1AA00B79171 /* WidgetColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */; }; + 4F7701E12F2EC1AA00B79171 /* Average.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D02F2EC1AA00B79171 /* Average.swift */; }; + 4F7701E22F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */; }; + 4F7701E32F2EC1AA00B79171 /* Lesson.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D22F2EC1AA00B79171 /* Lesson.swift */; }; + 4F7701E42F2EC1AA00B79171 /* Subject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D32F2EC1AA00B79171 /* Subject.swift */; }; + 4F7701E52F2EC1AA00B79171 /* WidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */; }; + 4F7701E62F2EC1AA00B79171 /* Grade.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D12F2EC1AA00B79171 /* Grade.swift */; }; + 4F7701E72F2EC1AA00B79171 /* WidgetColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */; }; + 4F7701E82F2EC1AA00B79171 /* Average.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D02F2EC1AA00B79171 /* Average.swift */; }; + 4F7701E92F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */; }; + 4F7701EA2F2EC1AA00B79171 /* Lesson.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D22F2EC1AA00B79171 /* Lesson.swift */; }; + 4F7701EB2F2EC1AA00B79171 /* Subject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D32F2EC1AA00B79171 /* Subject.swift */; }; + 4F7701EC2F2EC1AA00B79171 /* WidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */; }; + 4F7701EF2F2EC2F500B79171 /* TokenManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701EE2F2EC2F500B79171 /* TokenManager.swift */; }; + 4F7701F02F2EC2F500B79171 /* KretaAPIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F7701ED2F2EC2F500B79171 /* KretaAPIClient.swift */; }; + 4FCB030D2F330F3B00418E63 /* KretaAPIModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FCB030C2F330F3B00418E63 /* KretaAPIModels.swift */; }; + 4FE64E342F27B07A006F9205 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7662E8FBF9D008BB46C /* WidgetKit.framework */; }; + 4FE64E352F27B07A006F9205 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F30C7682E8FBF9D008BB46C /* SwiftUI.framework */; }; + 4FE64E422F27B07B006F9205 /* HomeWidgetsExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 4FE64E332F27B079006F9205 /* HomeWidgetsExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 4FF81B9A2F2EB4C300E95BA0 /* FirkaWatch Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 4FF81B7A2F2EB4C100E95BA0 /* FirkaWatch Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + AA00000100000005AABBCC05 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = AA00000100000004AABBCC04 /* Localizable.strings */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; + 4F30C7762E8FBF9F008BB46C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4F30C7642E8FBF9D008BB46C; + remoteInfo = TimetableWidgetExtension; + }; + 4F5966182F2F1BBF00A3DB03 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4F5965FC2F2F0EAF00A3DB03; + remoteInfo = FirkaWatchComplicationsExtension; + }; + 4F59661B2F2F1BD900A3DB03 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4F5965FC2F2F0EAF00A3DB03; + remoteInfo = FirkaWatchComplicationsExtension; + }; + 4F59661D2F2F1BE700A3DB03 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4F5965FC2F2F0EAF00A3DB03; + remoteInfo = FirkaWatchComplicationsExtension; + }; + 4FE64E402F27B07B006F9205 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4FE64E322F27B079006F9205; + remoteInfo = HomeWidgetsExtensionExtension; + }; + 4FF81B982F2EB4C300E95BA0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4FF81B792F2EB4C100E95BA0; + remoteInfo = "FirkaWatch Watch App"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 4F30C77E2E8FBF9F008BB46C /* Embed Foundation Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 4F30C7782E8FBF9F008BB46C /* LiveActivityWidget.appex in Embed Foundation Extensions */, + 4FE64E422F27B07B006F9205 /* HomeWidgetsExtension.appex in Embed Foundation Extensions */, + ); + name = "Embed Foundation Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; + 4F59661A2F2F1BBF00A3DB03 /* Embed Foundation Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 4F5966172F2F1BBF00A3DB03 /* FirkaWatchComplicationsExtension.appex in Embed Foundation Extensions */, + ); + name = "Embed Foundation Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; + 4FF81B9B2F2EB4C300E95BA0 /* Embed Watch Content */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "$(CONTENTS_FOLDER_PATH)/Watch"; + dstSubfolderSpec = 16; + files = ( + 4FF81B9A2F2EB4C300E95BA0 /* FirkaWatch Watch App.app in Embed Watch Content */, + ); + name = "Embed Watch Content"; + runOnlyForDeploymentPostprocessing = 0; + }; + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 035E9CCBCC6585D0F5639031 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 248F3DE56A05CAECFEBD617C /* 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 = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 4836947EC3B04B475B3DA1F8 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 485F3791F25A288C749509B2 /* 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 = ""; }; + 4F25FCBD2EB1790E0060DAAA /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + 4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedKeychainManager.swift; sourceTree = ""; }; + 4F30C7582E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityMethodChannelManager.swift; sourceTree = ""; }; + 4F30C7652E8FBF9D008BB46C /* LiveActivityWidget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = LiveActivityWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 4F30C7662E8FBF9D008BB46C /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; }; + 4F30C7682E8FBF9D008BB46C /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; }; + 4F45A1732F27FA3C0020E6F1 /* HomeWidgetMethodChannel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeWidgetMethodChannel.swift; sourceTree = ""; }; + 4F5824822F3548B800B92EA7 /* WatchToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchToken.swift; sourceTree = ""; }; + 4F5965F72F2F0C1600A3DB03 /* WatchSessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchSessionManager.swift; sourceTree = ""; }; + 4F5965FD2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = FirkaWatchComplicationsExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 4F5966162F2F0F6500A3DB03 /* FirkaWatchComplicationsExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = FirkaWatchComplicationsExtension.entitlements; sourceTree = ""; }; + 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SeasonalIconHelper.swift; sourceTree = ""; }; + 4F7701D02F2EC1AA00B79171 /* Average.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Average.swift; sourceTree = ""; }; + 4F7701D12F2EC1AA00B79171 /* Grade.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Grade.swift; sourceTree = ""; }; + 4F7701D22F2EC1AA00B79171 /* Lesson.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Lesson.swift; sourceTree = ""; }; + 4F7701D32F2EC1AA00B79171 /* Subject.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Subject.swift; sourceTree = ""; }; + 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetColors.swift; sourceTree = ""; }; + 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetData.swift; sourceTree = ""; }; + 4F7701ED2F2EC2F500B79171 /* KretaAPIClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KretaAPIClient.swift; sourceTree = ""; }; + 4F7701EE2F2EC2F500B79171 /* TokenManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenManager.swift; sourceTree = ""; }; + 4F959B792F289CA600FF7F03 /* LiveActivityWidget.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LiveActivityWidget.entitlements; sourceTree = ""; }; + 4F959B9C2F289CA600FF7F03 /* HomeWidgetsExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = HomeWidgetsExtension.entitlements; sourceTree = ""; }; + 4FCB030C2F330F3B00418E63 /* KretaAPIModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KretaAPIModels.swift; sourceTree = ""; }; + 4FE64E332F27B079006F9205 /* HomeWidgetsExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HomeWidgetsExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 4FF81B7A2F2EB4C100E95BA0 /* FirkaWatch Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "FirkaWatch Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = WidgetExtension.xcconfig; path = Flutter/WidgetExtension.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A749415A687CBFC3F46FA876 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AA00000100000001AABBCC01 /* hu */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = hu; path = hu.lproj/Localizable.strings; sourceTree = ""; }; + AA00000100000002AABBCC02 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; + AA00000100000003AABBCC03 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/Localizable.strings; sourceTree = ""; }; + AB2E15171B6907C52E8C2B42 /* 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 = ""; }; + AE756C46C544099A30412EAF /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + EBD040A65B2746AF6A3D5C40 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + 4F0EA0512F2BD2A2003CC89E /* Exceptions for "HomeWidgetsExtension" folder in "Runner" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Controls/AppControls.swift, + ); + target = 97C146ED1CF9000F007C117D /* Runner */; + }; + 4F4E70D02EF565FF00C90AD1 /* Exceptions for "LiveActivityWidget" folder in "Runner" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + ActivityAttributes.swift, + ); + target = 97C146ED1CF9000F007C117D /* Runner */; + }; + 4F5966082F2F0EB100A3DB03 /* Exceptions for "FirkaWatchComplications" folder in "FirkaWatchComplicationsExtension" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */; + }; + 4F6C1D3E2ECD3FBD00F819D7 /* Exceptions for "LiveActivityWidget" folder in "LiveActivityWidget" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 4F30C7642E8FBF9D008BB46C /* LiveActivityWidget */; + }; + 4FE64E472F27B07B006F9205 /* Exceptions for "HomeWidgetsExtension" folder in "HomeWidgetsExtension" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 4FE64E322F27B079006F9205 /* HomeWidgetsExtension */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 4F30C76A2E8FBF9D008BB46C /* LiveActivityWidget */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 4F4E70D02EF565FF00C90AD1 /* Exceptions for "LiveActivityWidget" folder in "Runner" target */, + 4F6C1D3E2ECD3FBD00F819D7 /* Exceptions for "LiveActivityWidget" folder in "LiveActivityWidget" target */, + ); + explicitFileTypes = { + }; + explicitFolders = ( + ); + path = LiveActivityWidget; + sourceTree = ""; + }; + 4F5966002F2F0EAF00A3DB03 /* FirkaWatchComplications */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 4F5966082F2F0EB100A3DB03 /* Exceptions for "FirkaWatchComplications" folder in "FirkaWatchComplicationsExtension" target */, + ); + explicitFileTypes = { + }; + explicitFolders = ( + ); + path = FirkaWatchComplications; + sourceTree = ""; + }; + 4FE64E362F27B07A006F9205 /* HomeWidgetsExtension */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 4F0EA0512F2BD2A2003CC89E /* Exceptions for "HomeWidgetsExtension" folder in "Runner" target */, + 4FE64E472F27B07B006F9205 /* Exceptions for "HomeWidgetsExtension" folder in "HomeWidgetsExtension" target */, + ); + explicitFileTypes = { + }; + explicitFolders = ( + ); + path = HomeWidgetsExtension; + sourceTree = ""; + }; + 4FF81B7B2F2EB4C100E95BA0 /* FirkaWatch Watch App */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); + explicitFileTypes = { + }; + explicitFolders = ( + ); + path = "FirkaWatch Watch App"; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 4F30C7622E8FBF9D008BB46C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F30C7692E8FBF9D008BB46C /* SwiftUI.framework in Frameworks */, + 4F30C7672E8FBF9D008BB46C /* WidgetKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F5965FA2F2F0EAF00A3DB03 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F5965FF2F2F0EAF00A3DB03 /* SwiftUI.framework in Frameworks */, + 4F5965FE2F2F0EAF00A3DB03 /* WidgetKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FE64E302F27B079006F9205 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4FE64E352F27B07A006F9205 /* SwiftUI.framework in Frameworks */, + 4FE64E342F27B07A006F9205 /* WidgetKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FF81B772F2EB4C100E95BA0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 213F8C0F6B5418B02DE14204 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C45E0924473D697285AAFD0B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 14578EED4EA309B337AB389E /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 427F5F07FF5CBAA039F178F5 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 4F30C7662E8FBF9D008BB46C /* WidgetKit.framework */, + 4F30C7682E8FBF9D008BB46C /* SwiftUI.framework */, + 035E9CCBCC6585D0F5639031 /* Pods_Runner.framework */, + A749415A687CBFC3F46FA876 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 4F7701CD2F2EC1AA00B79171 /* API */ = { + isa = PBXGroup; + children = ( + 4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */, + 4F7701ED2F2EC2F500B79171 /* KretaAPIClient.swift */, + 4F7701EE2F2EC2F500B79171 /* TokenManager.swift */, + 4FCB030C2F330F3B00418E63 /* KretaAPIModels.swift */, + ); + path = API; + sourceTree = ""; + }; + 4F7701CF2F2EC1AA00B79171 /* Helpers */ = { + isa = PBXGroup; + children = ( + 4F7701CE2F2EC1AA00B79171 /* SeasonalIconHelper.swift */, + ); + path = Helpers; + sourceTree = ""; + }; + 4F7701D62F2EC1AA00B79171 /* Models */ = { + isa = PBXGroup; + children = ( + 4F7701D02F2EC1AA00B79171 /* Average.swift */, + 4F7701D12F2EC1AA00B79171 /* Grade.swift */, + 4F7701D22F2EC1AA00B79171 /* Lesson.swift */, + 4F7701D32F2EC1AA00B79171 /* Subject.swift */, + 4F7701D42F2EC1AA00B79171 /* WidgetColors.swift */, + 4F7701D52F2EC1AA00B79171 /* WidgetData.swift */, + 4F5824822F3548B800B92EA7 /* WatchToken.swift */, + ); + path = Models; + sourceTree = ""; + }; + 4F7701D72F2EC1AA00B79171 /* Shared */ = { + isa = PBXGroup; + children = ( + 4F7701D62F2EC1AA00B79171 /* Models */, + 4F7701CD2F2EC1AA00B79171 /* API */, + 4F7701CF2F2EC1AA00B79171 /* Helpers */, + ); + path = Shared; + sourceTree = SOURCE_ROOT; + }; + 52B477EA0F4B63DC7CE4BA83 /* Pods */ = { + isa = PBXGroup; + children = ( + 485F3791F25A288C749509B2 /* Pods-Runner.debug.xcconfig */, + 248F3DE56A05CAECFEBD617C /* Pods-Runner.release.xcconfig */, + AB2E15171B6907C52E8C2B42 /* Pods-Runner.profile.xcconfig */, + EBD040A65B2746AF6A3D5C40 /* Pods-RunnerTests.debug.xcconfig */, + AE756C46C544099A30412EAF /* Pods-RunnerTests.release.xcconfig */, + 4836947EC3B04B475B3DA1F8 /* Pods-RunnerTests.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 4F5966162F2F0F6500A3DB03 /* FirkaWatchComplicationsExtension.entitlements */, + 4F959B792F289CA600FF7F03 /* LiveActivityWidget.entitlements */, + 4F959B9C2F289CA600FF7F03 /* HomeWidgetsExtension.entitlements */, + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 4F30C76A2E8FBF9D008BB46C /* LiveActivityWidget */, + 4FE64E362F27B07A006F9205 /* HomeWidgetsExtension */, + 4FF81B7B2F2EB4C100E95BA0 /* FirkaWatch Watch App */, + 4F5966002F2F0EAF00A3DB03 /* FirkaWatchComplications */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 52B477EA0F4B63DC7CE4BA83 /* Pods */, + 427F5F07FF5CBAA039F178F5 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + 4F30C7652E8FBF9D008BB46C /* LiveActivityWidget.appex */, + 4FE64E332F27B079006F9205 /* HomeWidgetsExtension.appex */, + 4FF81B7A2F2EB4C100E95BA0 /* FirkaWatch Watch App.app */, + 4F5965FD2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension.appex */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 4F5965F72F2F0C1600A3DB03 /* WatchSessionManager.swift */, + 4F7701D72F2EC1AA00B79171 /* Shared */, + 4F25FCBD2EB1790E0060DAAA /* Runner.entitlements */, + AA00000100000004AABBCC04 /* Localizable.strings */, + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + 4F30C7582E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift */, + 4F45A1732F27FA3C0020E6F1 /* HomeWidgetMethodChannel.swift */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 815908FE3DE50BB6C87AA0DF /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + C45E0924473D697285AAFD0B /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 4F30C7642E8FBF9D008BB46C /* LiveActivityWidget */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4F30C77A2E8FBF9F008BB46C /* Build configuration list for PBXNativeTarget "LiveActivityWidget" */; + buildPhases = ( + 4F30C7612E8FBF9D008BB46C /* Sources */, + 4F30C7622E8FBF9D008BB46C /* Frameworks */, + 4F30C7632E8FBF9D008BB46C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 4F30C76A2E8FBF9D008BB46C /* LiveActivityWidget */, + ); + name = LiveActivityWidget; + productName = TimetableWidgetExtension; + productReference = 4F30C7652E8FBF9D008BB46C /* LiveActivityWidget.appex */; + productType = "com.apple.product-type.app-extension"; + }; + 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4F5966092F2F0EB100A3DB03 /* Build configuration list for PBXNativeTarget "FirkaWatchComplicationsExtension" */; + buildPhases = ( + 4F5965F92F2F0EAF00A3DB03 /* Sources */, + 4F5965FA2F2F0EAF00A3DB03 /* Frameworks */, + 4F5965FB2F2F0EAF00A3DB03 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 4F5966002F2F0EAF00A3DB03 /* FirkaWatchComplications */, + ); + name = FirkaWatchComplicationsExtension; + productName = FirkaWatchComplicationsExtension; + productReference = 4F5965FD2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension.appex */; + productType = "com.apple.product-type.app-extension"; + }; + 4FE64E322F27B079006F9205 /* HomeWidgetsExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4FE64E462F27B07B006F9205 /* Build configuration list for PBXNativeTarget "HomeWidgetsExtension" */; + buildPhases = ( + 4FE64E2F2F27B079006F9205 /* Sources */, + 4FE64E302F27B079006F9205 /* Frameworks */, + 4FE64E312F27B079006F9205 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 4FE64E362F27B07A006F9205 /* HomeWidgetsExtension */, + ); + name = HomeWidgetsExtension; + productName = HomeWidgetsExtensionExtension; + productReference = 4FE64E332F27B079006F9205 /* HomeWidgetsExtension.appex */; + productType = "com.apple.product-type.app-extension"; + }; + 4FF81B792F2EB4C100E95BA0 /* FirkaWatch Watch App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4FF81BA52F2EB4C300E95BA0 /* Build configuration list for PBXNativeTarget "FirkaWatch Watch App" */; + buildPhases = ( + 4FF81B762F2EB4C100E95BA0 /* Sources */, + 4FF81B772F2EB4C100E95BA0 /* Frameworks */, + 4FF81B782F2EB4C100E95BA0 /* Resources */, + 4F59661A2F2F1BBF00A3DB03 /* Embed Foundation Extensions */, + ); + buildRules = ( + ); + dependencies = ( + 4F5966192F2F1BBF00A3DB03 /* PBXTargetDependency */, + 4F59661C2F2F1BD900A3DB03 /* PBXTargetDependency */, + 4F59661E2F2F1BE700A3DB03 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + 4FF81B7B2F2EB4C100E95BA0 /* FirkaWatch Watch App */, + ); + name = "FirkaWatch Watch App"; + productName = "FirkaWatch Watch App"; + productReference = 4FF81B7A2F2EB4C100E95BA0 /* FirkaWatch Watch App.app */; + productType = "com.apple.product-type.application"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + D576F90540C8E625A9A12317 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 4F30C77E2E8FBF9F008BB46C /* Embed Foundation Extensions */, + 4FF81B9B2F2EB4C300E95BA0 /* Embed Watch Content */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + EAA586B3BBC26BBE7306869D /* [CP] Embed Pods Frameworks */, + 3061E0FD6432139C72AA9A85 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + 4F30C7772E8FBF9F008BB46C /* PBXTargetDependency */, + 4FE64E412F27B07B006F9205 /* PBXTargetDependency */, + 4FF81B992F2EB4C300E95BA0 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 2620; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 4F30C7642E8FBF9D008BB46C = { + CreatedOnToolsVersion = 26.0; + }; + 4F5965FC2F2F0EAF00A3DB03 = { + CreatedOnToolsVersion = 26.2; + }; + 4FE64E322F27B079006F9205 = { + CreatedOnToolsVersion = 26.2; + }; + 4FF81B792F2EB4C100E95BA0 = { + CreatedOnToolsVersion = 26.2; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + de, + hu, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + 4F30C7642E8FBF9D008BB46C /* LiveActivityWidget */, + 4FE64E322F27B079006F9205 /* HomeWidgetsExtension */, + 4FF81B792F2EB4C100E95BA0 /* FirkaWatch Watch App */, + 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F30C7632E8FBF9D008BB46C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F5965FB2F2F0EAF00A3DB03 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FE64E312F27B079006F9205 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FF81B782F2EB4C100E95BA0 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AA00000100000005AABBCC05 /* Localizable.strings in Resources */, + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3061E0FD6432139C72AA9A85 /* [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; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 815908FE3DE50BB6C87AA0DF /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + 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 = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "set -e\nNATIVE_ASSETS_DIR=\"$FLUTTER_APPLICATION_PATH/$FLUTTER_BUILD_DIR/native_assets\"\ncase \"$FLUTTER_BUILD_DIR\" in\n /*) NATIVE_ASSETS_DIR=\"$FLUTTER_BUILD_DIR/native_assets\" ;;\nesac\nif [ -d \"$FLUTTER_APPLICATION_PATH/.dart_tool/hooks_runner\" ]; then\n find \"$FLUTTER_APPLICATION_PATH/.dart_tool/hooks_runner\" -exec xattr -c {} \\; 2>/dev/null || true\nfi\nif [ -d \"$NATIVE_ASSETS_DIR\" ]; then\n find \"$NATIVE_ASSETS_DIR\" -exec xattr -c {} \\; 2>/dev/null || true\nfi\n/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; + }; + D576F90540C8E625A9A12317 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + 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; + }; + EAA586B3BBC26BBE7306869D /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F30C7612E8FBF9D008BB46C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F7701DF2F2EC1AA00B79171 /* Grade.swift in Sources */, + 4F7701E02F2EC1AA00B79171 /* WidgetColors.swift in Sources */, + 4F7701E12F2EC1AA00B79171 /* Average.swift in Sources */, + 4F7701E22F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */, + 4F7701E32F2EC1AA00B79171 /* Lesson.swift in Sources */, + 4F7701E42F2EC1AA00B79171 /* Subject.swift in Sources */, + 4F7701E52F2EC1AA00B79171 /* WidgetData.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F5965F92F2F0EAF00A3DB03 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F5966152F2F0F5500A3DB03 /* WidgetData.swift in Sources */, + 4F5966132F2F0F4C00A3DB03 /* Subject.swift in Sources */, + 4F5966142F2F0F5100A3DB03 /* WidgetColors.swift in Sources */, + 4F59660F2F2F0F3B00A3DB03 /* SeasonalIconHelper.swift in Sources */, + 4F5966122F2F0F4900A3DB03 /* Lesson.swift in Sources */, + 4F5966112F2F0F4500A3DB03 /* Grade.swift in Sources */, + 4F5966102F2F0F4100A3DB03 /* Average.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FE64E2F2F27B079006F9205 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F7701D82F2EC1AA00B79171 /* Grade.swift in Sources */, + 4F7701D92F2EC1AA00B79171 /* WidgetColors.swift in Sources */, + 4F7701DA2F2EC1AA00B79171 /* Average.swift in Sources */, + 4F7701DB2F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */, + 4F7701DC2F2EC1AA00B79171 /* Lesson.swift in Sources */, + 4F7701DD2F2EC1AA00B79171 /* Subject.swift in Sources */, + 4F7701DE2F2EC1AA00B79171 /* WidgetData.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4FF81B762F2EB4C100E95BA0 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F7701E62F2EC1AA00B79171 /* Grade.swift in Sources */, + 4F7701E72F2EC1AA00B79171 /* WidgetColors.swift in Sources */, + 4F27D4D22F3F2F7700749B9A /* SharedKeychainManager.swift in Sources */, + 4F7701E82F2EC1AA00B79171 /* Average.swift in Sources */, + 4F5824842F3548B800B92EA7 /* WatchToken.swift in Sources */, + 4FCB030D2F330F3B00418E63 /* KretaAPIModels.swift in Sources */, + 4F7701E92F2EC1AA00B79171 /* SeasonalIconHelper.swift in Sources */, + 4F7701EA2F2EC1AA00B79171 /* Lesson.swift in Sources */, + 4F7701EB2F2EC1AA00B79171 /* Subject.swift in Sources */, + 4F7701EC2F2EC1AA00B79171 /* WidgetData.swift in Sources */, + 4F7701EF2F2EC2F500B79171 /* TokenManager.swift in Sources */, + 4F7701F02F2EC2F500B79171 /* KretaAPIClient.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 4F27D4D32F3F2F7700749B9A /* SharedKeychainManager.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 4F30C7592E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift in Sources */, + 4F45A1752F27FA3C0020E6F1 /* HomeWidgetMethodChannel.swift in Sources */, + 4F5965F82F2F0C1600A3DB03 /* WatchSessionManager.swift in Sources */, + 4F5824832F3548B800B92EA7 /* WatchToken.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; + 4F30C7772E8FBF9F008BB46C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4F30C7642E8FBF9D008BB46C /* LiveActivityWidget */; + targetProxy = 4F30C7762E8FBF9F008BB46C /* PBXContainerItemProxy */; + }; + 4F5966192F2F1BBF00A3DB03 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */; + targetProxy = 4F5966182F2F1BBF00A3DB03 /* PBXContainerItemProxy */; + }; + 4F59661C2F2F1BD900A3DB03 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */; + targetProxy = 4F59661B2F2F1BD900A3DB03 /* PBXContainerItemProxy */; + }; + 4F59661E2F2F1BE700A3DB03 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */; + targetProxy = 4F59661D2F2F1BE700A3DB03 /* PBXContainerItemProxy */; + }; + 4FE64E412F27B07B006F9205 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4FE64E322F27B079006F9205 /* HomeWidgetsExtension */; + targetProxy = 4FE64E402F27B07B006F9205 /* PBXContainerItemProxy */; + }; + 4FF81B992F2EB4C300E95BA0 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4FF81B792F2EB4C100E95BA0 /* FirkaWatch Watch App */; + targetProxy = 4FF81B982F2EB4C300E95BA0 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; + AA00000100000004AABBCC04 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + AA00000100000001AABBCC01 /* hu */, + AA00000100000002AABBCC02 /* en */, + AA00000100000003AABBCC03 /* de */, + ); + name = Localizable.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VALID_ARCHS = arm64; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Firka; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0.9; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + VALID_ARCHS = arm64; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EBD040A65B2746AF6A3D5C40 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + VALID_ARCHS = arm64; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AE756C46C544099A30412EAF /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + VALID_ARCHS = arm64; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4836947EC3B04B475B3DA1F8 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + VALID_ARCHS = arm64; + }; + name = Profile; + }; + 4F30C77B2E8FBF9F008BB46C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = LiveActivityWidget/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = LiveActivityWidget; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.LiveActivityWidget; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALID_ARCHS = arm64; + }; + name = Debug; + }; + 4F30C77C2E8FBF9F008BB46C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = LiveActivityWidget/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = LiveActivityWidget; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.LiveActivityWidget; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALID_ARCHS = arm64; + }; + name = Release; + }; + 4F30C77D2E8FBF9F008BB46C /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = LiveActivityWidget/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = LiveActivityWidget; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.LiveActivityWidget; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALID_ARCHS = arm64; + }; + name = Profile; + }; + 4F59660A2F2F0EB100A3DB03 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = FirkaWatchComplications/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatchComplications; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + "@executable_path/../../../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp.complications; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Debug; + }; + 4F59660B2F2F0EB100A3DB03 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = FirkaWatchComplications/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatchComplications; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + "@executable_path/../../../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp.complications; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Release; + }; + 4F59660C2F2F0EB100A3DB03 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = FirkaWatchComplications/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatchComplications; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + "@executable_path/../../../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp.complications; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Profile; + }; + 4FE64E432F27B07B006F9205 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = HomeWidgetsExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = HomeWidgetsExtension; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.HomeWidgetsExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 4FE64E442F27B07B006F9205 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = HomeWidgetsExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = HomeWidgetsExtension; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.HomeWidgetsExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 4FE64E452F27B07B006F9205 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB41CF90195004384FC /* WidgetExtension.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = HomeWidgetsExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = HomeWidgetsExtension; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_NSSupportsLiveActivities = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.HomeWidgetsExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Profile; + }; + 4FF81B9C2F2EB4C300E95BA0 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = "FirkaWatch Watch App/FirkaWatch Watch App.entitlements"; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firkaa.legacy; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Debug; + }; + 4FF81B9D2F2EB4C300E95BA0 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = "FirkaWatch Watch App/FirkaWatch Watch App.entitlements"; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firkaa.legacy; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Release; + }; + 4FF81B9E2F2EB4C300E95BA0 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD)"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AppIcon; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = "FirkaWatch Watch App/FirkaWatch Watch App.entitlements"; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firkaa.legacy; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy.watchkitapp; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SDKROOT = watchos; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALID_ARCHS = "$(ARCHS_STANDARD)"; + WATCHOS_DEPLOYMENT_TARGET = 10.0; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALID_ARCHS = arm64; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_KEY_NSSupportsLiveActivities = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VALID_ARCHS = arm64; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Firka; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0.9; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + VALID_ARCHS = arm64; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1102; + DEVELOPMENT_TEAM = R9PZGUCNJ3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Firka; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0.9; + PRODUCT_BUNDLE_IDENTIFIER = app.firkaa.legacy; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + VALID_ARCHS = arm64; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4F30C77A2E8FBF9F008BB46C /* Build configuration list for PBXNativeTarget "LiveActivityWidget" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4F30C77B2E8FBF9F008BB46C /* Debug */, + 4F30C77C2E8FBF9F008BB46C /* Release */, + 4F30C77D2E8FBF9F008BB46C /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4F5966092F2F0EB100A3DB03 /* Build configuration list for PBXNativeTarget "FirkaWatchComplicationsExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4F59660A2F2F0EB100A3DB03 /* Debug */, + 4F59660B2F2F0EB100A3DB03 /* Release */, + 4F59660C2F2F0EB100A3DB03 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4FE64E462F27B07B006F9205 /* Build configuration list for PBXNativeTarget "HomeWidgetsExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4FE64E432F27B07B006F9205 /* Debug */, + 4FE64E442F27B07B006F9205 /* Release */, + 4FE64E452F27B07B006F9205 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4FF81BA52F2EB4C300E95BA0 /* Build configuration list for PBXNativeTarget "FirkaWatch Watch App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4FF81B9C2F2EB4C300E95BA0 /* Debug */, + 4FF81B9D2F2EB4C300E95BA0 /* Release */, + 4FF81B9E2F2EB4C300E95BA0 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/firka/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/firka/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/FirkaWatch Watch App.xcscheme b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/FirkaWatch Watch App.xcscheme new file mode 100644 index 00000000..afb67be1 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/FirkaWatch Watch App.xcscheme @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/HomeWidgetsExtension.xcscheme b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/HomeWidgetsExtension.xcscheme new file mode 100644 index 00000000..c030932b --- /dev/null +++ b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/HomeWidgetsExtension.xcscheme @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/LiveActivityWidget.xcscheme b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/LiveActivityWidget.xcscheme new file mode 100644 index 00000000..a3d2d2eb --- /dev/null +++ b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/LiveActivityWidget.xcscheme @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..ecd1a709 --- /dev/null +++ b/firka/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner.xcworkspace/contents.xcworkspacedata b/firka/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..21a3cc14 --- /dev/null +++ b/firka/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/firka/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/firka/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/firka/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/firka/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/firka/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/firka/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/firka/ios/Runner/AppDelegate.swift b/firka/ios/Runner/AppDelegate.swift new file mode 100644 index 00000000..b3d1fcf7 --- /dev/null +++ b/firka/ios/Runner/AppDelegate.swift @@ -0,0 +1,262 @@ +import Flutter +import UIKit +import ActivityKit +import UserNotifications +import BackgroundTasks + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + private var liveActivityManager: Any? + private var fallbackChannel: FlutterMethodChannel? + private var deviceTokenString: String? + private var notificationChannel: FlutterMethodChannel? + private var backgroundFetchChannel: FlutterMethodChannel? + private var widgetDeepLinkChannel: FlutterMethodChannel? + private var pendingWidgetDeepLink: String? + + private let backgroundTaskIdentifier = "app.firka.timetable.refresh" + + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + if #available(iOS 13.0, *) { + BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in + self.handleBackgroundRefresh(task: task as! BGAppRefreshTask) + } + } + + UNUserNotificationCenter.current().delegate = self + + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in + if granted { + DispatchQueue.main.async { + application.registerForRemoteNotifications() + } + } + } + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + // With UIScene lifecycle the root view controller does not exist yet at launch, + // so channels are set up once Flutter's implicit engine is ready. + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + let messenger = engineBridge.applicationRegistrar.messenger() + let application = UIApplication.shared + + HomeWidgetMethodChannel.register(with: messenger) + WatchSessionManager.shared.setup(with: messenger) + + widgetDeepLinkChannel = FlutterMethodChannel(name: "firka.app/widget_deep_link", binaryMessenger: messenger) + widgetDeepLinkChannel?.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in + if call.method == "getPendingDeepLink" { + if let controlNav = UserDefaults(suiteName: "group.app.firkaa.legacy")?.string(forKey: "controlNavigation") { + UserDefaults(suiteName: "group.app.firkaa.legacy")?.removeObject(forKey: "controlNavigation") + result(controlNav) + } else if let link = self?.pendingWidgetDeepLink { + self?.pendingWidgetDeepLink = nil + result(link) + } else { + result(nil) + } + } else { + result(FlutterMethodNotImplemented) + } + } + + backgroundFetchChannel = FlutterMethodChannel(name: "firka.app/background_fetch", binaryMessenger: messenger) + + backgroundFetchChannel?.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in + guard let self = self else { + result(FlutterError(code: "UNAVAILABLE", message: "AppDelegate not available", details: nil)) + return + } + + if #available(iOS 13.0, *) { + switch call.method { + case "scheduleBackgroundFetch": + self.scheduleBackgroundRefresh() + result(true) + case "cancelBackgroundFetch": + BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: self.backgroundTaskIdentifier) + print("[AppDelegate] Background fetch cancelled from Flutter") + result(true) + default: + result(FlutterMethodNotImplemented) + } + } else { + result(FlutterError(code: "UNAVAILABLE", message: "Background fetch requires iOS 13+", details: nil)) + } + } + + notificationChannel = FlutterMethodChannel(name: "firka.app/notifications", binaryMessenger: messenger) + + + if #available(iOS 16.2, *) { + liveActivityManager = LiveActivityMethodChannelManager(messenger: messenger) + } else { + let channel = FlutterMethodChannel(name: "firka.app/live_activity", binaryMessenger: messenger) + self.fallbackChannel = channel + channel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in + switch call.method { + case "registerForPushNotifications": + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in + if granted { + DispatchQueue.main.async { + application.registerForRemoteNotifications() + } + result(self?.deviceTokenString) + } else { + result(FlutterError(code: "PERMISSION_DENIED", message: "Push notification permission denied", details: error?.localizedDescription)) + } + } + case "getDeviceToken": + if let token = self?.deviceTokenString { + result(token) + } else { + result(FlutterError(code: "NO_TOKEN", message: "Device token not available", details: nil)) + } + default: + result(FlutterMethodNotImplemented) + } + } + } + } + + override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { + let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() + self.deviceTokenString = tokenString + if #available(iOS 16.2, *) { + (liveActivityManager as? LiveActivityMethodChannelManager)?.setDeviceToken(tokenString) + } + } + + override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { + print("Failed to register for remote notifications: \(error)") + } + + + override func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { + let userInfo = response.notification.request.content.userInfo + + UIApplication.shared.applicationIconBadgeNumber = 0 + + var action = userInfo["action"] as? String + if action == nil, let aps = userInfo["aps"] as? [String: Any] { + action = aps["action"] as? String + } + + if let action = action { + notificationChannel?.invokeMethod("onNotificationTapped", arguments: [ + "action": action, + "data": userInfo + ]) + } else if let route = userInfo["route"] as? String { + notificationChannel?.invokeMethod("onNotificationTapped", arguments: [ + "route": route, + "action": userInfo["action"] as? String ?? "", + "data": userInfo + ]) + } + + completionHandler() + } + + override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + if #available(iOS 14.0, *) { + completionHandler([.banner, .sound, .badge]) + } else { + completionHandler([.alert, .sound, .badge]) + } + } + + override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { + if let aps = userInfo["aps"] as? [AnyHashable: Any] { + if let contentState = aps["content-state"] { + if let contentStateDict = contentState as? [AnyHashable: Any] { + // iOS automatically handles the Live Activity update + } + } + } + + completionHandler(.newData) + } + + // MARK: - Background Refresh + + @available(iOS 13.0, *) + private func handleBackgroundRefresh(task: BGAppRefreshTask) { + scheduleBackgroundRefresh() + + let queue = OperationQueue() + queue.maxConcurrentOperationCount = 1 + + let operation = BlockOperation { + DispatchQueue.main.async { + self.backgroundFetchChannel?.invokeMethod("performBackgroundFetch", arguments: nil) { result in + if let success = result as? Bool, success { + task.setTaskCompleted(success: true) + } else { + task.setTaskCompleted(success: false) + } + } + } + } + + task.expirationHandler = { + queue.cancelAllOperations() + task.setTaskCompleted(success: false) + } + + queue.addOperation(operation) + } + + @available(iOS 13.0, *) + func scheduleBackgroundRefresh() { + let request = BGAppRefreshTaskRequest(identifier: backgroundTaskIdentifier) + + // IMPORTANT: iOS may delay this based on system conditions and user behavior + // Requested cadence: 15 minutes (best effort, not guaranteed by iOS) + request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) + + do { + try BGTaskScheduler.shared.submit(request) + print("[AppDelegate] Background refresh scheduled for ~15 minutes from now") + } catch { + print("[AppDelegate] Could not schedule background refresh: \(error)") + } + } + + override func applicationDidEnterBackground(_ application: UIApplication) { + // Background fetch will be scheduled from Flutter side when needed + // No automatic scheduling here to give Flutter full control + } + + override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { + if handleWidgetURL(url) { + return true + } + return super.application(app, open: url, options: options) + } + + func handleWidgetURL(_ url: URL) -> Bool { + guard url.scheme == "firka" && url.host == "widget" else { return false } + let path = url.path.replacingOccurrences(of: "/", with: "") + pendingWidgetDeepLink = path + widgetDeepLinkChannel?.invokeMethod("onWidgetDeepLink", arguments: path) + return true + } +} + +/// Scenes get URLs instead of the app delegate, widget deep links are routed back to it. +class SceneDelegate: FlutterSceneDelegate { + override func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { + let appDelegate = UIApplication.shared.delegate as? AppDelegate + let rest = URLContexts.filter { !(appDelegate?.handleWidgetURL($0.url) ?? false) } + if !rest.isEmpty { + super.scene(scene, openURLContexts: rest) + } + } +} diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..d0d98aa1 --- /dev/null +++ b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"images":[{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@3x.png","scale":"3x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@3x.png","scale":"3x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@3x.png","scale":"3x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@1x.png","scale":"1x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@3x.png","scale":"3x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@1x.png","scale":"1x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@1x.png","scale":"1x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@1x.png","scale":"1x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@2x.png","scale":"2x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@1x.png","scale":"1x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@2x.png","scale":"2x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@1x.png","scale":"1x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@2x.png","scale":"2x"},{"size":"83.5x83.5","idiom":"ipad","filename":"Icon-App-83.5x83.5@2x.png","scale":"2x"},{"size":"1024x1024","idiom":"ios-marketing","filename":"Icon-App-1024x1024@1x.png","scale":"1x"}],"info":{"version":1,"author":"xcode"}} \ No newline at end of file diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 00000000..ee502b50 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 00000000..65f2b5e7 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 00000000..af474ff9 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 00000000..eb3896af Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 00000000..12e81ed9 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 00000000..e2989694 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 00000000..b52022aa Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 00000000..af474ff9 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 00000000..ba47f818 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 00000000..6d0ef646 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 00000000..720e1ea8 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 00000000..b6ca29f1 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 00000000..7e6a4890 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 00000000..0960e939 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 00000000..6d0ef646 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 00000000..0d7665fb Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 00000000..236f11be Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 00000000..10d99ec1 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 00000000..094b8df6 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 00000000..cbd39dad Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 00000000..65b83e3c Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/Contents.json b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/Contents.json new file mode 100644 index 00000000..8bb185b1 --- /dev/null +++ b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "filename" : "background.png", + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "darkbackground.png", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/background.png b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/background.png new file mode 100644 index 00000000..0af28733 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/background.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/darkbackground.png b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/darkbackground.png new file mode 100644 index 00000000..0af28733 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchBackground.imageset/darkbackground.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 00000000..f3387d4a --- /dev/null +++ b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,56 @@ +{ + "images" : [ + { + "filename" : "LaunchImage.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "LaunchImageDark.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "LaunchImage@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "LaunchImageDark@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "LaunchImage@3x.png", + "idiom" : "universal", + "scale" : "3x" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "LaunchImageDark@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 00000000..76f06f94 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 00000000..31c2a830 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 00000000..439cd78c Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark.png new file mode 100644 index 00000000..76f06f94 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@2x.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@2x.png new file mode 100644 index 00000000..31c2a830 Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@2x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@3x.png b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@3x.png new file mode 100644 index 00000000..439cd78c Binary files /dev/null and b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImageDark@3x.png differ diff --git a/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 00000000..89c2725b --- /dev/null +++ b/firka/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/firka/ios/Runner/Base.lproj/LaunchScreen.storyboard b/firka/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..28354052 --- /dev/null +++ b/firka/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner/Base.lproj/Main.storyboard b/firka/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f3c28516 --- /dev/null +++ b/firka/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/firka/ios/Runner/HomeWidgetMethodChannel.swift b/firka/ios/Runner/HomeWidgetMethodChannel.swift new file mode 100644 index 00000000..f37d5457 --- /dev/null +++ b/firka/ios/Runner/HomeWidgetMethodChannel.swift @@ -0,0 +1,34 @@ +import Flutter +import WidgetKit + +class HomeWidgetMethodChannel { + static let channelName = "app.firka/home_widgets" + + static func register(with messenger: FlutterBinaryMessenger) { + let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger) + + channel.setMethodCallHandler { call, result in + switch call.method { + case "getAppGroupDirectory": + if let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: "group.app.firkaa.legacy" + ) { + result(containerURL.path) + } else { + result(FlutterError(code: "NO_APP_GROUP", message: "App Group not available", details: nil)) + } + + case "reloadAllWidgets": + if #available(iOS 14.0, *) { + WidgetCenter.shared.reloadAllTimelines() + result(nil) + } else { + result(FlutterError(code: "UNSUPPORTED", message: "Widgets require iOS 14+", details: nil)) + } + + default: + result(FlutterMethodNotImplemented) + } + } + } +} diff --git a/firka/ios/Runner/Info.plist b/firka/ios/Runner/Info.plist new file mode 100644 index 00000000..ffae871b --- /dev/null +++ b/firka/ios/Runner/Info.plist @@ -0,0 +1,110 @@ + + + + + BGTaskSchedulerPermittedIdentifiers + + app.firka.timetable.refresh + + CADisableMinimumFrameDurationOnPhone + + CFBundleAllowMixedLocalizations + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + Firka Testing + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleLocalizations + + en + hu + de + + CFBundleName + firka + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleURLTypes + + + CFBundleURLName + app.firkaa.legacy + CFBundleURLSchemes + + firka + + + + CFBundleVersion + 1102 + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + NSSupportsLiveActivities + + NSSupportsLiveActivitiesFrequentUpdates + + UIApplicationSupportsIndirectInputEvents + + UIBackgroundModes + + remote-notification + fetch + processing + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + + diff --git a/firka/ios/Runner/LiveActivityMethodChannelManager.swift b/firka/ios/Runner/LiveActivityMethodChannelManager.swift new file mode 100644 index 00000000..86ccd718 --- /dev/null +++ b/firka/ios/Runner/LiveActivityMethodChannelManager.swift @@ -0,0 +1,250 @@ +import Flutter +import ActivityKit +import Foundation + +@available(iOS 16.2, *) +class LiveActivityMethodChannelManager: NSObject { + private let channel: FlutterMethodChannel + private var deviceToken: String? + + init(messenger: FlutterBinaryMessenger) { + self.channel = FlutterMethodChannel( + name: "firka.app/live_activity", + binaryMessenger: messenger + ) + + super.init() + + channel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in + self?.handleMethodCall(call, result: result) + } + } + + func setDeviceToken(_ token: String) { + self.deviceToken = token + } + + private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "initialize": + initialize(result: result) + + case "getDeviceToken": + getDeviceToken(result: result) + + case "registerForPushNotifications": + registerForPushNotifications(result: result) + + case "startActivity": + guard let args = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments", details: nil)) + return + } + startActivity(args: args, result: result) + + case "updateActivity": + guard let args = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments", details: nil)) + return + } + updateActivity(args: args, result: result) + + case "endActivity": + guard let args = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments", details: nil)) + return + } + endActivity(args: args, result: result) + + case "getActiveActivities": + getActiveActivities(result: result) + + case "endAllActivities": + endAllActivities(result: result) + + default: + result(FlutterMethodNotImplemented) + } + } + + private func initialize(result: @escaping FlutterResult) { + if #available(iOS 16.2, *) { + if ActivityAuthorizationInfo().areActivitiesEnabled { + result(true) + } else { + result(FlutterError( + code: "NOT_SUPPORTED", + message: "Live Activities are not enabled on this device", + details: nil + )) + } + } else { + result(FlutterError( + code: "NOT_SUPPORTED", + message: "Live Activities require iOS 16.2 or later", + details: nil + )) + } + } + + private func getDeviceToken(result: @escaping FlutterResult) { + if let token = deviceToken { + result(token) + } else { + result(FlutterError( + code: "NO_TOKEN", + message: "Device token not available", + details: nil + )) + } + } + + private func registerForPushNotifications(result: @escaping FlutterResult) { + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in + if granted { + DispatchQueue.main.async { + UIApplication.shared.registerForRemoteNotifications() + } + + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in + if let token = self?.deviceToken { + result(token) + } else { + result(FlutterError( + code: "NO_TOKEN", + message: "Failed to get device token", + details: nil + )) + } + } + } else { + result(FlutterError( + code: "PERMISSION_DENIED", + message: "Push notification permission denied", + details: error?.localizedDescription + )) + } + } + } + + private func startActivity(args: [String: Any], result: @escaping FlutterResult) { + guard let attributesJson = args["attributes"] as? String, + let contentStateJson = args["contentState"] as? String, + let attributesData = attributesJson.data(using: .utf8), + let contentStateData = contentStateJson.data(using: .utf8) else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments for startActivity", details: nil)) + return + } + + Task { + do { + let attributes = try JSONDecoder().decode([String: String].self, from: attributesData) + let contentState = try JSONDecoder().decode(TimetableActivityAttributes.ContentState.self, from: contentStateData) + + let existingActivities = Activity.activities + for activity in existingActivities { + await activity.end(nil, dismissalPolicy: .immediate) + } + + try await Task.sleep(nanoseconds: 100_000_000) + + guard let studentName = attributes["studentName"], + let schoolName = attributes["schoolName"] else { + result(FlutterError(code: "INVALID_ARGS", message: "Missing student or school name", details: nil)) + return + } + + let activityAttributes = TimetableActivityAttributes( + studentName: studentName, + schoolName: schoolName + ) + + let newActivity = try Activity.request( + attributes: activityAttributes, + content: .init(state: contentState, staleDate: nil), + pushType: .token + ) + + let activityId = newActivity.id + + Task { + for await pushToken in newActivity.pushTokenUpdates { + let token = pushToken.map { String(format: "%02x", $0) }.joined() + DispatchQueue.main.async { [weak self] in + self?.channel.invokeMethod("onPushTokenReceived", arguments: [ + "activityId": activityId, + "pushToken": token + ]) + } + } + } + result(activityId) + } catch { + result(FlutterError( + code: "START_FAILED", + message: "Failed to decode or start Live Activity: \(error.localizedDescription)", + details: nil + )) + } + } + } + + private func updateActivity(args: [String: Any], result: @escaping FlutterResult) { + guard let activityId = args["activityId"] as? String, + let contentStateJson = args["contentState"] as? String, + let contentStateData = contentStateJson.data(using: .utf8) else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments for updateActivity", details: nil)) + return + } + + Task { + guard let activity = Activity.activities.first(where: { $0.id == activityId }) else { + result(FlutterError(code: "NOT_FOUND", message: "Activity with specified ID not found for update.", details: nil)) + return + } + + do { + let contentState = try JSONDecoder().decode(TimetableActivityAttributes.ContentState.self, from: contentStateData) + await activity.update(ActivityContent(state: contentState, staleDate: nil)) + result(true) + } catch { + result(FlutterError(code: "UPDATE_FAILED", message: "Failed to decode or update Live Activity", details: error.localizedDescription)) + } + } + } + + private func endActivity(args: [String: Any], result: @escaping FlutterResult) { + guard let activityId = args["activityId"] as? String else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid arguments for endActivity", details: nil)) + return + } + + Task { + guard let activity = Activity.activities.first(where: { $0.id == activityId }) else { + result(true) + return + } + await activity.end(nil, dismissalPolicy: .immediate) + result(true) + } + } + + private func getActiveActivities(result: @escaping FlutterResult) { + if #available(iOS 16.2, *) { + let activityIds = Activity.activities.map { $0.id } + result(activityIds) + } else { + result([]) + } + } + + private func endAllActivities(result: @escaping FlutterResult) { + Task { + let activities = Activity.activities + for activity in activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + result(true) + } + } +} diff --git a/firka/ios/Runner/Runner-Bridging-Header.h b/firka/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 00000000..308a2a56 --- /dev/null +++ b/firka/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/firka/ios/Runner/Runner.entitlements b/firka/ios/Runner/Runner.entitlements new file mode 100644 index 00000000..a0754bcf --- /dev/null +++ b/firka/ios/Runner/Runner.entitlements @@ -0,0 +1,20 @@ + + + + + aps-environment + development + com.apple.developer.ubiquity-kvstore-identifier + $(TeamIdentifierPrefix)app.firkaa.legacy + com.apple.developer.usernotifications.time-sensitive + + com.apple.security.application-groups + + group.app.firkaa.legacy + + keychain-access-groups + + $(AppIdentifierPrefix)app.firka.shared + + + diff --git a/firka/ios/Runner/WatchSessionManager.swift b/firka/ios/Runner/WatchSessionManager.swift new file mode 100644 index 00000000..786bf8cd --- /dev/null +++ b/firka/ios/Runner/WatchSessionManager.swift @@ -0,0 +1,906 @@ +import Foundation +import WatchConnectivity +import Flutter + +class WatchSessionManager: NSObject, WCSessionDelegate { + static let shared = WatchSessionManager() + + private var flutterChannel: FlutterMethodChannel? + private var isFlutterWatchSyncReady = false + private var pendingAuthPayloads: [[String: Any]] = [] + private var pendingICloudRecoveryNotification = false + private let pendingAuthQueue = DispatchQueue(label: "app.firka.pendingAuthQueue") + + override private init() { + super.init() + } + + private func mergeApplicationContext(_ newEntries: [String: Any]) { + let session = WCSession.default + guard session.activationState == .activated else { return } + + var merged = session.applicationContext + for (key, value) in newEntries { + merged[key] = value + } + if !newEntries.keys.contains("force_logout") { + merged.removeValue(forKey: "force_logout") + } + do { + try session.updateApplicationContext(merged) + } catch { + print("[WatchSessionManager] Failed to merge applicationContext: \(error)") + } + } + + func setup(with messenger: FlutterBinaryMessenger) { + flutterChannel = FlutterMethodChannel( + name: "app.firka/watch_sync", + binaryMessenger: messenger + ) + + flutterChannel?.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in + switch call.method { + case "sendTokenToWatch": + self?.handleSendTokenToWatch(arguments: call.arguments, result: result) + case "sendWidgetDataToWatch": + self?.handleSendWidgetDataToWatch(arguments: call.arguments, result: result) + case "sendLanguageToWatch": + self?.handleSendLanguageToWatch(arguments: call.arguments, result: result) + case "notifyReauthRequired": + self?.handleNotifyReauthRequired(result: result) + case "requestTokenFromWatch": + self?.handleRequestTokenFromWatch(result: result) + case "checkiCloudToken": + self?.handleCheckiCloudToken(result: result) + case "saveTokeToniCloud": + self?.handleSaveTokenToiCloud(arguments: call.arguments, result: result) + case "isWatchAppInstalled": + self?.handleIsWatchAppInstalled(result: result) + case "isWatchReachable": + self?.handleIsWatchReachable(result: result) + case "clearICloudToken": + self?.handleClearICloudToken(result: result) + case "sendLogoutToWatch": + self?.handleSendLogoutToWatch(result: result) + case "watchSyncReady": + self?.handleWatchSyncReady(result: result) + case "waitForPeerRefreshLease": + self?.handleWaitForPeerRefreshLease(arguments: call.arguments, result: result) + case "acquireRefreshLease": + self?.handleAcquireRefreshLease(arguments: call.arguments, result: result) + case "releaseRefreshLease": + self?.handleReleaseRefreshLease(arguments: call.arguments, result: result) + case "clearRefreshLeaseForAccount": + self?.handleClearRefreshLeaseForAccount(arguments: call.arguments, result: result) + case "clearAllRefreshLeases": + self?.handleClearAllRefreshLeases(result: result) + case "clearSharedLanguageState": + self?.handleClearSharedLanguageState(result: result) + case "sendMessageToWatch": + self?.handleSendMessageToWatch(arguments: call.arguments, result: result) + default: + result(FlutterMethodNotImplemented) + } + } + + if WCSession.isSupported() { + WCSession.default.delegate = self + WCSession.default.activate() + print("[WatchSessionManager] WCSession activated") + } else { + print("[WatchSessionManager] WCSession not supported on this device") + } + + NotificationCenter.default.addObserver( + self, + selector: #selector(handleTokenRecoveredFromiCloud), + name: Notification.Name("TokenRecoveredFromiCloud"), + object: nil + ) + } + + @objc private func handleTokenRecoveredFromiCloud() { + print("[WatchSessionManager] Token recovered from iCloud, notifying Flutter to clear reauth flag") + DispatchQueue.main.async { + self.notifyTokenRecoveredToFlutter() + } + } + + private func parseInt64(_ value: Any?) -> Int64? { + if let value = value as? Int64 { + return value + } + if let value = value as? Int { + return Int64(value) + } + if let value = value as? Double { + return Int64(value) + } + if let value = value as? String, let parsed = Int64(value) { + return parsed + } + return nil + } + + private func parseLeaseOwner(_ value: Any?) -> RefreshLeaseOwner? { + guard let raw = value as? String else { + return nil + } + return RefreshLeaseOwner(rawValue: raw) + } + + private func tokenPayload(from token: WatchToken) -> [String: Any] { + var tokenData: [String: Any] = [ + "studentId": token.studentId, + "studentIdNorm": token.studentIdNorm, + "iss": token.iss, + "idToken": token.idToken, + "accessToken": token.accessToken, + "refreshToken": token.refreshToken, + "expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000) + ] + if let tokenVersion = token.effectiveTokenVersion { + tokenData["tokenVersion"] = tokenVersion + } + if let updatedAtMs = token.effectiveUpdatedAtMs { + tokenData["updatedAtMs"] = updatedAtMs + } + return tokenData + } + + private func isTokenUsable(_ token: WatchToken, skewSeconds: TimeInterval = 60) -> Bool { + token.expiryDate > Date().addingTimeInterval(skewSeconds) + } + + private func fallbackTokenFromSharedKeychain() -> [String: Any]? { + guard let token = SharedKeychainManager.shared.loadToken() else { + return nil + } + guard isTokenUsable(token, skewSeconds: 0) else { + print("[WatchSessionManager] Shared Keychain fallback token is expired, skipping fallback") + return nil + } + return tokenPayload(from: token) + } + + private func sameTokenPayload(_ lhs: [String: Any], _ rhs: [String: Any]) -> Bool { + return parseInt64(lhs["studentIdNorm"]) == parseInt64(rhs["studentIdNorm"]) && + parseInt64(lhs["expiryDate"]) == parseInt64(rhs["expiryDate"]) && + parseInt64(lhs["tokenVersion"]) == parseInt64(rhs["tokenVersion"]) && + parseInt64(lhs["updatedAtMs"]) == parseInt64(rhs["updatedAtMs"]) && + (lhs["refreshToken"] as? String) == (rhs["refreshToken"] as? String) + } + + private func tokenPayloadIsUsable(_ tokenData: [String: Any], skewMs: Int64 = 0) -> Bool { + guard let expiryMs = parseInt64(tokenData["expiryDate"]) else { + return false + } + let nowMs = Int64(Date().timeIntervalSince1970 * 1000) + return expiryMs > (nowMs + skewMs) + } + + private func enqueuePendingAuth(_ authData: [String: Any]) { + pendingAuthQueue.sync { + if pendingAuthPayloads.contains(where: { sameTokenPayload($0, authData) }) { + return + } + pendingAuthPayloads.append(authData) + print("[WatchSessionManager] Queued pending token from Watch until Flutter sync is ready") + } + } + + private func forwardTokenToFlutter(_ authData: [String: Any]) { + guard isFlutterWatchSyncReady else { + enqueuePendingAuth(authData) + return + } + flutterChannel?.invokeMethod("onTokenFromWatch", arguments: authData) + } + + private func notifyTokenRecoveredToFlutter() { + guard isFlutterWatchSyncReady else { + pendingICloudRecoveryNotification = true + print("[WatchSessionManager] Queued iCloud recovery notification until Flutter sync is ready") + return + } + flutterChannel?.invokeMethod("onTokenRecoveredFromiCloud", arguments: nil) + } + + private func flushPendingEvents() { + guard isFlutterWatchSyncReady else { + return + } + + let payloadsToFlush: [[String: Any]] = pendingAuthQueue.sync { + let copy = pendingAuthPayloads + pendingAuthPayloads.removeAll() + return copy + } + + if !payloadsToFlush.isEmpty { + print("[WatchSessionManager] Flushing \(payloadsToFlush.count) queued token event(s) to Flutter") + } + for authData in payloadsToFlush { + flutterChannel?.invokeMethod("onTokenFromWatch", arguments: authData) + } + + if pendingICloudRecoveryNotification { + pendingICloudRecoveryNotification = false + flutterChannel?.invokeMethod("onTokenRecoveredFromiCloud", arguments: nil) + } + } + + private func handleWatchSyncReady(result: @escaping FlutterResult) { + isFlutterWatchSyncReady = true + print("[WatchSessionManager] Flutter WatchSync marked as ready") + flushPendingEvents() + result(nil) + } + + private func handleSendTokenToWatch(arguments: Any?, result: @escaping FlutterResult) { + guard let authData = arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Arguments must be a dictionary", details: nil)) + return + } + + guard WCSession.default.isWatchAppInstalled else { + print("[WatchSessionManager] No paired Watch app, skipping token send") + result(nil) + return + } + + guard WCSession.default.activationState == .activated else { + result(FlutterError(code: "SESSION_NOT_ACTIVE", message: "WCSession is not activated", details: nil)) + return + } + + let session = WCSession.default + + mergeApplicationContext(["auth": authData]) + + session.transferUserInfo([ + "id": "token_update", + "auth": authData + ]) + + if session.isReachable { + session.sendMessage( + [ + "id": "token_update", + "auth": authData + ], + replyHandler: { _ in + print("[WatchSessionManager] Token delivered to Watch via sendMessage") + }, + errorHandler: { error in + print("[WatchSessionManager] Failed immediate token send via sendMessage: \(error.localizedDescription)") + } + ) + } + + result(nil) + print("[WatchSessionManager] Token sent to Watch") + } + + private func handleSendWidgetDataToWatch(arguments: Any?, result: @escaping FlutterResult) { + guard let jsonString = arguments as? String else { + result(FlutterError(code: "INVALID_ARGS", message: "Arguments must be a JSON string", details: nil)) + return + } + + guard WCSession.default.activationState == .activated else { + result(FlutterError(code: "SESSION_NOT_ACTIVE", message: "WCSession is not activated", details: nil)) + return + } + + mergeApplicationContext(["widget_data": jsonString]) + result(nil) + print("[WatchSessionManager] Widget data sent to Watch") + } + + private func handleSendLanguageToWatch(arguments: Any?, result: @escaping FlutterResult) { + guard let languageCode = arguments as? String else { + result(FlutterError(code: "INVALID_ARGS", message: "Language code must be a string", details: nil)) + return + } + + guard WCSession.default.isWatchAppInstalled else { + print("[WatchSessionManager] No paired Watch app, skipping language publish") + result(nil) + return + } + + let sharedState = SharedLanguageStateManager.shared.publishState(languageCode: languageCode) + + if WCSession.default.activationState == .activated { + mergeApplicationContext([ + "language": languageCode, + "language_state_version": sharedState.stateVersion + ]) + print("[WatchSessionManager] Language '\(languageCode)' sent to Watch via applicationContext") + + WCSession.default.transferUserInfo([ + "id": "language_update", + "language": languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else { + print("[WatchSessionManager] WCSession not active, language shared-state published only") + } + result(nil) + print("[WatchSessionManager] Language '\(languageCode)' sent to Watch") + } + + private func handleNotifyReauthRequired(result: @escaping FlutterResult) { + guard WCSession.default.activationState == .activated else { + result(FlutterError(code: "SESSION_NOT_ACTIVE", message: "WCSession is not activated", details: nil)) + return + } + + WCSession.default.transferUserInfo([ + "id": "reauth_required" + ]) + result(nil) + print("[WatchSessionManager] Reauth notification sent to Watch") + } + + private func handleRequestTokenFromWatch(result: @escaping FlutterResult) { + guard WCSession.default.activationState == .activated else { + result(["error": "session_not_active"]) + return + } + + guard WCSession.default.isReachable else { + result(["error": "watch_not_reachable"]) + return + } + + print("[WatchSessionManager] Requesting token from Watch...") + + WCSession.default.sendMessage( + ["action": "getToken"], + replyHandler: { response in + if let tokenData = response["token"] as? [String: Any] { + print("[WatchSessionManager] Received token from Watch") + result(tokenData) + } else if let error = response["error"] as? String { + print("[WatchSessionManager] Watch returned error: \(error)") + result(["error": error]) + } else { + result(["error": "no_token"]) + } + }, + errorHandler: { error in + print("[WatchSessionManager] Failed to request token from Watch: \(error)") + result(["error": error.localizedDescription]) + } + ) + } + + private func handleCheckiCloudToken(result: @escaping FlutterResult) { + print("[WatchSessionManager] Checking shared Keychain for token...") + + guard let token = SharedKeychainManager.shared.loadToken() else { + print("[WatchSessionManager] No token in shared Keychain") + result(["error": "no_token"]) + return + } + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + print("[WatchSessionManager] Found shared Keychain token, expiry: \(formatter.string(from: token.expiryDate))") + + result(tokenPayload(from: token)) + } + + private func handleSaveTokenToiCloud(arguments: Any?, result: @escaping FlutterResult) { + guard let tokenData = arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Arguments must be a dictionary", details: nil)) + return + } + + guard WCSession.default.isWatchAppInstalled else { + print("[WatchSessionManager] No paired Watch app, skipping token save to shared Keychain") + result(nil) + return + } + + guard let accessToken = tokenData["accessToken"] as? String, + let refreshToken = tokenData["refreshToken"] as? String, + let idToken = tokenData["idToken"] as? String, + let iss = tokenData["iss"] as? String, + let studentId = tokenData["studentId"] as? String, + let expiryMs = parseInt64(tokenData["expiryDate"]) else { + result(FlutterError(code: "INVALID_ARGS", message: "Missing required token fields", details: nil)) + return + } + + let studentIdNorm = parseInt64(tokenData["studentIdNorm"]) ?? 0 + let expiryDate = Date(timeIntervalSince1970: Double(expiryMs) / 1000.0) + let tokenVersion = parseInt64(tokenData["tokenVersion"]) ?? WatchToken.extractIatMillis(from: idToken) + let updatedAtMs = parseInt64(tokenData["updatedAtMs"]) ?? Int64(Date().timeIntervalSince1970 * 1000) + + let token = WatchToken( + accessToken: accessToken, + refreshToken: refreshToken, + idToken: idToken, + iss: iss, + studentId: studentId, + studentIdNorm: studentIdNorm, + expiryDate: expiryDate, + tokenVersion: tokenVersion, + updatedAtMs: updatedAtMs + ) + + let forceAccountSwitch = (tokenData["forceAccountSwitch"] as? Bool) == true + let didSave = SharedKeychainManager.shared.saveToken( + token, + forceAccountSwitch: forceAccountSwitch + ) + if WCSession.default.isWatchAppInstalled { + if didSave { + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: true, + activeStudentIdNorm: studentIdNorm + ) + } else if SharedKeychainManager.shared.loadToken()?.studentIdNorm == studentIdNorm { + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: true, + activeStudentIdNorm: studentIdNorm + ) + } else { + print("[WatchSessionManager] Token save skipped (stale/cross-account); skipping session-state publish for \(studentIdNorm)") + } + } + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + print("[WatchSessionManager] Token saved to shared Keychain, expiry: \(formatter.string(from: expiryDate))") + + result(nil) + } + + private func handleIsWatchAppInstalled(result: @escaping FlutterResult) { + guard WCSession.isSupported() else { + result(false) + return + } + + let session = WCSession.default + let installed = session.isPaired && session.isWatchAppInstalled + result(installed) + } + + private func handleIsWatchReachable(result: @escaping FlutterResult) { + guard WCSession.isSupported() else { + result(false) + return + } + + let session = WCSession.default + let reachable = + session.isPaired && + session.isWatchAppInstalled && + session.activationState == .activated && + session.isReachable + result(reachable) + } + + private func handleClearICloudToken(result: @escaping FlutterResult) { + SharedKeychainManager.shared.deleteToken() + + SharedKeychainManager.shared.clearKVStore() + RefreshLeaseManager.shared.clearAllLeases() + SharedLanguageStateManager.shared.clearState() + if WCSession.default.isWatchAppInstalled { + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: false, + activeStudentIdNorm: nil + ) + } else { + SharedSessionStateManager.shared.clearState() + } + result(nil) + } + + private func handleWaitForPeerRefreshLease(arguments: Any?, result: @escaping FlutterResult) { + guard let args = arguments as? [String: Any], + let owner = parseLeaseOwner(args["owner"]), + let studentIdNorm = parseInt64(args["studentIdNorm"]) else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid wait lease arguments", details: nil)) + return + } + + let maxWaitMs = parseInt64(args["maxWaitMs"]) ?? 150_000 + let pollMs = parseInt64(args["pollIntervalMs"]) ?? 250 + + if owner == .iphone && !WCSession.default.isWatchAppInstalled { + result([ + "ready": true, + "status": "no_watch", + "waitedMs": 0, + "leaseChanged": false + ]) + return + } + + Task { + let waitResult = await RefreshLeaseManager.shared.waitForPeerLeaseRelease( + owner: owner, + studentIdNorm: studentIdNorm, + maxWaitMs: maxWaitMs, + pollIntervalMs: pollMs + ) + DispatchQueue.main.async { + result(waitResult.asDictionary()) + } + } + } + + private func handleAcquireRefreshLease(arguments: Any?, result: @escaping FlutterResult) { + guard let args = arguments as? [String: Any], + let owner = parseLeaseOwner(args["owner"]), + let studentIdNorm = parseInt64(args["studentIdNorm"]) else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid acquire lease arguments", details: nil)) + return + } + + if owner == .iphone && !WCSession.default.isWatchAppInstalled { + result([ + "skipped": true, + "status": "no_watch" + ]) + return + } + + let ttlMs = parseInt64(args["ttlMs"]) ?? 120_000 + let operationId = (args["operationId"] as? String) ?? UUID().uuidString + let lease = RefreshLeaseManager.shared.acquireLease( + owner: owner, + studentIdNorm: studentIdNorm, + ttlMs: ttlMs, + operationId: operationId + ) + result([ + "operationId": lease.operationId, + "startedAtMs": lease.startedAtMs, + "expiresAtMs": lease.expiresAtMs + ]) + } + + private func handleReleaseRefreshLease(arguments: Any?, result: @escaping FlutterResult) { + guard let args = arguments as? [String: Any], + let owner = parseLeaseOwner(args["owner"]), + let studentIdNorm = parseInt64(args["studentIdNorm"]) else { + result(FlutterError(code: "INVALID_ARGS", message: "Invalid release lease arguments", details: nil)) + return + } + let operationId = args["operationId"] as? String + RefreshLeaseManager.shared.releaseLease( + owner: owner, + studentIdNorm: studentIdNorm, + operationId: operationId + ) + result(nil) + } + + private func handleClearRefreshLeaseForAccount(arguments: Any?, result: @escaping FlutterResult) { + guard let args = arguments as? [String: Any], + let studentIdNorm = parseInt64(args["studentIdNorm"]) else { + result(FlutterError(code: "INVALID_ARGS", message: "Missing studentIdNorm", details: nil)) + return + } + RefreshLeaseManager.shared.clearLeases(studentIdNorm: studentIdNorm) + result(nil) + } + + private func handleClearAllRefreshLeases(result: @escaping FlutterResult) { + RefreshLeaseManager.shared.clearAllLeases() + result(nil) + } + + private func handleClearSharedLanguageState(result: @escaping FlutterResult) { + SharedLanguageStateManager.shared.clearState() + result(nil) + } + + private func handleSendLogoutToWatch(result: @escaping FlutterResult) { + guard WCSession.default.activationState == .activated else { + result(nil) + return + } + + guard WCSession.default.isWatchAppInstalled else { + result(nil) + return + } + + mergeApplicationContext(["force_logout": true]) + + WCSession.default.transferUserInfo([ + "id": "force_logout" + ]) + print("[WatchSessionManager] Force logout sent to Watch") + result(nil) + } + + private func handleSendMessageToWatch(arguments: Any?, result: @escaping FlutterResult) { + guard let message = arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_ARGS", message: "Arguments must be a dictionary", details: nil)) + return + } + + guard WCSession.default.activationState == .activated else { + result(FlutterError(code: "SESSION_NOT_ACTIVE", message: "WCSession is not activated", details: nil)) + return + } + + guard WCSession.default.isReachable else { + result(FlutterError(code: "NOT_REACHABLE", message: "Watch is not reachable", details: nil)) + return + } + + WCSession.default.sendMessage(message, replyHandler: nil, errorHandler: { error in + print("[WatchSessionManager] Failed to send message to Watch: \(error.localizedDescription)") + }) + result(nil) + } + + func session( + _ session: WCSession, + activationDidCompleteWith activationState: WCSessionActivationState, + error: Error? + ) { + DispatchQueue.main.async { + if let error = error { + print("[WatchSessionManager] Activation error: \(error.localizedDescription)") + } else { + print("[WatchSessionManager] Session activated with state: \(activationState.rawValue)") + + if activationState == .activated { + let context = session.receivedApplicationContext + if let authData = context["auth"] as? [String: Any] { + print("[WatchSessionManager] Found pending auth in applicationContext") + self.forwardTokenToFlutter(authData) + } + } + } + } + } + + func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { + print("[WatchSessionManager] Received applicationContext from Watch") + DispatchQueue.main.async { + if let authData = applicationContext["auth"] as? [String: Any] { + print("[WatchSessionManager] Processing auth from applicationContext") + self.forwardTokenToFlutter(authData) + } + } + } + + func session( + _ session: WCSession, + didReceiveMessage message: [String: Any], + replyHandler: @escaping ([String: Any]) -> Void + ) { + DispatchQueue.main.async { [self] in + self._handleMessageWithReply(message: message, replyHandler: replyHandler) + } + } + + private func _handleMessageWithReply(message: [String: Any], replyHandler: @escaping ([String: Any]) -> Void) { + print("[WatchSessionManager] Received message from Watch: \(message)") + + guard let action = message["action"] as? String else { + replyHandler(["error": "No action specified"]) + return + } + + switch action { + case "requestToken": + if !self.isFlutterWatchSyncReady { + if let tokenData = self.fallbackTokenFromSharedKeychain() { + print("[WatchSessionManager] Flutter not ready, returning iCloud token to Watch") + replyHandler(["auth": tokenData]) + } else { + print("[WatchSessionManager] Flutter not ready and no iCloud token available") + replyHandler(["error": "no_token"]) + } + return + } + self.flutterChannel?.invokeMethod("getTokenForWatch", arguments: nil) { result in + if let tokenData = result as? [String: Any] { + if let error = tokenData["error"] as? String { + if error == "needsReauth" { + print("[WatchSessionManager] Flutter reported needsReauth, not using iCloud fallback") + replyHandler(["error": error]) + } else if let fallbackToken = self.fallbackTokenFromSharedKeychain() { + print("[WatchSessionManager] Flutter returned error (\(error)), falling back to iCloud token") + replyHandler(["auth": fallbackToken]) + } else { + print("[WatchSessionManager] Flutter returned error: \(error)") + replyHandler(["error": error]) + } + } else { + guard self.tokenPayloadIsUsable(tokenData) else { + print("[WatchSessionManager] Flutter token is expired, refusing to send to Watch") + replyHandler(["error": "needsReauth"]) + return + } + print("[WatchSessionManager] Sending token to Watch") + replyHandler(["auth": tokenData]) + } + } else { + if let fallbackToken = self.fallbackTokenFromSharedKeychain() { + print("[WatchSessionManager] No Flutter token available, falling back to iCloud token") + replyHandler(["auth": fallbackToken]) + } else { + print("[WatchSessionManager] No token available from Flutter") + replyHandler(["error": "no_token"]) + } + } + } + + case "requestLanguage": + if !self.isFlutterWatchSyncReady { + if let sharedState = SharedLanguageStateManager.shared.loadState() { + print("[WatchSessionManager] Flutter not ready for language request, serving shared language: \(sharedState.languageCode)") + replyHandler([ + "language": sharedState.languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else { + print("[WatchSessionManager] Flutter not ready for language request and no shared language is available") + replyHandler(["error": "language_not_ready"]) + } + return + } + + guard let flutterChannel = self.flutterChannel else { + if let sharedState = SharedLanguageStateManager.shared.loadState() { + print("[WatchSessionManager] Flutter channel missing for language request, serving shared language: \(sharedState.languageCode)") + replyHandler([ + "language": sharedState.languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else { + print("[WatchSessionManager] Flutter channel missing for language request and no shared language is available") + replyHandler(["error": "language_not_ready"]) + } + return + } + + var hasReplied = false + let timeoutWorkItem = DispatchWorkItem { + guard !hasReplied else { return } + hasReplied = true + if let sharedState = SharedLanguageStateManager.shared.loadState() { + print("[WatchSessionManager] Flutter timeout, serving shared language: \(sharedState.languageCode)") + replyHandler([ + "language": sharedState.languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else { + print("[WatchSessionManager] Flutter timeout and no shared language available") + replyHandler(["error": "timeout"]) + } + } + DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: timeoutWorkItem) + + flutterChannel.invokeMethod("getLanguageForWatch", arguments: nil) { result in + timeoutWorkItem.cancel() + guard !hasReplied else { return } + hasReplied = true + + if let languageCode = result as? String, !languageCode.isEmpty { + if let existingState = SharedLanguageStateManager.shared.loadState(), + existingState.languageCode == languageCode { + print("[WatchSessionManager] Sending language to Watch from shared cache: \(languageCode)") + replyHandler([ + "language": languageCode, + "language_state_version": existingState.stateVersion + ]) + return + } + + let sharedState = SharedLanguageStateManager.shared.publishState( + languageCode: languageCode + ) + print("[WatchSessionManager] Sending language to Watch: \(languageCode)") + replyHandler([ + "language": languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else if let sharedState = SharedLanguageStateManager.shared.loadState() { + print("[WatchSessionManager] No language from Flutter, serving last shared language: \(sharedState.languageCode)") + replyHandler([ + "language": sharedState.languageCode, + "language_state_version": sharedState.stateVersion + ]) + } else { + print("[WatchSessionManager] No language available from Flutter or shared state") + replyHandler(["error": "language_not_ready"]) + } + } + + case "receiveTokenFromWatch": + guard let tokenData = message["token"] as? [String: Any] else { + replyHandler(["error": "no_token_data"]) + return + } + + if !self.isFlutterWatchSyncReady { + print("[WatchSessionManager] Flutter not ready, queueing token from Watch") + self.enqueuePendingAuth(tokenData) + replyHandler(["success": true]) + return + } + + print("[WatchSessionManager] Receiving token from Watch") + self.flutterChannel?.invokeMethod("onTokenFromWatch", arguments: tokenData) { result in + if let success = result as? Bool, success { + print("[WatchSessionManager] Flutter accepted Watch token") + replyHandler(["success": true]) + } else if let resultDict = result as? [String: Any], + let success = resultDict["success"] as? Bool, success { + print("[WatchSessionManager] Flutter accepted Watch token") + replyHandler(["success": true]) + } else { + print("[WatchSessionManager] Flutter rejected Watch token") + replyHandler(["error": "rejected"]) + } + } + + default: + replyHandler(["error": "Unknown action: \(action)"]) + } + } + + func session(_ session: WCSession, didReceiveMessage message: [String: Any]) { + print("[WatchSessionManager] Received fire-and-forget message from Watch: \(message)") + DispatchQueue.main.async { + self.flutterChannel?.invokeMethod("onWatchMessage", arguments: message) + } + } + + func sessionDidBecomeInactive(_ session: WCSession) { + print("[WatchSessionManager] Session did become inactive") + } + + func sessionDidDeactivate(_ session: WCSession) { + print("[WatchSessionManager] Session did deactivate, reactivating...") + if WCSession.isSupported() { + WCSession.default.activate() + } + } + + func session( + _ session: WCSession, + didReceiveUserInfo userInfo: [String : Any] = [:] + ) { + DispatchQueue.main.async { + guard let messageId = userInfo["id"] as? String else { + return + } + + if messageId == "token_update_from_watch" { + if let authData = userInfo["auth"] as? [String: Any] { + self.forwardTokenToFlutter(authData) + print("[WatchSessionManager] Token received from Watch") + } + } + } + } + + func sessionWatchStateDidChange(_ session: WCSession) { + DispatchQueue.main.async { + if session.isWatchAppInstalled { + self.flutterChannel?.invokeMethod("watchAppInstalled", arguments: nil) + print("[WatchSessionManager] Watch app installed detected") + } else { + print("[WatchSessionManager] Watch app not installed") + } + } + } +} diff --git a/firka/ios/Runner/de.lproj/Localizable.strings b/firka/ios/Runner/de.lproj/Localizable.strings new file mode 100644 index 00000000..d4f95c1c --- /dev/null +++ b/firka/ios/Runner/de.lproj/Localizable.strings @@ -0,0 +1,7 @@ +/* Navigation Intent Titles (shared with HomeWidgetsExtension) */ +"control_home_title" = "Firka Startseite"; +"control_home_description" = "Firka Startseite öffnen"; +"control_grades_title" = "Firka Noten"; +"control_grades_description" = "Firka Noten öffnen"; +"control_timetable_title" = "Firka Stundenplan"; +"control_timetable_description" = "Firka Stundenplan öffnen"; diff --git a/firka/ios/Runner/en.lproj/Localizable.strings b/firka/ios/Runner/en.lproj/Localizable.strings new file mode 100644 index 00000000..dc35f9fb --- /dev/null +++ b/firka/ios/Runner/en.lproj/Localizable.strings @@ -0,0 +1,7 @@ +/* Navigation Intent Titles (shared with HomeWidgetsExtension) */ +"control_home_title" = "Firka Home"; +"control_home_description" = "Open Firka home screen"; +"control_grades_title" = "Firka Grades"; +"control_grades_description" = "Open Firka grades"; +"control_timetable_title" = "Firka Timetable"; +"control_timetable_description" = "Open Firka timetable"; diff --git a/firka/ios/Runner/hu.lproj/Localizable.strings b/firka/ios/Runner/hu.lproj/Localizable.strings new file mode 100644 index 00000000..4974516c --- /dev/null +++ b/firka/ios/Runner/hu.lproj/Localizable.strings @@ -0,0 +1,7 @@ +/* Navigation Intent Titles (shared with HomeWidgetsExtension) */ +"control_home_title" = "Firka Főoldal"; +"control_home_description" = "Firka app főoldal megnyitása"; +"control_grades_title" = "Firka Jegyek"; +"control_grades_description" = "Firka app jegyek megnyitása"; +"control_timetable_title" = "Firka Órarend"; +"control_timetable_description" = "Firka app órarend megnyitása"; diff --git a/firka/ios/RunnerTests/RunnerTests.swift b/firka/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..86a7c3b1 --- /dev/null +++ b/firka/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/firka/ios/Shared/API/KretaAPIClient.swift b/firka/ios/Shared/API/KretaAPIClient.swift new file mode 100644 index 00000000..b77ef7b0 --- /dev/null +++ b/firka/ios/Shared/API/KretaAPIClient.swift @@ -0,0 +1,225 @@ +import Foundation + +// MARK: - API Error Types + +enum APIError: Error { + case invalidURL + case requestFailed(statusCode: Int) + case decodingFailed(Error) + case unauthorized + case tokenError(TokenError) +} + +// MARK: - Kréta API Client + +class KretaAPIClient { + static let shared = KretaAPIClient() + + private let apiKey = "21ff6c25-d1da-4a68-a811-c881a6057463" + private let userAgent = "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0" + private let dateFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd" + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(abbreviation: "UTC") + return formatter + }() + + private init() {} + + // MARK: - Public API Methods + func fetchTimetable(from: Date, to: Date) async throws -> [WidgetLesson] { + let token = try await getValidToken() + let fromString = dateFormatter.string(from: from) + let toString = dateFormatter.string(from: to) + + let path = "/ellenorzo/v3/sajat/OrarendElemek" + let queryItems = [ + URLQueryItem(name: "datumTol", value: fromString), + URLQueryItem(name: "datumIg", value: toString) + ] + + let data = try await performRequest( + path: path, + queryItems: queryItems, + token: token + ) + + let kretaLessons = try decodeJSON([KretaLesson].self, from: data) + return kretaLessons.map { $0.toWidgetLesson() } + } + + func fetchGrades() async throws -> [WidgetGrade] { + let token = try await getValidToken() + let path = "/ellenorzo/v3/sajat/Ertekelesek" + + let data = try await performRequest( + path: path, + token: token + ) + + let kretaGrades = try decodeJSON([KretaGrade].self, from: data) + return kretaGrades.map { $0.toWidgetGrade() } + } + + func fetchTests() async throws -> [[String: Any]] { + let token = try await getValidToken() + let path = "/ellenorzo/v3/sajat/BejelentettSzamonkeresek" + + let data = try await performRequest( + path: path, + token: token + ) + + guard let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { + throw APIError.decodingFailed(DecodingError.typeMismatch( + [[String: Any]].self, + DecodingError.Context( + codingPath: [], + debugDescription: "Expected array of dictionaries" + ) + )) + } + + return json + } + + // MARK: - Token Management + + func getValidToken() async throws -> WatchToken { + if let token = TokenManager.shared.loadToken() { + let expiryThreshold = token.expiryDate.addingTimeInterval(-60) + if Date() < expiryThreshold { + TokenManager.shared.clearLastRecoveryFailure() + return token + } + } + + print("[KretaAPI] Token invalid or expired, starting recovery...") + if let recoveredToken = await TokenManager.shared.recoverToken() { + print("[KretaAPI] Token recovery succeeded") + TokenManager.shared.clearLastRecoveryFailure() + return recoveredToken + } + + if let recoveryFailure = TokenManager.shared.lastRecoveryFailure { + print("[KretaAPI] Token recovery failed with classified error: \(recoveryFailure)") + throw APIError.tokenError(recoveryFailure) + } + + print("[KretaAPI] Token recovery failed") + throw APIError.tokenError(.noToken) + } + + // MARK: - Private Helper Methods + private func performRequest( + path: String, + queryItems: [URLQueryItem] = [], + token: WatchToken + ) async throws -> Data { + let baseURLString = "https://\(token.iss).e-kreta.hu" + guard let baseURL = URL(string: baseURLString) else { + throw APIError.invalidURL + } + + var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false) + if !queryItems.isEmpty { + components?.queryItems = queryItems + } + + guard let url = components?.url else { + throw APIError.invalidURL + } + + var request = URLRequest(url: url) + request.httpMethod = "GET" + + request.setValue(apiKey, forHTTPHeaderField: "X-ApiKey") + request.setValue(userAgent, forHTTPHeaderField: "User-Agent") + request.setValue("Bearer \(token.accessToken)", forHTTPHeaderField: "Authorization") + request.setValue("application/json", forHTTPHeaderField: "Accept") + + do { + let (data, response) = try await URLSession.shared.data(for: request) + + guard let httpResponse = response as? HTTPURLResponse else { + throw APIError.requestFailed(statusCode: -1) + } + + switch httpResponse.statusCode { + case 200: + return data + + case 401: + throw APIError.unauthorized + + case 400...599: + throw APIError.requestFailed(statusCode: httpResponse.statusCode) + + default: + throw APIError.requestFailed(statusCode: httpResponse.statusCode) + } + } catch let error as APIError { + throw error + } catch { + throw APIError.requestFailed(statusCode: -1) + } + } + + private func decodeJSON(_ type: T.Type, from data: Data) throws -> T { + let decoder = createJSONDecoder() + + do { + return try decoder.decode(type, from: data) + } catch let error as DecodingError { + throw APIError.decodingFailed(error) + } catch { + throw APIError.decodingFailed(error) + } + } + + private func createJSONDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + + let iso8601Full = ISO8601DateFormatter() + iso8601Full.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + let iso8601 = ISO8601DateFormatter() + iso8601.formatOptions = [.withInternetDateTime] + + let formatterLocal = DateFormatter() + formatterLocal.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" + formatterLocal.locale = Locale(identifier: "en_US_POSIX") + formatterLocal.timeZone = TimeZone.current + + let formatterShort = DateFormatter() + formatterShort.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" + formatterShort.locale = Locale(identifier: "en_US_POSIX") + formatterShort.timeZone = TimeZone.current + + decoder.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let dateString = try container.decode(String.self) + + if let date = iso8601Full.date(from: dateString) { + return date + } + if let date = iso8601.date(from: dateString) { + return date + } + if let date = formatterLocal.date(from: dateString) { + return date + } + if let date = formatterShort.date(from: dateString) { + return date + } + + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Invalid date: \(dateString)" + ) + } + + return decoder + } +} diff --git a/firka/ios/Shared/API/KretaAPIModels.swift b/firka/ios/Shared/API/KretaAPIModels.swift new file mode 100644 index 00000000..2d73dc90 --- /dev/null +++ b/firka/ios/Shared/API/KretaAPIModels.swift @@ -0,0 +1,165 @@ +import Foundation + +// MARK: - Kréta API Response Models +struct KretaLesson: Decodable { + let uid: String + let date: String + let start: Date + let end: Date + let name: String + let lessonNumber: Int? + let teacher: String? + let subject: KretaSubject? + let theme: String? + let roomName: String? + let state: KretaNameUidDesc? + let substituteTeacher: String? + + enum CodingKeys: String, CodingKey { + case uid = "Uid" + case date = "Datum" + case start = "KezdetIdopont" + case end = "VegIdopont" + case name = "Nev" + case lessonNumber = "Oraszam" + case teacher = "TanarNeve" + case subject = "Tantargy" + case theme = "Tema" + case roomName = "TeremNeve" + case state = "Allapot" + case substituteTeacher = "HelyettesTanarNeve" + } + + func toWidgetLesson() -> WidgetLesson { + let widgetSubject = subject.map { sub in + WidgetSubject( + uid: sub.uid, + name: sub.name, + category: sub.category.map { cat in + NameUidDesc(uid: cat.uid, name: cat.name, description: cat.description) + }, + sortIndex: sub.sortIndex ?? 0, + teacherName: sub.teacherName + ) + } ?? WidgetSubject( + uid: "", + name: name, + category: nil, + sortIndex: 0, + teacherName: nil + ) + + let isCancelled = state?.name.lowercased().contains("elmarad") ?? false + + let calendar = Calendar.current + let components = calendar.dateComponents([.year, .month, .day], from: start) + let dateString = String(format: "%04d-%02d-%02d", + components.year ?? 0, + components.month ?? 0, + components.day ?? 0) + + return WidgetLesson( + uid: uid, + date: dateString, + start: start, + end: end, + name: name, + lessonNumber: lessonNumber, + teacher: teacher, + substituteTeacher: substituteTeacher, + subject: widgetSubject, + theme: theme, + roomName: roomName, + isCancelled: isCancelled, + isSubstitution: substituteTeacher != nil + ) + } +} + +struct KretaSubject: Decodable { + let uid: String + let name: String + let category: KretaNameUidDesc? + let sortIndex: Int? + let teacherName: String? + + enum CodingKeys: String, CodingKey { + case uid = "Uid" + case name = "Nev" + case category = "Kategoria" + case sortIndex = "SortIndex" + case teacherName = "alkalmazottNev" + } +} + +struct KretaNameUidDesc: Decodable { + let uid: String + let name: String + let description: String? + + enum CodingKeys: String, CodingKey { + case uid = "Uid" + case name = "Nev" + case description = "Leiras" + } +} + +// MARK: - API Grade Response + +struct KretaGrade: Decodable { + let uid: String + let recordDate: Date + let subject: KretaSubject + let topic: String? + let type: KretaNameUidDesc + let valueType: KretaNameUidDesc? + let numericValue: Int? + let strValue: String? + let weightPercentage: Int? + + enum CodingKeys: String, CodingKey { + case uid = "Uid" + case recordDate = "RogzitesDatuma" + case subject = "Tantargy" + case topic = "Tema" + case type = "Tipus" + case valueType = "ErtekFajta" + case numericValue = "SzamErtek" + case strValue = "SzovegesErtek" + case weightPercentage = "SulySzazalekErteke" + } + + func toWidgetGrade() -> WidgetGrade { + let widgetSubject = WidgetSubject( + uid: subject.uid, + name: subject.name, + category: subject.category.map { cat in + NameUidDesc(uid: cat.uid, name: cat.name, description: cat.description) + }, + sortIndex: subject.sortIndex ?? 0, + teacherName: subject.teacherName + ) + + let widgetType = NameUidDesc( + uid: type.uid, + name: type.name, + description: type.description + ) + + let widgetValueType = valueType.map { vt in + NameUidDesc(uid: vt.uid, name: vt.name, description: vt.description) + } + + return WidgetGrade( + uid: uid, + recordDate: recordDate, + subject: widgetSubject, + topic: topic, + type: widgetType, + valueType: widgetValueType, + numericValue: numericValue, + strValue: strValue, + weightPercentage: weightPercentage + ) + } +} diff --git a/firka/ios/Shared/API/SharedKeychainManager.swift b/firka/ios/Shared/API/SharedKeychainManager.swift new file mode 100644 index 00000000..5e145079 --- /dev/null +++ b/firka/ios/Shared/API/SharedKeychainManager.swift @@ -0,0 +1,791 @@ +import Foundation +import Security + +/// Manages the synced Keychain storage for cross-device token sharing via iCloud Keychain. +class SharedKeychainManager { + static let shared = SharedKeychainManager() + + private let accessGroupSuffix = "app.firka.shared" + private lazy var accessGroup: String = resolveAccessGroup() + private let service = "app.firka.shared.token" + private let account = "syncedToken" + + #if os(iOS) + private let deviceName = "iPhone" + #elseif os(watchOS) + private let deviceName = "Watch" + #endif + + private init() {} + + var resolvedAccessGroup: String { + accessGroup + } + + private func resolveAccessGroup() -> String { + let probeService = "\(service).probe" + let probeAccount = "probe" + let probeValue = Data("probe".utf8) + + let cleanupQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: probeService, + kSecAttrAccount as String: probeAccount, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(cleanupQuery as CFDictionary) + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: probeService, + kSecAttrAccount as String: probeAccount, + kSecValueData as String: probeValue, + kSecAttrSynchronizable as String: kCFBooleanTrue!, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock + ] + + let addStatus = SecItemAdd(addQuery as CFDictionary, nil) + if addStatus == errSecSuccess || addStatus == errSecDuplicateItem { + let readQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: probeService, + kSecAttrAccount as String: probeAccount, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny, + kSecReturnAttributes as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let readStatus = SecItemCopyMatching(readQuery as CFDictionary, &result) + SecItemDelete(cleanupQuery as CFDictionary) + + if readStatus == errSecSuccess, + let attributes = result as? [String: Any], + let resolvedGroup = attributes[kSecAttrAccessGroup as String] as? String, + !resolvedGroup.isEmpty { + print("[SharedKeychain] Resolved access group: \(resolvedGroup)") + return resolvedGroup + } + } + + print("[SharedKeychain] Failed to resolve access group dynamically, using suffix fallback") + return accessGroupSuffix + } + + // MARK: - Save Token (Synced) + @discardableResult + func saveToken(_ token: WatchToken, forceAccountSwitch: Bool = false) -> Bool { + if let existingToken = loadToken() { + if existingToken.isSameAccount(as: token) { + if !token.isNewer(than: existingToken) { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + print("[SharedKeychain] Ignoring stale token save from \(deviceName), existing expiry: \(formatter.string(from: existingToken.expiryDate)), incoming: \(formatter.string(from: token.expiryDate))") + return false + } + } else { + if !forceAccountSwitch { + let incomingUpdatedAt = token.effectiveUpdatedAtMs ?? 0 + let existingUpdatedAt = existingToken.effectiveUpdatedAtMs ?? 0 + if incomingUpdatedAt > 0 && + existingUpdatedAt > 0 && + incomingUpdatedAt <= existingUpdatedAt { + print("[SharedKeychain] Ignoring cross-account stale token save from \(deviceName)") + return false + } + } + } + } + + print("[SharedKeychain] Saving token to synced Keychain from \(deviceName)") + + do { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(token) + + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue! + ] + SecItemDelete(deleteQuery as CFDictionary) + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue!, + kSecValueData as String: data, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock + ] + + let status = SecItemAdd(addQuery as CFDictionary, nil) + + if status == errSecSuccess { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + print("[SharedKeychain] Token saved successfully to synced Keychain, expiry: \(formatter.string(from: token.expiryDate))") + return true + } else { + print("[SharedKeychain] Failed to save token to synced Keychain: \(status)") + return false + } + } catch { + print("[SharedKeychain] Failed to encode token: \(error)") + return false + } + } + + // MARK: - Load Token (Synced) + func loadToken() -> WatchToken? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue!, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + guard status == errSecSuccess, let data = result as? Data else { + if status != errSecItemNotFound { + print("[SharedKeychain] Failed to load token from synced Keychain: \(status)") + } + return nil + } + + do { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let token = try decoder.decode(WatchToken.self, from: data) + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + print("[SharedKeychain] Token loaded from synced Keychain, expiry: \(formatter.string(from: token.expiryDate))") + + return token + } catch { + print("[SharedKeychain] Failed to decode token from synced Keychain: \(error)") + return nil + } + } + + // MARK: - Delete Token (Synced) + func deleteToken() { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue! + ] + + let status = SecItemDelete(query as CFDictionary) + if status == errSecSuccess || status == errSecItemNotFound { + print("[SharedKeychain] Token deleted from synced Keychain") + } else { + print("[SharedKeychain] Failed to delete token from synced Keychain: \(status)") + } + } + + // MARK: - Migration from KV Store + func migrateFromKVStoreAndClear() -> WatchToken? { + let iCloudStore = NSUbiquitousKeyValueStore.default + + iCloudStore.synchronize() + + guard let accessToken = iCloudStore.string(forKey: "firka_access_token"), + let refreshToken = iCloudStore.string(forKey: "firka_refresh_token"), + let idToken = iCloudStore.string(forKey: "firka_id_token"), + let iss = iCloudStore.string(forKey: "firka_iss"), + let studentId = iCloudStore.string(forKey: "firka_student_id") else { + print("[SharedKeychain] No token found in KV Store to migrate") + clearKVStore() + return nil + } + + let studentIdNorm = iCloudStore.longLong(forKey: "firka_student_id_norm") + let expiryTimestamp = iCloudStore.double(forKey: "firka_expiry_date") + let tokenVersionRaw = iCloudStore.longLong(forKey: "firka_token_version") + let updatedAtMsRaw = iCloudStore.longLong(forKey: "firka_updated_at_ms") + + guard expiryTimestamp > 0 else { + print("[SharedKeychain] Invalid expiry date in KV Store") + clearKVStore() + return nil + } + + let expiryDate = Date(timeIntervalSince1970: expiryTimestamp) + + let token = WatchToken( + accessToken: accessToken, + refreshToken: refreshToken, + idToken: idToken, + iss: iss, + studentId: studentId, + studentIdNorm: studentIdNorm, + expiryDate: expiryDate, + tokenVersion: tokenVersionRaw > 0 ? tokenVersionRaw : nil, + updatedAtMs: updatedAtMsRaw > 0 ? updatedAtMsRaw : nil + ) + + print("[SharedKeychain] Migrated token from KV Store, expiry: \(expiryDate)") + + clearKVStore() + + return token + } + + func clearKVStore() { + let iCloudStore = NSUbiquitousKeyValueStore.default + + let keysToRemove = [ + "firka_access_token", + "firka_refresh_token", + "firka_id_token", + "firka_iss", + "firka_student_id", + "firka_student_id_norm", + "firka_expiry_date", + "firka_token_version", + "firka_updated_at_ms", + "firka_last_updated_device", + "firka_last_update_timestamp" + ] + + for key in keysToRemove { + iCloudStore.removeObject(forKey: key) + } + + iCloudStore.synchronize() + print("[SharedKeychain] Cleared old KV Store data") + } +} + +enum RefreshLeaseOwner: String { + case iphone + case watch + + var peer: RefreshLeaseOwner { + switch self { + case .iphone: + return .watch + case .watch: + return .iphone + } + } +} + +struct SharedSessionStateRecord: Codable { + let stateVersion: Int64 + let hasAnyAccount: Bool + let activeStudentIdNorm: Int64? + let updatedAtMs: Int64 + let sourceDevice: String +} + +struct SharedLanguageStateRecord: Codable { + let stateVersion: Int64 + let languageCode: String + let updatedAtMs: Int64 + let expiresAtMs: Int64 + let sourceDevice: String +} + +class SharedLanguageStateManager { + static let shared = SharedLanguageStateManager() + + private let service = "app.firka.shared.language_state" + private let account = "language_state" + private let accessGroup: String + private let maxTtlMs: Int64 = 7 * 24 * 60 * 60 * 1000 + + #if os(iOS) + private let sourceDevice = "iphone" + #elseif os(watchOS) + private let sourceDevice = "watch" + #endif + + private init() { + accessGroup = SharedKeychainManager.shared.resolvedAccessGroup + } + + private func nowMs() -> Int64 { + Int64(Date().timeIntervalSince1970 * 1000) + } + + private func encode(_ state: SharedLanguageStateRecord) -> Data? { + try? JSONEncoder().encode(state) + } + + private func decode(_ data: Data) -> SharedLanguageStateRecord? { + try? JSONDecoder().decode(SharedLanguageStateRecord.self, from: data) + } + + private func keychainQueryBase() -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup + ] + } + + private func loadStateFromKeychain() -> SharedLanguageStateRecord? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + guard status == errSecSuccess, let data = result as? Data else { + return nil + } + return decode(data) + } + + private func storeStateInKeychain(_ state: SharedLanguageStateRecord) { + guard let data = encode(state) else { + print("[SharedLanguageState] Failed to encode state for keychain") + return + } + + var deleteQuery = keychainQueryBase() + deleteQuery[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny + SecItemDelete(deleteQuery as CFDictionary) + + var addQuery = keychainQueryBase() + addQuery[kSecAttrSynchronizable as String] = kCFBooleanTrue! + addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock + addQuery[kSecValueData as String] = data + let status = SecItemAdd(addQuery as CFDictionary, nil) + if status != errSecSuccess { + print("[SharedLanguageState] Failed to publish state to keychain: \(status)") + } + } + + private func clearKeychainState() { + var query = keychainQueryBase() + query[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny + SecItemDelete(query as CFDictionary) + } + + private func isExpired(_ state: SharedLanguageStateRecord, now: Int64) -> Bool { + state.expiresAtMs <= now + } + + func loadState() -> SharedLanguageStateRecord? { + let now = nowMs() + guard let keychainState = loadStateFromKeychain() else { + return nil + } + if isExpired(keychainState, now: now) { + clearKeychainState() + return nil + } + return keychainState + } + + @discardableResult + func publishState( + languageCode: String, + ttlMs: Int64 = 24 * 60 * 60 * 1000 + ) -> SharedLanguageStateRecord { + let now = nowMs() + let previousVersion = loadStateFromKeychain()?.stateVersion ?? 0 + let nextVersion = max(now, previousVersion + 1) + let effectiveTtl = max(min(ttlMs, maxTtlMs), 60_000) + let state = SharedLanguageStateRecord( + stateVersion: nextVersion, + languageCode: languageCode, + updatedAtMs: now, + expiresAtMs: now + effectiveTtl, + sourceDevice: sourceDevice + ) + + storeStateInKeychain(state) + + return state + } + + func clearState() { + clearKeychainState() + } +} + +class SharedSessionStateManager { + static let shared = SharedSessionStateManager() + + private let service = "app.firka.shared.session_state" + private let account = "session_state" + private let accessGroup: String + + #if os(iOS) + private let sourceDevice = "iphone" + #elseif os(watchOS) + private let sourceDevice = "watch" + #endif + + private init() { + accessGroup = SharedKeychainManager.shared.resolvedAccessGroup + } + + private func nowMs() -> Int64 { + Int64(Date().timeIntervalSince1970 * 1000) + } + + private func encode(_ state: SharedSessionStateRecord) -> Data? { + try? JSONEncoder().encode(state) + } + + private func decode(_ data: Data) -> SharedSessionStateRecord? { + try? JSONDecoder().decode(SharedSessionStateRecord.self, from: data) + } + + func loadState() -> SharedSessionStateRecord? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + guard status == errSecSuccess, let data = result as? Data else { + return nil + } + return decode(data) + } + + @discardableResult + func publishState( + hasAnyAccount: Bool, + activeStudentIdNorm: Int64? + ) -> SharedSessionStateRecord { + let now = nowMs() + let previousVersion = loadState()?.stateVersion ?? 0 + let nextVersion = max(now, previousVersion + 1) + let state = SharedSessionStateRecord( + stateVersion: nextVersion, + hasAnyAccount: hasAnyAccount, + activeStudentIdNorm: hasAnyAccount ? activeStudentIdNorm : nil, + updatedAtMs: now, + sourceDevice: sourceDevice + ) + + if let data = encode(state) { + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(deleteQuery as CFDictionary) + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue!, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock, + kSecValueData as String: data + ] + let status = SecItemAdd(addQuery as CFDictionary, nil) + if status != errSecSuccess { + print("[SharedSessionState] Failed to publish state: \(status)") + } + } else { + print("[SharedSessionState] Failed to encode state") + } + + return state + } + + func clearState() { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(query as CFDictionary) + } +} + +struct RefreshLeaseRecord: Codable { + let owner: String + let studentIdNorm: Int64 + let operationId: String + let startedAtMs: Int64 + let expiresAtMs: Int64 +} + +struct RefreshLeaseWaitResult { + let ready: Bool + let status: String + let waitedMs: Int64 + let peerOperationId: String? + let leaseChanged: Bool + + func asDictionary() -> [String: Any] { + var dict: [String: Any] = [ + "ready": ready, + "status": status, + "waitedMs": waitedMs, + "leaseChanged": leaseChanged + ] + if let peerOperationId { + dict["peerOperationId"] = peerOperationId + } + return dict + } +} + +class RefreshLeaseManager { + static let shared = RefreshLeaseManager() + + private let service = "app.firka.shared.refresh_lease" + private let accountPrefix = "lease" + private let accessGroup: String + + private init() { + accessGroup = SharedKeychainManager.shared.resolvedAccessGroup + } + + private func keyAccount( + owner: RefreshLeaseOwner, + studentIdNorm: Int64 + ) -> String { + "\(accountPrefix)_\(owner.rawValue)_\(studentIdNorm)" + } + + private func nowMs() -> Int64 { + Int64(Date().timeIntervalSince1970 * 1000) + } + + private func encode(_ lease: RefreshLeaseRecord) -> Data? { + try? JSONEncoder().encode(lease) + } + + private func decode(_ data: Data) -> RefreshLeaseRecord? { + try? JSONDecoder().decode(RefreshLeaseRecord.self, from: data) + } + + func loadLease( + owner: RefreshLeaseOwner, + studentIdNorm: Int64 + ) -> RefreshLeaseRecord? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: keyAccount(owner: owner, studentIdNorm: studentIdNorm), + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + guard status == errSecSuccess, let data = result as? Data else { + return nil + } + return decode(data) + } + + @discardableResult + func acquireLease( + owner: RefreshLeaseOwner, + studentIdNorm: Int64, + ttlMs: Int64, + operationId: String = UUID().uuidString + ) -> RefreshLeaseRecord { + let now = nowMs() + let clampedTtl = max(ttlMs, 5_000) + let lease = RefreshLeaseRecord( + owner: owner.rawValue, + studentIdNorm: studentIdNorm, + operationId: operationId, + startedAtMs: now, + expiresAtMs: now + clampedTtl + ) + + if let data = encode(lease) { + let account = keyAccount(owner: owner, studentIdNorm: studentIdNorm) + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(deleteQuery as CFDictionary) + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kCFBooleanTrue!, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock, + kSecValueData as String: data + ] + let status = SecItemAdd(addQuery as CFDictionary, nil) + if status != errSecSuccess { + print("[RefreshLease] Failed to acquire lease for \(owner.rawValue): \(status)") + } + } else { + print("[RefreshLease] Failed to encode lease for \(owner.rawValue)") + } + + return lease + } + + func releaseLease( + owner: RefreshLeaseOwner, + studentIdNorm: Int64, + operationId: String? = nil + ) { + if let operationId, + let current = loadLease(owner: owner, studentIdNorm: studentIdNorm), + current.operationId != operationId { + return + } + + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: keyAccount(owner: owner, studentIdNorm: studentIdNorm), + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(query as CFDictionary) + } + + func clearLeases(studentIdNorm: Int64) { + releaseLease(owner: .iphone, studentIdNorm: studentIdNorm, operationId: nil) + releaseLease(owner: .watch, studentIdNorm: studentIdNorm, operationId: nil) + } + + func clearAllLeases() { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny, + kSecReturnAttributes as String: true, + kSecMatchLimit as String: kSecMatchLimitAll + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status != errSecSuccess { + return + } + + guard let items = result as? [[String: Any]] else { + return + } + + for item in items { + guard let account = item[kSecAttrAccount as String] as? String else { + continue + } + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + kSecAttrSynchronizable as String: kSecAttrSynchronizableAny + ] + SecItemDelete(deleteQuery as CFDictionary) + } + } + + func waitForPeerLeaseRelease( + owner: RefreshLeaseOwner, + studentIdNorm: Int64, + maxWaitMs: Int64, + pollIntervalMs: Int64 + ) async -> RefreshLeaseWaitResult { + let startedAt = nowMs() + var deadline = startedAt + max(maxWaitMs, 1_000) + var lastFingerprint: String? + var leaseChanged = false + + while nowMs() < deadline { + let now = nowMs() + guard let peer = loadLease(owner: owner.peer, studentIdNorm: studentIdNorm) else { + return RefreshLeaseWaitResult( + ready: true, + status: leaseChanged ? "peer_lease_changed" : "peer_lease_missing", + waitedMs: now - startedAt, + peerOperationId: nil, + leaseChanged: leaseChanged + ) + } + + if peer.expiresAtMs <= now { + releaseLease( + owner: owner.peer, + studentIdNorm: studentIdNorm, + operationId: peer.operationId + ) + return RefreshLeaseWaitResult( + ready: true, + status: "peer_lease_expired", + waitedMs: now - startedAt, + peerOperationId: peer.operationId, + leaseChanged: leaseChanged + ) + } + + let fingerprint = "\(peer.operationId)|\(peer.startedAtMs)|\(peer.expiresAtMs)" + if let previousFingerprint = lastFingerprint, previousFingerprint != fingerprint { + leaseChanged = true + deadline = min(deadline, peer.expiresAtMs + 5_000) + lastFingerprint = fingerprint + continue + } + + lastFingerprint = fingerprint + deadline = min(deadline, peer.expiresAtMs + 5_000) + let sleepMs = max(min(pollIntervalMs, 1_000), 50) + try? await Task.sleep(nanoseconds: UInt64(sleepMs) * 1_000_000) + } + + let waited = max(nowMs() - startedAt, 0) + let peerOperation = loadLease(owner: owner.peer, studentIdNorm: studentIdNorm)?.operationId + return RefreshLeaseWaitResult( + ready: false, + status: "timed_out", + waitedMs: waited, + peerOperationId: peerOperation, + leaseChanged: leaseChanged + ) + } +} diff --git a/firka/ios/Shared/API/TokenManager.swift b/firka/ios/Shared/API/TokenManager.swift new file mode 100644 index 00000000..6b710dd0 --- /dev/null +++ b/firka/ios/Shared/API/TokenManager.swift @@ -0,0 +1,1023 @@ +import Foundation +import Security +#if os(watchOS) +import WatchConnectivity +#endif + +// MARK: - Token Response Structure +private struct TokenRefreshResponse: Decodable { + let accessToken: String + let refreshToken: String + let idToken: String + let expiresIn: Int + + enum CodingKeys: String, CodingKey { + case accessToken = "access_token" + case refreshToken = "refresh_token" + case idToken = "id_token" + case expiresIn = "expires_in" + } +} + +// MARK: - Error Types +enum TokenError: Error { + case noToken + case refreshExpired + case invalidGrant + case invalidResponse + case networkError +} + +// MARK: - Token Manager +class TokenManager { + static let shared = TokenManager() + + private let appGroupID = "group.app.firkaa.legacy" + private let tokenFileName = "watch_token.json" + + private static let keychainService = "app.firka.watch.token" + private static let keychainAccount = "token" + private let tokenRefreshURL = "https://idp.e-kreta.hu/connect/token" + private let clientID = "kreta-ellenorzo-student-mobile-ios" + private let userAgent = "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0" + private let activeStudentIdNormKey = "firka.active_student_id_norm" + private let proactiveRefreshLeadTime: TimeInterval = 5 * 60 + private let minimumProactiveRefreshInterval: TimeInterval = 60 + private let iCloudProbeTimeoutNs: UInt64 = 1_500_000_000 + private let refreshRequestTimeout: TimeInterval = 12 + private let refreshResourceTimeout: TimeInterval = 20 + #if os(watchOS) + private let watchRefreshLeaseTtlMs: Int64 = 180_000 + private let iPhoneRefreshLeaseMaxWaitMs: Int64 = 150_000 + private let refreshLeasePollIntervalMs: Int64 = 250 + #endif + + #if os(iOS) + private let deviceName = "iPhone" + #elseif os(watchOS) + private let deviceName = "Watch" + #endif + private let recoveryLock = NSLock() + private var recoveryInProgress = false + private var lastProactiveRefreshAttemptAt: Date? + private(set) var lastRecoveryFailure: TokenError? + #if os(watchOS) + private var lastPhoneRecoveryRequestAt: Date? + #endif + + private func startRecoveryIfNeeded() -> Bool { + recoveryLock.lock() + defer { recoveryLock.unlock() } + if recoveryInProgress { + return false + } + recoveryInProgress = true + return true + } + + private func finishRecovery() { + recoveryLock.lock() + recoveryInProgress = false + recoveryLock.unlock() + } + + private func isRecoveryRunning() -> Bool { + recoveryLock.lock() + defer { recoveryLock.unlock() } + return recoveryInProgress + } + + func clearLastRecoveryFailure() { + lastRecoveryFailure = nil + } + + #if os(watchOS) + private func withWatchRefreshLease( + studentIdNorm: Int64, + _ operation: () async throws -> T + ) async throws -> T { + let waitResult = await RefreshLeaseManager.shared.waitForPeerLeaseRelease( + owner: .watch, + studentIdNorm: studentIdNorm, + maxWaitMs: iPhoneRefreshLeaseMaxWaitMs, + pollIntervalMs: refreshLeasePollIntervalMs + ) + + guard waitResult.ready else { + print("[TokenManager] Watch refresh lease wait timed out (waited \(waitResult.waitedMs)ms, changed: \(waitResult.leaseChanged))") + throw TokenError.networkError + } + + let lease = RefreshLeaseManager.shared.acquireLease( + owner: .watch, + studentIdNorm: studentIdNorm, + ttlMs: watchRefreshLeaseTtlMs + ) + + defer { + RefreshLeaseManager.shared.releaseLease( + owner: .watch, + studentIdNorm: studentIdNorm, + operationId: lease.operationId + ) + } + + return try await operation() + } + #endif + + private func getActiveStudentIdNorm() -> Int64? { + if let value = UserDefaults.standard.object(forKey: activeStudentIdNormKey) as? Int64 { + return value + } + if let value = UserDefaults.standard.object(forKey: activeStudentIdNormKey) as? Int { + return Int64(value) + } + if let value = UserDefaults.standard.object(forKey: activeStudentIdNormKey) as? Double { + return Int64(value) + } + if let value = UserDefaults.standard.object(forKey: activeStudentIdNormKey) as? String, + let parsed = Int64(value) { + return parsed + } + return nil + } + + private func setActiveStudentIdNorm(_ studentIdNorm: Int64) { + UserDefaults.standard.set(studentIdNorm, forKey: activeStudentIdNormKey) + } + + private func localTokenFromKeychainAndFile(preferredStudentIdNorm: Int64? = nil) -> WatchToken? { + let keychainToken = loadTokenFromKeychain() + let fileToken = loadTokenFromFile() + + var candidates: [WatchToken] = [] + if let keychainToken { candidates.append(keychainToken) } + if let fileToken { candidates.append(fileToken) } + + if let preferredStudentIdNorm { + let filtered = candidates.filter { $0.studentIdNorm == preferredStudentIdNorm } + if !filtered.isEmpty { + candidates = filtered + } + } + + return candidates.dropFirst().reduce(candidates.first) { best, candidate in + guard let best else { return candidate } + return candidate.isNewer(than: best) ? candidate : best + } + } + + private func probeSharedKeychainTokenWithTimeout() async -> WatchToken? { + await withTaskGroup(of: WatchToken?.self) { group in + group.addTask { + SharedKeychainManager.shared.loadToken() + } + group.addTask { [iCloudProbeTimeoutNs] in + try? await Task.sleep(nanoseconds: iCloudProbeTimeoutNs) + return nil + } + + let first = await group.next() ?? nil + group.cancelAll() + return first + } + } + + private init() { + runKVStoreMigrationIfNeeded() + } + + private let kvStoreMigrationKey = "firka_kv_store_migrated_v1" + + private func runKVStoreMigrationIfNeeded() { + let alreadyMigrated = UserDefaults.standard.bool(forKey: kvStoreMigrationKey) + if alreadyMigrated { + return + } + + print("[TokenManager] Running KV Store migration...") + + if let migratedToken = SharedKeychainManager.shared.migrateFromKVStoreAndClear() { + SharedKeychainManager.shared.saveToken(migratedToken) + + try? saveTokenToKeychain(migratedToken) + try? saveTokenToFile(migratedToken) + setActiveStudentIdNorm(migratedToken.studentIdNorm) + + print("[TokenManager] KV Store migration completed, token migrated") + } else { + SharedKeychainManager.shared.clearKVStore() + print("[TokenManager] KV Store migration completed, no token to migrate") + } + + UserDefaults.standard.set(true, forKey: kvStoreMigrationKey) + } + + #if os(iOS) + private func notifyiOSTokenRecovered() { + print("[TokenManager] Valid token received from iCloud, notifying Flutter to clear reauth flag") + DispatchQueue.main.async { + NotificationCenter.default.post( + name: Notification.Name("TokenRecoveredFromiCloud"), + object: nil + ) + } + } + #endif + + // MARK: - File Management + private func getTokenFilePath() -> URL? { + guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupID) else { + return nil + } + return containerURL.appendingPathComponent(tokenFileName) + } + + // MARK: - Load Token (active-account first) + func loadToken() -> WatchToken? { + let sharedKeychainToken = SharedKeychainManager.shared.loadToken() + let keychainToken = loadTokenFromKeychain() + let fileToken = loadTokenFromFile() + + var candidates: [(token: WatchToken, source: String)] = [] + if let t = sharedKeychainToken { candidates.append((t, "sharedKeychain")) } + if let t = keychainToken { candidates.append((t, "keychain")) } + if let t = fileToken { candidates.append((t, "file")) } + + guard !candidates.isEmpty else { + print("[TokenManager] No token found anywhere") + return nil + } + + var preferredStudentIdNorm = getActiveStudentIdNorm() + var requirePreferredAccount = false + #if os(watchOS) + if let sessionState = SharedSessionStateManager.shared.loadState() { + if !sessionState.hasAnyAccount { + print("[TokenManager] Shared session state indicates no active accounts, returning no token") + return nil + } + if let sharedActiveStudentIdNorm = sessionState.activeStudentIdNorm { + preferredStudentIdNorm = sharedActiveStudentIdNorm + requirePreferredAccount = true + if getActiveStudentIdNorm() != sharedActiveStudentIdNorm { + setActiveStudentIdNorm(sharedActiveStudentIdNorm) + } + } + } + #endif + + let freshest: (token: WatchToken, source: String) + if let preferredStudentIdNorm { + let filtered = candidates.filter { $0.token.studentIdNorm == preferredStudentIdNorm } + if let preferredFreshest = filtered.dropFirst().reduce(filtered.first) { best, candidate in + guard let best else { return candidate } + return candidate.token.isNewer(than: best.token) ? candidate : best + } { + freshest = preferredFreshest + } else { + if requirePreferredAccount { + print("[TokenManager] Active shared-session account token (\(preferredStudentIdNorm)) not found yet, falling back to best available token") + #if os(watchOS) + if WCSession.default.activationState == .activated && WCSession.default.isReachable { + print("[TokenManager] iPhone reachable, requesting active account token") + WatchConnectivityManager.shared.requestTokenFromPhone() + } + #endif + } + freshest = candidates.dropFirst().reduce(candidates[0]) { currentBest, candidate in + candidate.token.isNewer(than: currentBest.token) ? candidate : currentBest + } + } + } else { + freshest = candidates.dropFirst().reduce(candidates[0]) { currentBest, candidate in + candidate.token.isNewer(than: currentBest.token) ? candidate : currentBest + } + } + let previousActiveStudentIdNorm = getActiveStudentIdNorm() + setActiveStudentIdNorm(freshest.token.studentIdNorm) + + #if os(iOS) + if previousActiveStudentIdNorm != freshest.token.studentIdNorm { + _ = SharedSessionStateManager.shared.publishState( + hasAnyAccount: true, + activeStudentIdNorm: freshest.token.studentIdNorm + ) + print("[TokenManager] Active account changed from \(previousActiveStudentIdNorm ?? 0) to \(freshest.token.studentIdNorm), published to SharedSessionState") + } + #endif + + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss" + formatter.timeZone = TimeZone.current + + print("[TokenManager] Token sources found: \(candidates.map { "\($0.source): \($0.token.studentIdNorm) @ \(formatter.string(from: $0.token.expiryDate))" }.joined(separator: ", "))") + print("[TokenManager] Using selected token from \(freshest.source) (expiry: \(formatter.string(from: freshest.token.expiryDate)))") + + if keychainToken == nil || + keychainToken!.studentIdNorm != freshest.token.studentIdNorm || + freshest.token.isNewer(than: keychainToken!) { + print("[TokenManager] Syncing fresher token to keychain") + try? saveTokenToKeychain(freshest.token) + } + if fileToken == nil || + fileToken!.studentIdNorm != freshest.token.studentIdNorm || + freshest.token.isNewer(than: fileToken!) { + print("[TokenManager] Syncing fresher token to file") + try? saveTokenToFile(freshest.token) + } + + return freshest.token + } + + private func loadTokenFromFile() -> WatchToken? { + guard let filePath = getTokenFilePath() else { + return nil + } + + do { + let data = try Data(contentsOf: filePath) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return try decoder.decode(WatchToken.self, from: data) + } catch { + return nil + } + } + + // MARK: - Delete Token + func deleteToken() { + print("[TokenManager] Deleting token from all storage locations") + + SharedSessionStateManager.shared.publishState(hasAnyAccount: false, activeStudentIdNorm: nil) + + if let previousToken = loadToken() { + RefreshLeaseManager.shared.clearLeases(studentIdNorm: previousToken.studentIdNorm) + } else { + RefreshLeaseManager.shared.clearAllLeases() + } + deleteTokenFromKeychain() + SharedKeychainManager.shared.deleteToken() + UserDefaults.standard.removeObject(forKey: activeStudentIdNormKey) + + guard let filePath = getTokenFilePath() else { return } + try? FileManager.default.removeItem(at: filePath) + } + + // MARK: - Save Token + func saveToken( + _ token: WatchToken, + syncToSharedKeychain: Bool = false, + forceAccountSwitch: Bool = false + ) throws { + let currentToken = loadToken() + if let currentToken { + if forceAccountSwitch && !token.isSameAccount(as: currentToken) { + print("[TokenManager] Forcing token save for explicit account switch (\(currentToken.studentIdNorm) -> \(token.studentIdNorm))") + } else if !token.isNewer(than: currentToken) { + print("[TokenManager] Ignoring stale or same token save attempt") + return + } + } + + if forceAccountSwitch, + let currentToken, + !token.isSameAccount(as: currentToken) { + RefreshLeaseManager.shared.clearLeases(studentIdNorm: currentToken.studentIdNorm) + } + + print("[TokenManager] Saving token locally (Keychain + file)") + setActiveStudentIdNorm(token.studentIdNorm) + + try saveTokenToKeychain(token) + + if syncToSharedKeychain { + SharedKeychainManager.shared.saveToken(token, forceAccountSwitch: forceAccountSwitch) + } + + guard let filePath = getTokenFilePath() else { + throw TokenError.networkError + } + + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(token) + try data.write(to: filePath) + } + + private func saveTokenToFile(_ token: WatchToken) throws { + guard let filePath = getTokenFilePath() else { + throw TokenError.networkError + } + + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(token) + try data.write(to: filePath) + } + + // MARK: - Keychain Methods + func saveTokenToKeychain(_ token: WatchToken) throws { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(token) + + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.keychainService, + kSecAttrAccount as String: Self.keychainAccount + ] + SecItemDelete(deleteQuery as CFDictionary) + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.keychainService, + kSecAttrAccount as String: Self.keychainAccount, + kSecValueData as String: data, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock + ] + + let status = SecItemAdd(addQuery as CFDictionary, nil) + guard status == errSecSuccess else { + print("[TokenManager] Keychain save failed: \(status)") + throw TokenError.networkError + } + print("[TokenManager] Token saved to Keychain") + } + + func loadTokenFromKeychain() -> WatchToken? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.keychainService, + kSecAttrAccount as String: Self.keychainAccount, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + guard status == errSecSuccess, let data = result as? Data else { + return nil + } + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + if let token = try? decoder.decode(WatchToken.self, from: data) { + return token + } + + if let legacyToken = try? JSONDecoder().decode(WatchToken.self, from: data) { + try? saveTokenToKeychain(legacyToken) + return legacyToken + } + + return nil + } + + func deleteTokenFromKeychain() { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.keychainService, + kSecAttrAccount as String: Self.keychainAccount + ] + + SecItemDelete(query as CFDictionary) + print("[TokenManager] Token deleted from Keychain") + } + + // MARK: - Check Expiry + func isTokenExpired() -> Bool { + guard let token = loadToken() else { + return true + } + + let expiryThreshold = token.expiryDate.addingTimeInterval(-60) + return Date() >= expiryThreshold + } + + func shouldRefreshProactively() -> Bool { + guard let token = loadToken() else { + return false + } + + let proactiveThreshold = token.expiryDate.addingTimeInterval(-proactiveRefreshLeadTime) + return Date() >= proactiveThreshold + } + + func refreshTokenProactively() async { + guard loadToken() != nil else { + print("[TokenManager] No token available for proactive refresh") + return + } + + guard shouldRefreshProactively() else { + print("[TokenManager] Token is not close to expiry, no proactive refresh needed") + return + } + + let now = Date() + if let lastAttempt = lastProactiveRefreshAttemptAt, + now.timeIntervalSince(lastAttempt) < minimumProactiveRefreshInterval { + print("[TokenManager] Proactive refresh skipped due to cooldown") + return + } + lastProactiveRefreshAttemptAt = now + + print("[TokenManager] Proactively refreshing token...") + do { + guard let token = loadToken() else { + print("[TokenManager] Token disappeared before proactive refresh") + return + } + _ = try await refreshTokenInternal(token) + clearLastRecoveryFailure() + print("[TokenManager] Proactive token refresh succeeded") + } catch { + if let tokenError = error as? TokenError { + lastRecoveryFailure = tokenError + } else { + lastRecoveryFailure = .networkError + } + print("[TokenManager] Proactive token refresh failed: \(error)") + } + } + + // MARK: - Central Token Recovery + func recoverToken() async -> WatchToken? { + clearLastRecoveryFailure() + + if let validToken = loadToken(), !isTokenExpired() { + print("[TokenManager] Existing token is valid, skipping recovery flow") + clearLastRecoveryFailure() + return validToken + } + + if !startRecoveryIfNeeded() { + print("[TokenManager] Recovery already in progress, waiting for current recovery...") + for _ in 0..<40 { + if let token = loadToken(), !isTokenExpired() { + print("[TokenManager] Current recovery produced a valid token") + return token + } + + if !isRecoveryRunning() { + break + } + try? await Task.sleep(nanoseconds: 250_000_000) + } + + if let token = loadToken(), !isTokenExpired() { + print("[TokenManager] Valid token became available after waiting") + return token + } + + print("[TokenManager] Existing recovery did not yield a valid token") + return nil + } + + defer { finishRecovery() } + + print("[TokenManager] Starting central token recovery...") + + if let sharedToken = await probeSharedKeychainTokenWithTimeout() { + let now = Date() + if let preferredStudentIdNorm = getActiveStudentIdNorm(), + sharedToken.studentIdNorm != preferredStudentIdNorm, + localTokenFromKeychainAndFile(preferredStudentIdNorm: preferredStudentIdNorm) != nil { + print("[TokenManager] Shared Keychain probe token belongs to inactive account, skipping direct apply") + } else if sharedToken.expiryDate > now.addingTimeInterval(60) { + print("[TokenManager] Shared Keychain probe found valid token, applying without recovery") + do { + try saveToken(sharedToken, syncToSharedKeychain: false) + clearLastRecoveryFailure() + return sharedToken + } catch { + print("[TokenManager] Failed to apply shared Keychain probe token: \(error)") + } + } else { + print("[TokenManager] Shared Keychain probe token exists but access is expired, continuing with refresh path") + } + } else { + print("[TokenManager] Shared Keychain probe timed out or no token available, continuing with refresh path") + } + + print("[TokenManager] Step 1: Trying local token refresh...") + if let token = loadToken() { + if token.expiryDate > Date().addingTimeInterval(60) { + print("[TokenManager] Step 1 SUCCESS: Local token already valid") + clearLastRecoveryFailure() + return token + } + do { + let refreshedToken = try await refreshTokenInternal(token) + print("[TokenManager] Step 1 SUCCESS: Local refresh succeeded") + clearLastRecoveryFailure() + return refreshedToken + } catch { + print("[TokenManager] Step 1 FAILED: Local refresh failed: \(error)") + if let tokenError = error as? TokenError { + lastRecoveryFailure = tokenError + if tokenError == .networkError { + print("[TokenManager] Step 1 detected network error, aborting recovery flow") + return nil + } + } + } + } else { + print("[TokenManager] Step 1 SKIPPED: No local token found") + } + + print("[TokenManager] Step 2: Checking Keychain and WatchConnectivity...") + if let recoveredToken = await tryRecoverFromKeychainAndWatch() { + if recoveredToken.expiryDate > Date().addingTimeInterval(60) { + print("[TokenManager] Step 2 SUCCESS: Keychain/Watch token is already valid") + try? saveToken(recoveredToken, syncToSharedKeychain: false) + clearLastRecoveryFailure() + return recoveredToken + } else { + do { + let refreshedToken = try await refreshTokenInternal(recoveredToken) + print("[TokenManager] Step 2 SUCCESS: Keychain/Watch token refresh succeeded") + clearLastRecoveryFailure() + return refreshedToken + } catch { + print("[TokenManager] Step 2 FAILED: Keychain/Watch token refresh failed: \(error)") + if let tokenError = error as? TokenError { + lastRecoveryFailure = tokenError + if tokenError == .networkError { + print("[TokenManager] Step 2 detected network error, aborting recovery flow") + return nil + } + } + } + } + } else { + print("[TokenManager] Step 2 SKIPPED: No token from Keychain/Watch") + } + + print("[TokenManager] Step 3: Trying shared Keychain recovery with retries...") + let retryDelays: [TimeInterval] = [0, 5, 10, 5, 10] + var sharedKeychainHasToken = false + + for (attempt, delay) in retryDelays.enumerated() { + if delay > 0 { + if !sharedKeychainHasToken && attempt > 0 { + print("[TokenManager] Step 3: Skipping retries - shared Keychain has no token") + break + } + print("[TokenManager] Step 3: Waiting \(Int(delay))s before attempt \(attempt + 1)...") + try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + } + + print("[TokenManager] Step 3: Shared Keychain attempt \(attempt + 1)/\(retryDelays.count)...") + + if let sharedToken = SharedKeychainManager.shared.loadToken() { + if let preferredStudentIdNorm = getActiveStudentIdNorm(), + sharedToken.studentIdNorm != preferredStudentIdNorm { + if localTokenFromKeychainAndFile( + preferredStudentIdNorm: preferredStudentIdNorm + ) != nil { + print("[TokenManager] Step 3: Ignoring shared Keychain token for inactive account (\(sharedToken.studentIdNorm)), active is \(preferredStudentIdNorm)") + continue + } + print("[TokenManager] Step 3: Active account token missing locally, considering different-account shared Keychain token") + } + sharedKeychainHasToken = true + if sharedToken.expiryDate > Date() { + print("[TokenManager] Step 3 SUCCESS: Found valid shared Keychain token, applying without immediate refresh") + try? saveToken(sharedToken, syncToSharedKeychain: false) + clearLastRecoveryFailure() + return sharedToken + } else { + print("[TokenManager] Step 3: Shared Keychain token is expired, trying refresh anyway...") + do { + let refreshedToken = try await refreshTokenInternal(sharedToken) + print("[TokenManager] Step 3 SUCCESS: Expired shared Keychain token refresh succeeded on attempt \(attempt + 1)") + clearLastRecoveryFailure() + return refreshedToken + } catch { + print("[TokenManager] Step 3: Expired shared Keychain token refresh failed on attempt \(attempt + 1): \(error)") + if let tokenError = error as? TokenError { + lastRecoveryFailure = tokenError + if tokenError == .networkError { + print("[TokenManager] Step 3 detected network error, aborting retries") + return nil + } + } + } + } + } else { + print("[TokenManager] Step 3: No token in shared Keychain on attempt \(attempt + 1)") + if attempt == 0 { + sharedKeychainHasToken = false + } + } + } + + print("[TokenManager] All recovery attempts failed") + if lastRecoveryFailure == nil { + lastRecoveryFailure = .noToken + } + return nil + } + + private func tryRecoverFromKeychainAndWatch() async -> WatchToken? { + var candidates: [(token: WatchToken, source: String)] = [] + + if let keychainToken = loadTokenFromKeychain() { + candidates.append((keychainToken, "keychain")) + print("[TokenManager] Found token in Keychain") + } + + if let fileToken = loadTokenFromFile() { + candidates.append((fileToken, "file")) + print("[TokenManager] Found token in file storage") + } + + #if os(watchOS) + if let watchToken = await requestTokenFromiPhoneForRecovery() { + candidates.append((watchToken, "WatchConnectivity")) + print("[TokenManager] Found token from iPhone via WatchConnectivity") + } + #endif + + guard !candidates.isEmpty else { + return nil + } + + if let preferredStudentIdNorm = getActiveStudentIdNorm() { + let filtered = candidates.filter { $0.token.studentIdNorm == preferredStudentIdNorm } + if !filtered.isEmpty { + candidates = filtered + } else { + print("[TokenManager] No recovery candidate for active account \(preferredStudentIdNorm)") + return nil + } + } + + let freshest = candidates.dropFirst().reduce(candidates[0]) { currentBest, candidate in + candidate.token.isNewer(than: currentBest.token) ? candidate : currentBest + } + print("[TokenManager] Using freshest token from \(freshest.source)") + return freshest.token + } + + #if os(watchOS) + private func requestTokenFromiPhoneForRecovery() async -> WatchToken? { + guard WCSession.default.activationState == .activated, + WCSession.default.isReachable else { + print("[TokenManager] iPhone not reachable for recovery") + return nil + } + + let now = Date() + if let lastPhoneRecoveryRequestAt, + now.timeIntervalSince(lastPhoneRecoveryRequestAt) < 5 { + print("[TokenManager] Skipping iPhone recovery request due to cooldown") + return nil + } + lastPhoneRecoveryRequestAt = now + + let timeoutSeconds: UInt64 = 10 + + return await withTaskGroup(of: WatchToken?.self) { group in + group.addTask { + do { + try await Task.sleep(nanoseconds: timeoutSeconds * 1_000_000_000) + } catch { + return nil + } + if Task.isCancelled { + return nil + } + print("[TokenManager] iPhone request timed out after \(timeoutSeconds)s") + return nil + } + + group.addTask { + await withCheckedContinuation { continuation in + var hasResumed = false + let resumeOnce: (WatchToken?) -> Void = { token in + guard !hasResumed else { return } + hasResumed = true + continuation.resume(returning: token) + } + + WCSession.default.sendMessage( + ["action": "requestToken"], + replyHandler: { response in + if let authDict = response["auth"] as? [String: Any] { + do { + let jsonData = try JSONSerialization.data(withJSONObject: authDict) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let timestamp = try container.decode(Int64.self) + return Date(timeIntervalSince1970: Double(timestamp) / 1000.0) + } + let token = try decoder.decode(WatchToken.self, from: jsonData) + print("[TokenManager] Received token from iPhone for recovery") + resumeOnce(token) + } catch { + print("[TokenManager] Failed to decode iPhone token: \(error)") + resumeOnce(nil) + } + } else { + print("[TokenManager] iPhone returned no token for recovery") + resumeOnce(nil) + } + }, + errorHandler: { error in + print("[TokenManager] iPhone request failed: \(error)") + resumeOnce(nil) + } + ) + } + } + + if let result = await group.next() { + group.cancelAll() + return result + } + return nil + } + } + #endif + + private func refreshTokenInternal(_ token: WatchToken) async throws -> WatchToken { + #if os(watchOS) + return try await withWatchRefreshLease(studentIdNorm: token.studentIdNorm) { + let response = try await performTokenRefresh( + refreshToken: token.refreshToken, + instituteCode: token.iss + ) + let nowMs = Int64(Date().timeIntervalSince1970 * 1000) + let tokenVersion = WatchToken.extractIatMillis(from: response.idToken) ?? nowMs + + let newToken = WatchToken( + accessToken: response.accessToken, + refreshToken: response.refreshToken, + idToken: response.idToken, + iss: token.iss, + studentId: token.studentId, + studentIdNorm: token.studentIdNorm, + expiryDate: Date().addingTimeInterval(Double(response.expiresIn) - 60), + tokenVersion: tokenVersion, + updatedAtMs: nowMs + ) + + try saveToken(newToken, syncToSharedKeychain: true) + WatchConnectivityManager.shared.sendTokenToiPhoneInBackground() + return newToken + } + #else + let response = try await performTokenRefresh( + refreshToken: token.refreshToken, + instituteCode: token.iss + ) + let nowMs = Int64(Date().timeIntervalSince1970 * 1000) + let tokenVersion = WatchToken.extractIatMillis(from: response.idToken) ?? nowMs + + let newToken = WatchToken( + accessToken: response.accessToken, + refreshToken: response.refreshToken, + idToken: response.idToken, + iss: token.iss, + studentId: token.studentId, + studentIdNorm: token.studentIdNorm, + expiryDate: Date().addingTimeInterval(Double(response.expiresIn) - 60), + tokenVersion: tokenVersion, + updatedAtMs: nowMs + ) + + try saveToken(newToken, syncToSharedKeychain: true) + return newToken + #endif + } + + // MARK: - Refresh Token + func refreshToken() async throws -> WatchToken { + guard let currentToken = loadToken() else { + throw TokenError.noToken + } + + #if os(watchOS) + return try await withWatchRefreshLease(studentIdNorm: currentToken.studentIdNorm) { + let response = try await performTokenRefresh( + refreshToken: currentToken.refreshToken, + instituteCode: currentToken.iss + ) + let nowMs = Int64(Date().timeIntervalSince1970 * 1000) + let tokenVersion = WatchToken.extractIatMillis(from: response.idToken) ?? nowMs + + let newToken = WatchToken( + accessToken: response.accessToken, + refreshToken: response.refreshToken, + idToken: response.idToken, + iss: currentToken.iss, + studentId: currentToken.studentId, + studentIdNorm: currentToken.studentIdNorm, + expiryDate: Date().addingTimeInterval(Double(response.expiresIn) - 60), + tokenVersion: tokenVersion, + updatedAtMs: nowMs + ) + + try saveToken(newToken, syncToSharedKeychain: true) + WatchConnectivityManager.shared.sendTokenToiPhoneInBackground() + return newToken + } + #else + let response = try await performTokenRefresh( + refreshToken: currentToken.refreshToken, + instituteCode: currentToken.iss + ) + let nowMs = Int64(Date().timeIntervalSince1970 * 1000) + let tokenVersion = WatchToken.extractIatMillis(from: response.idToken) ?? nowMs + + let newToken = WatchToken( + accessToken: response.accessToken, + refreshToken: response.refreshToken, + idToken: response.idToken, + iss: currentToken.iss, + studentId: currentToken.studentId, + studentIdNorm: currentToken.studentIdNorm, + expiryDate: Date().addingTimeInterval(Double(response.expiresIn) - 60), + tokenVersion: tokenVersion, + updatedAtMs: nowMs + ) + + try saveToken(newToken, syncToSharedKeychain: true) + return newToken + #endif + } + + // MARK: - Private Helper Methods + private func performTokenRefresh( + refreshToken: String, + instituteCode: String + ) async throws -> TokenRefreshResponse { + guard let url = URL(string: tokenRefreshURL) else { + throw TokenError.networkError + } + + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type") + request.setValue(userAgent, forHTTPHeaderField: "User-Agent") + request.setValue("*/*", forHTTPHeaderField: "Accept") + request.timeoutInterval = refreshRequestTimeout + + let formParameters: [String: String] = [ + "institute_code": instituteCode, + "refresh_token": refreshToken, + "grant_type": "refresh_token", + "client_id": clientID + ] + + request.httpBody = encodeFormData(formParameters).data(using: .utf8) + + do { + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = refreshRequestTimeout + configuration.timeoutIntervalForResource = refreshResourceTimeout + let session = URLSession(configuration: configuration) + let (data, response) = try await session.data(for: request) + + guard let httpResponse = response as? HTTPURLResponse else { + throw TokenError.networkError + } + + switch httpResponse.statusCode { + case 200: + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return try decoder.decode(TokenRefreshResponse.self, from: data) + + case 400: + throw TokenError.refreshExpired + + case 401: + throw TokenError.invalidGrant + + default: + throw TokenError.invalidResponse + } + } catch let error as TokenError { + throw error + } catch { + throw TokenError.networkError + } + } + + private func encodeFormData(_ parameters: [String: String]) -> String { + return parameters + .map { key, value in + let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? key + let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? value + return "\(encodedKey)=\(encodedValue)" + } + .joined(separator: "&") + } +} diff --git a/firka/ios/Shared/Helpers/SeasonalIconHelper.swift b/firka/ios/Shared/Helpers/SeasonalIconHelper.swift new file mode 100644 index 00000000..a753cab7 --- /dev/null +++ b/firka/ios/Shared/Helpers/SeasonalIconHelper.swift @@ -0,0 +1,92 @@ +import SwiftUI + +struct SeasonalIconHelper { + static func iconName(for mode: String?, season: String?, lessonIcon: String? = nil) -> String { + guard let mode = mode else { + return lessonIcon ?? "book.fill" + } + + switch mode { + case "xmas": + return "gift.fill" + case "newYearEve": + return "party.popper.fill" + case "newYearDay": + return "sparkles" + case "beforeSchool": + return "sun.horizon.fill" + case "seasonalBreak": + guard let season = season else { + return "snowflake" + } + switch season { + case "spring": + return "flower.fill" + case "summer": + return "sun.max.fill" + case "autumn": + return "leaf.fill" + case "winter": + return "snowflake" + case "other": + return "calendar.badge.exclamationmark" + default: + return "snowflake" + } + case "lesson": + return lessonIcon ?? "book.fill" + default: + return lessonIcon ?? "book.fill" + } + } + + static func iconColor(for mode: String?, season: String? = nil) -> Color { + guard let mode = mode else { + return .green + } + + switch mode { + case "beforeSchool": + return .orange + case "xmas": + return .red + case "newYearEve": + return .purple + case "newYearDay": + return Color(red: 0.4, green: 0.9, blue: 0.8) + case "seasonalBreak": + return seasonColor(for: season) + default: + return .green + } + } + + static func seasonColor(for season: String?) -> Color { + guard let season = season else { + return .blue + } + + switch season { + case "spring": + return .green + case "summer": + return .blue + case "autumn": + return .orange + case "winter": + return Color(red: 0.4, green: 0.8, blue: 1.0) + case "other": + return .blue + default: + return .blue + } + } + + static func isSeasonalMode(_ mode: String?) -> Bool { + guard let mode = mode else { + return false + } + return mode == "seasonalBreak" || mode == "xmas" || mode == "newYearEve" || mode == "newYearDay" + } +} + diff --git a/firka/ios/Shared/Models/Average.swift b/firka/ios/Shared/Models/Average.swift new file mode 100644 index 00000000..8a8ce00e --- /dev/null +++ b/firka/ios/Shared/Models/Average.swift @@ -0,0 +1,18 @@ +import Foundation +import SwiftUI + +extension SubjectAverage { + var averageColor: Color { + switch average { + case 4.5...: return .green + case 3.5..<4.5: return .blue + case 2.5..<3.5: return .yellow + case 1.5..<2.5: return .orange + default: return .red + } + } + + var formattedAverage: String { + String(format: "%.2f", average) + } +} diff --git a/firka/ios/Shared/Models/Grade.swift b/firka/ios/Shared/Models/Grade.swift new file mode 100644 index 00000000..3ee5efe2 --- /dev/null +++ b/firka/ios/Shared/Models/Grade.swift @@ -0,0 +1,119 @@ +import Foundation +import SwiftUI + +struct WidgetGrade: Codable, Identifiable { + let uid: String + let recordDate: Date + let subject: WidgetSubject + let topic: String? + let type: NameUidDesc + let valueType: NameUidDesc? + let numericValue: Int? + let strValue: String? + let weightPercentage: Int? + + var id: String { uid } + + init(uid: String, recordDate: Date, subject: WidgetSubject, topic: String?, + type: NameUidDesc, valueType: NameUidDesc?, numericValue: Int?, strValue: String?, weightPercentage: Int?) { + self.uid = uid + self.recordDate = recordDate + self.subject = subject + self.topic = topic + self.type = type + self.valueType = valueType + self.numericValue = numericValue + self.strValue = strValue + self.weightPercentage = weightPercentage + } + + var isPercentageGrade: Bool { + valueType?.name.lowercased().contains("szazalekos") ?? false + } + + static func percentageToGrade(_ percentage: Int) -> Int { + if percentage < 50 { return 1 } + if percentage < 60 { return 2 } + if percentage < 70 { return 3 } + if percentage < 80 { return 4 } + return 5 + } + + var normalizedNumericValue: Int? { + guard let numeric = numericValue else { return nil } + if isPercentageGrade { + return WidgetGrade.percentageToGrade(numeric) + } + return numeric + } + + var displayValue: String { + if let numeric = numericValue { + return "\(numeric)" + } + return strValue ?? "" + } + + var dateString: String { + let formatter = DateFormatter() + formatter.dateFormat = "MMM d." + return formatter.string(from: recordDate) + } + + var gradeColor: Color { + guard let value = normalizedNumericValue else { return .gray } + switch value { + case 5: return .green + case 4: return .blue + case 3: return .yellow + case 2: return .orange + case 1: return .red + default: return .gray + } + } + + var subjectNameWithWeight: String { + if let weight = weightPercentage, weight != 100 { + return "\(subject.name) (\(weight)%)" + } + return subject.name + } + + var teacherName: String? { + subject.teacherName + } +} + +extension WidgetGrade { + var displayType: String { + let typeMap: [String: String] = [ + "evkozi_jegy_ertekeles": "Órai munka", + "felevi_jegy_ertekeles": "Félévi jegy", + "evvegi_jegy_ertekeles": "Év végi jegy", + "dolgozat": "Dolgozat", + "ropdolgozat": "Röpdolgozat", + "hazi_feladat": "Házi feladat", + "osztalyzat": "Osztályzat", + "szorgalom": "Szorgalom", + "magatartas": "Magatartás" + ] + return typeMap[type.name.lowercased()] ?? type.name.replacingOccurrences(of: "_", with: " ").capitalized + } + + var displayTypeWithWeight: String { + if let weight = weightPercentage, weight != 100 { + return "\(displayType) (\(weight)%)" + } + return displayType + } + + var displayGradeValue: String { + if isPercentageGrade, let numeric = numericValue { + return "\(numeric)%" + } + if let numeric = numericValue { + return "\(numeric)" + } + return strValue ?? "" + } +} diff --git a/firka/ios/Shared/Models/Lesson.swift b/firka/ios/Shared/Models/Lesson.swift new file mode 100644 index 00000000..2b72f183 --- /dev/null +++ b/firka/ios/Shared/Models/Lesson.swift @@ -0,0 +1,56 @@ +import Foundation + +struct WidgetLesson: Codable, Identifiable { + let uid: String + let date: String + let start: Date + let end: Date + let name: String + let lessonNumber: Int? + let teacher: String? + let substituteTeacher: String? + let subject: WidgetSubject + let theme: String? + let roomName: String? + let isCancelled: Bool + let isSubstitution: Bool + + var id: String { uid } + + init(uid: String, date: String, start: Date, end: Date, name: String, + lessonNumber: Int?, teacher: String?, substituteTeacher: String?, subject: WidgetSubject, + theme: String?, roomName: String?, isCancelled: Bool, isSubstitution: Bool) { + self.uid = uid + self.date = date + self.start = start + self.end = end + self.name = name + self.lessonNumber = lessonNumber + self.teacher = teacher + self.substituteTeacher = substituteTeacher + self.subject = subject + self.theme = theme + self.roomName = roomName + self.isCancelled = isCancelled + self.isSubstitution = isSubstitution + } + + var displayName: String { + subject.name + } + + var timeString: String { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter.string(from: start) + } + + var isCurrentlyActive: Bool { + let now = Date() + return now >= start && now <= end + } + + var isUpcoming: Bool { + return Date() < start + } +} diff --git a/firka/ios/Shared/Models/Subject.swift b/firka/ios/Shared/Models/Subject.swift new file mode 100644 index 00000000..210bb4ee --- /dev/null +++ b/firka/ios/Shared/Models/Subject.swift @@ -0,0 +1,29 @@ +import Foundation + +struct WidgetSubject: Codable { + let uid: String + let name: String + let category: NameUidDesc? + let sortIndex: Int? + let teacherName: String? + + init(uid: String, name: String, category: NameUidDesc?, sortIndex: Int?, teacherName: String?) { + self.uid = uid + self.name = name + self.category = category + self.sortIndex = sortIndex + self.teacherName = teacherName + } +} + +struct NameUidDesc: Codable { + let uid: String + let name: String + let description: String? + + init(uid: String, name: String, description: String?) { + self.uid = uid + self.name = name + self.description = description + } +} diff --git a/firka/ios/Shared/Models/WatchToken.swift b/firka/ios/Shared/Models/WatchToken.swift new file mode 100644 index 00000000..d0b703e4 --- /dev/null +++ b/firka/ios/Shared/Models/WatchToken.swift @@ -0,0 +1,167 @@ +import Foundation + +// MARK: - Token Structure +struct WatchToken: Codable { + let accessToken: String + let refreshToken: String + let idToken: String + let iss: String + let studentId: String + let studentIdNorm: Int64 + let expiryDate: Date + let tokenVersion: Int64? + let updatedAtMs: Int64? + + init( + accessToken: String, + refreshToken: String, + idToken: String, + iss: String, + studentId: String, + studentIdNorm: Int64, + expiryDate: Date, + tokenVersion: Int64? = nil, + updatedAtMs: Int64? = nil + ) { + self.accessToken = accessToken + self.refreshToken = refreshToken + self.idToken = idToken + self.iss = iss + self.studentId = studentId + self.studentIdNorm = studentIdNorm + self.expiryDate = expiryDate + self.tokenVersion = tokenVersion + self.updatedAtMs = updatedAtMs + } + + enum CodingKeys: String, CodingKey { + case accessToken + case refreshToken + case idToken + case iss + case studentId + case studentIdNorm + case expiryDate + case tokenVersion + case updatedAtMs + } + + var effectiveTokenVersion: Int64? { + if let tokenVersion, tokenVersion > 0 { + return tokenVersion + } + return Self.extractIatMillis(from: idToken) + } + + var effectiveUpdatedAtMs: Int64? { + if let updatedAtMs, updatedAtMs > 0 { + return updatedAtMs + } + return nil + } + + func isSameAccount(as other: WatchToken) -> Bool { + return iss == other.iss && studentIdNorm == other.studentIdNorm + } + + func isNewer(than other: WatchToken) -> Bool { + if !isSameAccount(as: other) { + let incomingUpdatedAt = effectiveUpdatedAtMs + let currentUpdatedAt = other.effectiveUpdatedAtMs + if let incomingUpdatedAt, let currentUpdatedAt, incomingUpdatedAt != currentUpdatedAt { + return incomingUpdatedAt > currentUpdatedAt + } + if let _ = incomingUpdatedAt, currentUpdatedAt == nil { + return true + } + if incomingUpdatedAt == nil, let _ = currentUpdatedAt { + return false + } + + let incomingVersion = effectiveTokenVersion + let currentVersion = other.effectiveTokenVersion + if let incomingVersion, let currentVersion, incomingVersion != currentVersion { + return incomingVersion > currentVersion + } + if let _ = incomingVersion, currentVersion == nil { + return true + } + if incomingVersion == nil, let _ = currentVersion { + return false + } + + if expiryDate != other.expiryDate { + return expiryDate > other.expiryDate + } + return false + } + + let incomingVersion = effectiveTokenVersion + let currentVersion = other.effectiveTokenVersion + if let incomingVersion, let currentVersion, incomingVersion != currentVersion { + return incomingVersion > currentVersion + } + + if expiryDate != other.expiryDate { + return expiryDate > other.expiryDate + } + + let incomingUpdatedAt = effectiveUpdatedAtMs + let currentUpdatedAt = other.effectiveUpdatedAtMs + if let incomingUpdatedAt, let currentUpdatedAt, incomingUpdatedAt != currentUpdatedAt { + return incomingUpdatedAt > currentUpdatedAt + } + + if refreshToken != other.refreshToken { + if let _ = incomingUpdatedAt, currentUpdatedAt == nil { + return true + } + if incomingUpdatedAt == nil, let _ = currentUpdatedAt { + return false + } + if let _ = incomingVersion, currentVersion == nil { + return true + } + if incomingVersion == nil, let _ = currentVersion { + return false + } + } + + return false + } + + static func extractIatMillis(from idToken: String) -> Int64? { + let parts = idToken.split(separator: ".") + guard parts.count >= 2 else { + return nil + } + + var payload = String(parts[1]) + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + let padding = payload.count % 4 + if padding > 0 { + payload += String(repeating: "=", count: 4 - padding) + } + + guard let payloadData = Data(base64Encoded: payload), + let json = try? JSONSerialization.jsonObject(with: payloadData) as? [String: Any] else { + return nil + } + + if let iatInt = json["iat"] as? Int { + return Int64(iatInt) * 1000 + } + if let iatInt64 = json["iat"] as? Int64 { + return iatInt64 * 1000 + } + if let iatDouble = json["iat"] as? Double { + return Int64(iatDouble * 1000) + } + if let iatString = json["iat"] as? String, let iatInt64 = Int64(iatString) { + return iatInt64 * 1000 + } + + return nil + } +} diff --git a/firka/ios/Shared/Models/WidgetColors.swift b/firka/ios/Shared/Models/WidgetColors.swift new file mode 100644 index 00000000..74f4859d --- /dev/null +++ b/firka/ios/Shared/Models/WidgetColors.swift @@ -0,0 +1,30 @@ +import SwiftUI + +struct WidgetColors: Codable { + let background: Int + let textPrimary: Int + let textSecondary: Int + let textTertiary: Int + let card: Int + let accent: Int + let grade5: Int + let grade4: Int + let grade3: Int + let grade2: Int + let grade1: Int + + func color(from argb: Int) -> Color { + let alpha = Double((argb >> 24) & 0xFF) / 255.0 + let red = Double((argb >> 16) & 0xFF) / 255.0 + let green = Double((argb >> 8) & 0xFF) / 255.0 + let blue = Double(argb & 0xFF) / 255.0 + return Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha) + } + + var backgroundColor: Color { color(from: background) } + var textPrimaryColor: Color { color(from: textPrimary) } + var textSecondaryColor: Color { color(from: textSecondary) } + var textTertiaryColor: Color { color(from: textTertiary) } + var cardColor: Color { color(from: card) } + var accentColor: Color { color(from: accent) } +} diff --git a/firka/ios/Shared/Models/WidgetData.swift b/firka/ios/Shared/Models/WidgetData.swift new file mode 100644 index 00000000..5883141e --- /dev/null +++ b/firka/ios/Shared/Models/WidgetData.swift @@ -0,0 +1,142 @@ +import Foundation + +struct WidgetData: Codable { + let lastUpdated: Date? + let locale: String + let theme: String + let timetable: TimetableData + let grades: [WidgetGrade] + let averages: AveragesData + + static var lastError: String = "Not loaded yet" + + static func load() -> WidgetData? { + guard let containerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: "group.app.firkaa.legacy" + ) else { + lastError = "No App Group container" + return nil + } + + let fileURL = containerURL.appendingPathComponent("widget_data.json") + + let fileExists = FileManager.default.fileExists(atPath: fileURL.path) + if !fileExists { + lastError = "File not found at: \(fileURL.path)" + return nil + } + + guard let data = try? Data(contentsOf: fileURL) else { + lastError = "Could not read file" + return nil + } + + lastError = "Read \(data.count) bytes, decoding..." + + let decoder = JSONDecoder() + + let iso8601Full = ISO8601DateFormatter() + iso8601Full.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + let iso8601 = ISO8601DateFormatter() + iso8601.formatOptions = [.withInternetDateTime] + + let formatterLocal = DateFormatter() + formatterLocal.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" + formatterLocal.locale = Locale(identifier: "en_US_POSIX") + formatterLocal.timeZone = TimeZone.current + + let formatterShort = DateFormatter() + formatterShort.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" + formatterShort.locale = Locale(identifier: "en_US_POSIX") + formatterShort.timeZone = TimeZone.current + + decoder.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let dateString = try container.decode(String.self) + + if let date = iso8601Full.date(from: dateString) { + return date + } + if let date = iso8601.date(from: dateString) { + return date + } + if let date = formatterLocal.date(from: dateString) { + return date + } + if let date = formatterShort.date(from: dateString) { + return date + } + + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(dateString)") + } + + do { + let widgetData = try decoder.decode(WidgetData.self, from: data) + lastError = "OK: \(widgetData.timetable.today.count) lessons, \(widgetData.grades.count) grades" + return widgetData + } catch let DecodingError.keyNotFound(key, context) { + lastError = "Missing key: \(key.stringValue) in \(context.codingPath.map { $0.stringValue }.joined(separator: "."))" + return nil + } catch let DecodingError.typeMismatch(type, context) { + lastError = "Type mismatch: \(type) at \(context.codingPath.map { $0.stringValue }.joined(separator: "."))" + return nil + } catch let DecodingError.valueNotFound(type, context) { + lastError = "Null value: \(type) at \(context.codingPath.map { $0.stringValue }.joined(separator: "."))" + return nil + } catch { + lastError = "Other: \(error)" + return nil + } + } + + static var placeholder: WidgetData { + WidgetData( + lastUpdated: nil, + locale: "hu", + theme: "dark", + timetable: TimetableData(today: [], tomorrow: [], nextSchoolDay: nil, nextSchoolDayDate: nil, currentBreak: nil, allLessons: nil), + grades: [], + averages: AveragesData(overall: nil, subjects: []) + ) + } +} + +struct TimetableData: Codable { + let today: [WidgetLesson] + let tomorrow: [WidgetLesson] + let nextSchoolDay: [WidgetLesson]? + let nextSchoolDayDate: String? + let currentBreak: BreakInfo? + let allLessons: [WidgetLesson]? + + init(today: [WidgetLesson], tomorrow: [WidgetLesson], nextSchoolDay: [WidgetLesson]?, + nextSchoolDayDate: String?, currentBreak: BreakInfo?, allLessons: [WidgetLesson]? = nil) { + self.today = today + self.tomorrow = tomorrow + self.nextSchoolDay = nextSchoolDay + self.nextSchoolDayDate = nextSchoolDayDate + self.currentBreak = currentBreak + self.allLessons = allLessons + } +} + +struct BreakInfo: Codable { + let name: String + let nameKey: String + let endDate: Date +} + +struct AveragesData: Codable { + let overall: Double? + let subjects: [SubjectAverage] +} + +struct SubjectAverage: Codable, Identifiable { + let uid: String + let name: String + let average: Double + let gradeCount: Int + + var id: String { uid } +} diff --git a/firka/lib/api/client/kreta_client.dart b/firka/lib/api/client/kreta_client.dart index 02205e21..93b47f6f 100644 --- a/firka/lib/api/client/kreta_client.dart +++ b/firka/lib/api/client/kreta_client.dart @@ -25,10 +25,15 @@ import 'package:firka/core/dev/mock_backend.dart'; import 'package:firka_common/data/models/token_model.dart'; import 'package:firka/core/debug_helper.dart'; import 'package:firka_common/data/util.dart'; +import 'package:firka/services/watch_sync_helper.dart'; import '../token_grant.dart'; +import 'dart:io'; +import 'package:flutter/services.dart'; import 'package:flutter/foundation.dart'; +const _watchChannel = MethodChannel('app.firka/watch_sync'); + const backoffCount = 4; const backoffMin = 100; const backoffStep = 500; @@ -313,6 +318,13 @@ class KretaClient { } Future _setReauthFlag() async { + if (Platform.isIOS) { + try { + _watchChannel.invokeMethod('notifyReauthRequired'); + } catch (e) { + debugPrint('[KretaClient] Watch reauth notification skipped: $e'); + } + } _toastCubit.setActiveToast(ActiveToastType.reauth); debugPrint('[KretaClient] Reauth flag set'); } @@ -320,8 +332,62 @@ class KretaClient { Future _refreshModelWithCrossDeviceLease( TokenModel sourceToken, ) async { - final extended = await extendToken(sourceToken); - return TokenModel.fromResp(extended); + final studentIdNorm = sourceToken.key; + String? leaseOperationId; + + try { + if (Platform.isIOS) { + final watchInstalled = await WatchSyncHelper.isWatchAppInstalled(); + if (watchInstalled) { + final leaseReady = await WatchSyncHelper.waitForWatchRefreshLease( + studentIdNorm: studentIdNorm, + ); + if (!leaseReady) { + throw Exception('watch_refresh_lease_timeout'); + } + leaseOperationId = await WatchSyncHelper.acquireIPhoneRefreshLease( + studentIdNorm: studentIdNorm, + ); + if (leaseOperationId == null) { + throw Exception('iphone_refresh_lease_acquire_failed'); + } + } + } + + final extended = await extendToken(sourceToken); + return TokenModel.fromResp(extended); + } finally { + if (Platform.isIOS && leaseOperationId != null) { + await WatchSyncHelper.releaseIPhoneRefreshLease( + studentIdNorm: studentIdNorm, + operationId: leaseOperationId, + ); + } + } + } + + Future _syncTokenToAppleTargets(TokenModel token) async { + if (!Platform.isIOS) return; + + final watchInstalled = await WatchSyncHelper.isWatchAppInstalled(); + if (!watchInstalled) { + debugPrint( + '[KretaClient] Skipping Apple token sync because no paired Watch app is installed', + ); + return; + } + + try { + await WatchSyncHelper.saveTokenToiCloud(token); + } catch (e) { + debugPrint('[KretaClient] iCloud token sync skipped: $e'); + } + + try { + await WatchSyncHelper.sendTokenToWatch(); + } catch (e) { + debugPrint('[KretaClient] Watch token sync skipped: $e'); + } } Future recoverToken() async { @@ -341,12 +407,92 @@ class KretaClient { }); cache.token = tokenModel; + await _syncTokenToAppleTargets(cache.token); logger.info("[Recovery] Step 1 SUCCESS: Local refresh succeeded"); return true; } catch (e) { logger.warning("[Recovery] Step 1 FAILED: Local refresh failed: $e"); } + if (!Platform.isIOS || !initDone) { + logger.warning( + "[Recovery] Not iOS or not initialized, cannot try iCloud", + ); + await _setReauthFlag(); + return false; + } + + logger.info("[Recovery] Step 2: Trying iCloud recovery with retries..."); + const retryDelays = [0, 5, 10, 5, 10]; // instant, 5s, 10s, 5s, 10s + bool iCloudHasToken = + false; // Track if iCloud has any token (to avoid useless retries) + + for (var attempt = 0; attempt < retryDelays.length; attempt++) { + final delay = retryDelays[attempt]; + if (delay > 0) { + if (!iCloudHasToken && attempt > 0) { + logger.info("[Recovery] Skipping retries - iCloud has no token"); + break; + } + logger.info( + "[Recovery] Waiting ${delay}s before attempt ${attempt + 1}...", + ); + await Future.delayed(Duration(seconds: delay)); + } + + logger.info( + "[Recovery] iCloud attempt ${attempt + 1}/${retryDelays.length}...", + ); + + final recovered = await WatchSyncHelper.checkAndRecoverFromiCloud( + isar: isarInit, + client: this, + allowExpiredAccessToken: true, + ); + + if (recovered) { + iCloudHasToken = true; + + final recoveredExpiry = cache.token.expiryDate; + if (recoveredExpiry.isAfter( + timeNow().add(const Duration(seconds: 60)), + )) { + logger.info( + "[Recovery] Step 2 SUCCESS on attempt ${attempt + 1}: usable iCloud token applied without immediate refresh", + ); + return true; + } + + logger.info( + "[Recovery] Found iCloud token close to expiry, trying refresh...", + ); + try { + var tokenModel = await _refreshModelWithCrossDeviceLease(cache.token); + + await isarInit.writeTxn(() async { + await isarInit.tokenModels.put(tokenModel); + }); + + cache.token = tokenModel; + await _syncTokenToAppleTargets(cache.token); + logger.info("[Recovery] Step 2 SUCCESS on attempt ${attempt + 1}"); + return true; + } catch (e) { + logger.warning( + "[Recovery] iCloud token refresh failed on attempt ${attempt + 1}: $e", + ); + iCloudHasToken = true; + } + } else { + logger.info( + "[Recovery] No fresh token in iCloud on attempt ${attempt + 1}", + ); + if (attempt == 0) { + iCloudHasToken = false; + } + } + } + logger.warning("[Recovery] All recovery attempts failed"); await _setReauthFlag(); return false; @@ -368,6 +514,13 @@ class KretaClient { logger.warning("[Proactive] Token recovery failed"); await _setReauthFlag(); + if (Platform.isIOS && needsReauth) { + try { + _watchChannel.invokeMethod('notifyReauthRequired'); + } catch (e) { + debugPrint('[KretaClient] Watch reauth notification skipped: $e'); + } + } return false; } diff --git a/firka/lib/api/client/live_activity_backend_client.dart b/firka/lib/api/client/live_activity_backend_client.dart new file mode 100644 index 00000000..7febc9df --- /dev/null +++ b/firka/lib/api/client/live_activity_backend_client.dart @@ -0,0 +1,207 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:logging/logging.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Client for the Live Activity push server (refilc-live-server, `app_type: firka`). +/// +/// The server needs the Live Activity push token before it accepts a schedule, +/// so lessons are kept here and sent once [updatePushToken] delivers the token. +/// `deviceToken` is only used as the stable device id. +class LiveActivityBackendClient { + static final Logger _logger = Logger('LiveActivityBackendClient'); + static const _pushTokenKey = 'live_activity_server_push_token'; + + final Dio _dio; + List _lessons = []; + double _bellDelay = 0; + + LiveActivityBackendClient({Dio? dio}) : _dio = dio ?? Dio() { + _dio.options.baseUrl = + dotenv.env['LIVE_SERVER_URL'] ?? 'https://live.firka.app'; + _dio.options.connectTimeout = const Duration(seconds: 10); + _dio.options.receiveTimeout = const Duration(seconds: 10); + _dio.options.headers = {'Content-Type': 'application/json'}; + } + + /// Keeps the timetable and sends it if a push token is already known. + Future registerDevice({ + required String deviceToken, + required List timetable, + String? language, + double? bellDelay, + int? morningNotificationTime, + bool? morningNotificationEnabled, + bool? liveActivityEnabled, + }) async { + return updateTimetable( + deviceToken: deviceToken, + timetable: timetable, + bellDelay: bellDelay, + ); + } + + Future updateTimetable({ + required String deviceToken, + required List timetable, + double? bellDelay, + }) async { + _lessons = timetable; + if (bellDelay != null) _bellDelay = bellDelay; + + final prefs = await SharedPreferences.getInstance(); + final pushToken = prefs.getString(_pushTokenKey); + // Returning true lets the caller start the activity, which then delivers the push token. + if (pushToken == null) return true; + return _sync(deviceToken, pushToken); + } + + Future unregisterDevice({required String deviceToken}) async { + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_pushTokenKey); + await _dio.post('/unregister', data: {'device_id': deviceToken}); + return true; + } catch (e) { + _logger.severe('Error unregistering device: $e'); + return false; + } + } + + /// The server keeps no change history, so the app always decides by itself. + Future checkTimetableChanges({ + required String deviceToken, + required DateTime lastUpdated, + }) async { + return false; + } + + Future?> getTimetable({required String deviceToken}) async { + return null; + } + + Future updatePushToken({ + required String deviceToken, + required String pushToken, + }) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_pushTokenKey, pushToken); + return _sync(deviceToken, pushToken); + } + + Future updateApnsToken({ + required String deviceToken, + required String apnsPushToken, + }) async { + return true; + } + + Future sendTestNotification({required String deviceToken}) async { + return false; + } + + Future updateLanguage({ + required String deviceToken, + required String language, + }) async { + return true; + } + + Future updateBellDelay({ + required String deviceToken, + required double bellDelay, + }) async { + return updateTimetable( + deviceToken: deviceToken, + timetable: _lessons, + bellDelay: bellDelay, + ); + } + + Future updateMorningNotificationSettings({ + required String deviceToken, + int? morningNotificationTime, + bool? morningNotificationEnabled, + }) async { + return true; + } + + Future toggleLiveActivity({ + required String deviceToken, + required bool liveActivityEnabled, + }) async { + if (liveActivityEnabled) return true; + return unregisterDevice(deviceToken: deviceToken); + } + + Future _sync(String deviceId, String pushToken) async { + try { + final bundleId = (await PackageInfo.fromPlatform()).packageName; + await _dio.post( + '/register', + data: { + 'device_id': deviceId, + 'apns_token': pushToken, + 'bundle_id': bundleId, + 'app_type': 'firka', + 'settings': {'live_activity_color': '#000000'}, + }, + ); + + final now = DateTime.now(); + final today = + '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}'; + final lessons = todayScheduleItems(_lessons, now, _bellDelay); + await _dio.post( + '/schedule', + data: {'device_id': deviceId, 'date': today, 'lessons': lessons}, + ); + _logger.info('Live Activity schedule sent: ${lessons.length} lessons'); + return true; + } catch (e) { + _logger.severe('Error syncing Live Activity schedule: $e'); + return false; + } + } +} + +/// Today's real lessons in the server's `/schedule` format. Events and the +/// `__FOR_NOTIFICATION_ONLY` look-ahead lessons are left out, [bellDelay] is in seconds. +List> todayScheduleItems( + List lessons, + DateTime now, + double bellDelay, +) { + final delay = Duration(milliseconds: (bellDelay * 1000).round()); + final today = lessons.where((l) { + final start = l.start.toLocal(); + final uid = l.uid.toLowerCase(); + return start.year == now.year && + start.month == now.month && + start.day == now.day && + !uid.contains('tanevrendjeesemeny') && + !uid.contains('__for_notification_only'); + }).toList()..sort((a, b) => a.start.compareTo(b.start)); + + return [ + for (final l in today) + { + 'type': '', + 'index': '${l.lessonNumber ?? ''}', + 'subject': l.name, + 'icon': '', + 'room': l.roomName ?? '', + 'description': l.theme ?? '', + 'start': l.start.add(delay).millisecondsSinceEpoch, + 'end': l.end.add(delay).millisecondsSinceEpoch, + 'teacher': l.teacher ?? '', + 'theme': l.theme ?? '', + 'isSubstitution': l.substituteTeacher != null, + 'isCancelled': l.state.name.toLowerCase().contains('elmarad'), + 'substituteTeacher': l.substituteTeacher ?? '', + 'lessonNumber': l.lessonNumber, + }, + ]; +} diff --git a/firka/lib/api/client/notification_backend_client.dart b/firka/lib/api/client/notification_backend_client.dart index 46ccc69d..75c79d27 100644 --- a/firka/lib/api/client/notification_backend_client.dart +++ b/firka/lib/api/client/notification_backend_client.dart @@ -2,7 +2,8 @@ import 'package:dio/dio.dart'; import 'package:logging/logging.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -/// Client for registering FCM push tokens with firka's backend. +/// Client for registering FCM push tokens with firka's backend, mirroring +/// LiveActivityBackendClient's conventions (same backend, same auth scheme). /// Requires the backend to expose the `/notifications/*` routes below. class NotificationBackendClient { static final Logger _logger = Logger('NotificationBackendClient'); diff --git a/firka/lib/api/login_finish.dart b/firka/lib/api/login_finish.dart index e758cd57..b3e0d2b9 100644 --- a/firka/lib/api/login_finish.dart +++ b/firka/lib/api/login_finish.dart @@ -1,6 +1,9 @@ +import "dart:io"; + import "package:firka/app/app_state.dart"; import "package:firka/app/initialization.dart"; import "package:firka/services/notification_delivery_service.dart"; +import "package:firka/services/watch_sync_helper.dart"; import "package:firka_common/data/models/token_model.dart"; import "package:kreta_api/kreta_api.dart"; @@ -22,4 +25,17 @@ Future completeLogin( client: data.client!, ); } + + if (Platform.isIOS) { + final watchInstalled = await WatchSyncHelper.isWatchAppInstalled(); + if (watchInstalled) { + try { + await WatchSyncHelper.saveTokenToiCloud(tokenModel); + } catch (_) {} + + try { + await WatchSyncHelper.sendTokenToWatch(); + } catch (_) {} + } + } } diff --git a/firka/lib/app/initialization.dart b/firka/lib/app/initialization.dart index 2f382dac..f4c59fc3 100644 --- a/firka/lib/app/initialization.dart +++ b/firka/lib/app/initialization.dart @@ -13,10 +13,12 @@ import 'package:firka/services/notification_delivery_service.dart'; import 'package:firka/services/progress_notification_service.dart'; import 'package:firka/data/widget.dart'; import 'package:firka/core/extensions.dart'; +import 'package:firka/services/live_activity_service.dart'; import 'package:firka/core/settings/settings_effects.dart'; import 'package:firka/core/settings/settings_repository.dart'; import 'package:firka/core/settings/settings_schema.dart'; import 'package:firka/core/settings/title_font.dart'; +import 'package:firka/services/watch_sync_helper.dart'; import 'package:firka/l10n/app_localizations_de.dart'; import 'package:firka/l10n/app_localizations_en.dart'; import 'package:firka/l10n/app_localizations_hu.dart'; @@ -33,30 +35,52 @@ import 'package:path_provider/path_provider.dart'; Future initLang(AppInitialization data) async { + String? languageCode; + switch (Settings.language.value) { case AppLanguage.hu: data.l10n = AppLocalizationsHu(); + languageCode = 'hu'; break; case AppLanguage.en: data.l10n = AppLocalizationsEn(); + languageCode = 'en'; break; case AppLanguage.de: data.l10n = AppLocalizationsDe(); + languageCode = 'de'; break; case AppLanguage.auto: switch (ui.PlatformDispatcher.instance.locale.languageCode) { case 'hu': data.l10n = AppLocalizationsHu(); + languageCode = 'hu'; break; case 'en': data.l10n = AppLocalizationsEn(); + languageCode = 'en'; break; case 'de': data.l10n = AppLocalizationsDe(); + languageCode = 'de'; break; } break; } + + if (languageCode != null && Platform.isIOS) { + try { + await LiveActivityService.updateLanguagePreference(languageCode); + } catch (e) { + logger.warning('Failed to update language preference on backend: $e'); + } + + try { + await WatchSyncHelper.sendLanguageToWatch(); + } catch (e) { + logger.warning('Failed to send language to Watch: $e'); + } + } } /// Builds a full style for an explicit brightness, applying all custom color @@ -362,6 +386,23 @@ Future _initData(AppInitialization init) async { }()); }; + var didRunFreshInstallCleanup = false; + if (Platform.isIOS) { + try { + didRunFreshInstallCleanup = + await WatchSyncHelper.runFreshInstallCleanupIfNeeded(isar: init.isar); + if (didRunFreshInstallCleanup) { + logger.info( + '[Init] Fresh-install cleanup completed; skipping startup iCloud recovery on this launch', + ); + } else { + await WatchSyncHelper.checkAndRecoverFromiCloud(isar: init.isar); + } + } catch (e) { + logger.warning('[Init] iCloud bootstrap/recovery failed: $e'); + } + } + final token = init.settings.getSelectedToken(); if (token == null) { logger.warning("[Init] No token available!"); @@ -421,6 +462,27 @@ Future _initData(AppInitialization init) async { init.homeRefreshCubit.requestRefresh(); }()); + if (Platform.isIOS) { + final expiryDate = token.expiryDate; + if (expiryDate.isAfter(DateTime.now())) { + init.toastCubit.clear(); + } + + unawaited(() async { + try { + await WatchSyncHelper.saveTokenToiCloud(token); + } catch (e) { + logger.warning('[Init] Failed to sync active token to iCloud: $e'); + } + + try { + await WatchSyncHelper.sendTokenModelToWatch(token); + } catch (e) { + logger.warning('[Init] Failed to sync active token to Watch: $e'); + } + }()); + } + final dataDir = await getApplicationDocumentsDirectory(); var pfpFile = File(p.join(dataDir.path, "profile.webp")); @@ -478,6 +540,18 @@ Future initializeApp() async { await Settings.loadAll(); registerSettingsEffects(initData.settings, initData); + if (Platform.isIOS) { + try { + await LiveActivityService.initialize().timeout( + const Duration(seconds: 8), + ); + } on TimeoutException catch (e, st) { + logger.warning('LiveActivity init timed out: $e', e, st); + } catch (e, st) { + logger.severe('Failed to initialize LiveActivity: $e', e, st); + } + } + try { await NotificationDeliveryService.initialize().timeout( const Duration(seconds: 8), diff --git a/firka/lib/app/initialization_screen.dart b/firka/lib/app/initialization_screen.dart index 7fd8b1ec..6fb81cc7 100644 --- a/firka/lib/app/initialization_screen.dart +++ b/firka/lib/app/initialization_screen.dart @@ -15,7 +15,7 @@ import 'package:firka/core/bloc/settings_cubit.dart'; import 'package:firka/core/bloc/theme_cubit.dart'; import 'package:firka/core/firka_bundle.dart'; import 'package:firka/routing/app_router.dart'; -import 'package:firka/services/wear_sync_helper.dart'; +import 'package:firka/services/watch_sync_helper.dart'; import 'package:firka/ui/theme/style.dart'; import 'package:firka/ui/phone/pages/extras/main_wear_pair.dart'; import 'package:firka/l10n/app_localizations.dart'; @@ -84,9 +84,21 @@ class _InitializationScreenState extends State { FlutterNativeSplash.remove(); + WatchSyncHelper.initialize(); if (Platform.isAndroid) { WatchSyncHelper.setWearSyncMethodCallHandler(); } + if (Platform.isIOS) { + unawaited(() async { + try { + await WatchSyncHelper.sendLanguageToWatch(); + } catch (e) { + logger.warning( + '[Init] Failed to publish language to Watch after sync init: $e', + ); + } + }()); + } if (!initData.hasWatchListener) { initData.hasWatchListener = true; @@ -103,7 +115,11 @@ class _InitializationScreenState extends State { final ctx = navigatorKey.currentContext; if (ctx != null && ctx.mounted) { logger.info('Watch init_data: ${jsonEncode(msg)}'); - showWearBottomSheet(ctx, initData, msg['model']); + showWearBottomSheet( + ctx, + initData, + Platform.isAndroid ? msg['model'] : 'Apple Watch', + ); } }); break; diff --git a/firka/lib/core/settings.dart b/firka/lib/core/settings.dart index f0e31900..5401081b 100644 --- a/firka/lib/core/settings.dart +++ b/firka/lib/core/settings.dart @@ -4,6 +4,7 @@ import "package:firka/core/settings/settings_repository.dart"; import "package:firka/core/settings/settings_schema.dart"; import "package:firka/core/settings/settings_ui.dart"; import "package:firka/l10n/app_localizations.dart"; +import "package:firka/services/live_activity_service.dart"; import "package:firka/ui/shared/firka_icon.dart"; import "package:flutter/foundation.dart"; import "package:majesticons_flutter/majesticons_flutter.dart"; @@ -16,6 +17,14 @@ bool isDeveloper() => isDebug() || Settings.developerOptsEnabled.value; bool isAndroid() => Platform.isAndroid; +bool isIOS() => Platform.isIOS; + +bool isLiveActivityEnabled() => + Platform.isIOS && Settings.liveActivityEnabled.value; + +bool isMorningNotificationEnabled() => + Platform.isIOS && Settings.morningNotificationEnabled.value; + bool isWearOsSupportEnabled() => Platform.isAndroid && Settings.wearOsSupport.value; @@ -23,6 +32,8 @@ bool isPushNotificationsEnabled() => Settings.notifyAll.value; bool isDebug() => kDebugMode; +bool isDebugIOS() => kDebugMode && Platform.isIOS; + Map appIconLabels(AppLocalizations l10n) => { "ace": l10n.ic_ace, "ace_f": l10n.ic_ace_f, @@ -255,6 +266,13 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { SettingsRegistry.leftHandedMode, never, ), + SettingsUiBoolean( + null, + null, + l10n.s_ag_privacy_ever_declined, + SettingsRegistry.liveActivityPrivacyEverDeclined, + never, + ), SettingsUiHeaderSmall(l10n.s_ag_language_header, always), SettingsUiEnum(SettingsRegistry.language, [ l10n.s_ag_language_auto, @@ -370,6 +388,45 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { ], isAndroid, ), + SettingsUiSubGroup( + FirkaIconType.majesticons, + Majesticon.bellSolid, + l10n.s_n, + [ + SettingsUiBackHeader(l10n.s_settings, always), + SettingsUiHeader(l10n.s_n, always), + SettingsUiPadding(23, always), + SettingsUiBoolean( + FirkaIconType.majesticons, + Majesticon.bellSolid, + l10n.s_n_morning, + SettingsRegistry.morningNotificationEnabled, + always, + ), + SettingsUiDouble( + FirkaIconType.majesticons, + Majesticon.clockSolid, + l10n.s_n_morning_time, + SettingsRegistry.morningNotificationTime, + isMorningNotificationEnabled, + ), + SettingsUiBoolean( + FirkaIconType.majesticons, + Majesticon.clockSolid, + l10n.s_n_live_activity, + SettingsRegistry.liveActivityEnabled, + always, + ), + SettingsUiButton( + FirkaIconType.majesticons, + Majesticon.bellSolid, + l10n.s_n_test, + isDebugIOS, + () async => LiveActivityService.sendTestNotification(), + ), + ], + isIOS, + ), SettingsUiSubGroup( FirkaIconType.majesticons, Majesticon.lightningBoltSolid, diff --git a/firka/lib/core/settings/settings_effects.dart b/firka/lib/core/settings/settings_effects.dart index 6fc9b70f..aa379cae 100644 --- a/firka/lib/core/settings/settings_effects.dart +++ b/firka/lib/core/settings/settings_effects.dart @@ -7,9 +7,10 @@ import "package:firka/app/initialization.dart"; import "package:firka/services/fcm_service.dart"; import "package:firka/services/notification_delivery_service.dart"; import "package:firka/services/progress_notification_service.dart"; -import "package:firka/services/wear_sync_helper.dart"; +import "package:firka/services/watch_sync_helper.dart"; import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart"; import "package:firka_common/ui/theme/core_theme.dart"; +import "package:firka/services/live_activity_service.dart"; import "package:firka/data/widget.dart"; import "settings_repository.dart"; @@ -135,6 +136,15 @@ void registerSettingsEffects( } }); + repo.onChange(SettingsRegistry.morningNotificationEnabled, (enabled) async { + LiveActivityService.onMorningNotificationEnabledChanged(enabled); + }); + + repo.onChange(SettingsRegistry.liveActivityEnabled, (enabled) async { + await LiveActivityService.handleEnabledChange(enabled, isManual: true); + await LiveActivityService.syncGlobalSettingWithCurrentUser(); + }); + repo.onChange(SettingsRegistry.notifyAll, (_) async { await NotificationDeliveryService.syncDeliveryBackend(); await ProgressNotificationService.sync(); @@ -163,4 +173,16 @@ void registerSettingsEffects( await FcmService.updatePreferences(); }); } + + // These two mirror LiveActivity widgets on iOS only, matching the original + // postUpdate wiring that was only attached inside an `if (Platform.isIOS)` block. + if (Platform.isIOS) { + repo.onChange(SettingsRegistry.bellDelay, (value) async { + LiveActivityService.onBellDelayChanged(value); + }); + + repo.onChange(SettingsRegistry.morningNotificationTime, (value) async { + LiveActivityService.onMorningNotificationTimeChanged(value); + }); + } } diff --git a/firka/lib/core/settings/settings_schema.dart b/firka/lib/core/settings/settings_schema.dart index 3b2ca9c8..02b89159 100644 --- a/firka/lib/core/settings/settings_schema.dart +++ b/firka/lib/core/settings/settings_schema.dart @@ -91,6 +91,25 @@ abstract class SettingsSchema { @BoolSetting(id: 1018, defaultValue: true) bool get ttToastSubstitution; + @BoolSetting(id: 1019, defaultValue: false) + bool get liveActivityEnabled; + + @BoolSetting(id: 1020, defaultValue: false) + bool get liveActivityPrivacyEverDeclined; + + @BoolSetting(id: 1021, defaultValue: true) + bool get morningNotificationEnabled; + + @DoubleSetting( + id: 1022, + defaultValue: 120, + min: 30, + max: 240, + precision: 0, + step: 15, + ) + double get morningNotificationTime; + @BoolSetting(id: 1023, defaultValue: true) bool get ttToastABTimetable; diff --git a/firka/lib/core/settings/settings_schema.gen.dart b/firka/lib/core/settings/settings_schema.gen.dart index ce3c949c..aa3c66e9 100644 --- a/firka/lib/core/settings/settings_schema.gen.dart +++ b/firka/lib/core/settings/settings_schema.gen.dart @@ -21,6 +21,10 @@ class SettingsRegistry { static const developerOptsEnabled = BoolSetting(id: 1016, defaultValue: false); static const themeBrightness = EnumSetting(id: 1017, defaultValue: ThemeBrightness.auto, values: ThemeBrightness.values); static const ttToastSubstitution = BoolSetting(id: 1018, defaultValue: true); + static const liveActivityEnabled = BoolSetting(id: 1019, defaultValue: false); + static const liveActivityPrivacyEverDeclined = BoolSetting(id: 1020, defaultValue: false); + static const morningNotificationEnabled = BoolSetting(id: 1021, defaultValue: true); + static const morningNotificationTime = DoubleSetting(id: 1022, defaultValue: 120, min: 30, max: 240, precision: 0, step: 15); static const ttToastABTimetable = BoolSetting(id: 1023, defaultValue: true); static const wearOsSupport = BoolSetting(id: 1024, defaultValue: false); static const titleFont = EnumSetting(id: 1026, defaultValue: TitleFont.montserrat, values: TitleFont.values); @@ -88,7 +92,7 @@ class SettingsRegistry { static const customBackgroundGradientDark = StringSetting(id: 1088, defaultValue: "[\"0xFF0D1202\",\"0xFF1A2405\"]"); static const all = [ - bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod, lessonCacheKeyMigrationDone, progressNotificationEnabled, customGradeColor5, customGradeColor4, customGradeColor3, customGradeColor2, customGradeColor1, customAccentColorLight, customAccentColorDark, customBackgroundColorLight, customBackgroundColorDark, customCardColorLight, customCardColorDark, customButtonColorLight, customButtonColorDark, customSecondaryColorLight, customSecondaryColorDark, customTextColorLight, customTextColorDark, customTextSecondaryColorLight, customTextSecondaryColorDark, customTextTertiaryColorLight, customTextTertiaryColorDark, customShadowColorLight, customShadowColorDark, customSuccessColorLight, customSuccessColorDark, customWarningAccentColorLight, customWarningAccentColorDark, customWarningTextColorLight, customWarningTextColorDark, customWarningCardColorLight, customWarningCardColorDark, customErrorAccentColorLight, customErrorAccentColorDark, customErrorTextColorLight, customErrorTextColorDark, customErrorCardColorLight, customErrorCardColorDark, customBackgroundGradientLight, customBackgroundGradientDark, + bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, liveActivityEnabled, liveActivityPrivacyEverDeclined, morningNotificationEnabled, morningNotificationTime, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod, lessonCacheKeyMigrationDone, progressNotificationEnabled, customGradeColor5, customGradeColor4, customGradeColor3, customGradeColor2, customGradeColor1, customAccentColorLight, customAccentColorDark, customBackgroundColorLight, customBackgroundColorDark, customCardColorLight, customCardColorDark, customButtonColorLight, customButtonColorDark, customSecondaryColorLight, customSecondaryColorDark, customTextColorLight, customTextColorDark, customTextSecondaryColorLight, customTextSecondaryColorDark, customTextTertiaryColorLight, customTextTertiaryColorDark, customShadowColorLight, customShadowColorDark, customSuccessColorLight, customSuccessColorDark, customWarningAccentColorLight, customWarningAccentColorDark, customWarningTextColorLight, customWarningTextColorDark, customWarningCardColorLight, customWarningCardColorDark, customErrorAccentColorLight, customErrorAccentColorDark, customErrorTextColorLight, customErrorTextColorDark, customErrorCardColorLight, customErrorCardColorDark, customBackgroundGradientLight, customBackgroundGradientDark, ]; } @@ -111,6 +115,10 @@ extension SettingsAccessors on SettingsRepository { SilentlySettable get developerOptsEnabled => SilentlySettable(this, SettingsRegistry.developerOptsEnabled); SilentlySettable get themeBrightness => SilentlySettable(this, SettingsRegistry.themeBrightness); SilentlySettable get ttToastSubstitution => SilentlySettable(this, SettingsRegistry.ttToastSubstitution); + SilentlySettable get liveActivityEnabled => SilentlySettable(this, SettingsRegistry.liveActivityEnabled); + SilentlySettable get liveActivityPrivacyEverDeclined => SilentlySettable(this, SettingsRegistry.liveActivityPrivacyEverDeclined); + SilentlySettable get morningNotificationEnabled => SilentlySettable(this, SettingsRegistry.morningNotificationEnabled); + SilentlySettable get morningNotificationTime => SilentlySettable(this, SettingsRegistry.morningNotificationTime); SilentlySettable get ttToastABTimetable => SilentlySettable(this, SettingsRegistry.ttToastABTimetable); SilentlySettable get wearOsSupport => SilentlySettable(this, SettingsRegistry.wearOsSupport); SilentlySettable get titleFont => SilentlySettable(this, SettingsRegistry.titleFont); diff --git a/firka/lib/data/ios_widget_helper.dart b/firka/lib/data/ios_widget_helper.dart new file mode 100644 index 00000000..d820db27 --- /dev/null +++ b/firka/lib/data/ios_widget_helper.dart @@ -0,0 +1,222 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:kreta_api/kreta_api.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +class IOSWidgetHelper { + static const _channel = MethodChannel('app.firka/home_widgets'); + static const _watchChannel = MethodChannel('app.firka/watch_sync'); + + static Future _getAppGroupDirectory() async { + if (!Platform.isIOS) return null; + + try { + final result = await _channel.invokeMethod( + 'getAppGroupDirectory', + ); + if (result != null) { + return Directory(result); + } + } catch (e) { + debugPrint('Error getting app group directory: $e'); + } + return null; + } + + static Future updateWidgetData({ + required String locale, + required String theme, + required List todayLessons, + required List tomorrowLessons, + List nextSchoolDayLessons = const [], + DateTime? nextSchoolDayDate, + required List grades, + required Map subjectAverages, + required double? overallAverage, + WidgetBreakInfo? currentBreak, + }) async { + if (!Platform.isIOS) return; + + debugPrint('[IOSWidget] Starting updateWidgetData...'); + debugPrint( + '[IOSWidget] todayLessons: ${todayLessons.length}, tomorrowLessons: ${tomorrowLessons.length}', + ); + debugPrint( + '[IOSWidget] grades: ${grades.length}, subjectAverages: ${subjectAverages.length}', + ); + + final dir = await _getAppGroupDirectory(); + if (dir == null) { + debugPrint('[IOSWidget] ERROR: App Group directory is null!'); + return; + } + debugPrint('[IOSWidget] App Group directory: ${dir.path}'); + + final data = { + 'lastUpdated': DateTime.now().toIso8601String(), + 'locale': locale, + 'theme': theme, + 'timetable': { + 'today': todayLessons.map((l) => _lessonToJson(l)).toList(), + 'tomorrow': tomorrowLessons.map((l) => _lessonToJson(l)).toList(), + 'nextSchoolDay': nextSchoolDayLessons + .map((l) => _lessonToJson(l)) + .toList(), + 'nextSchoolDayDate': nextSchoolDayDate?.toIso8601String(), + 'currentBreak': currentBreak != null + ? { + 'name': currentBreak.name, + 'nameKey': currentBreak.nameKey, + 'endDate': currentBreak.endDate.toIso8601String(), + } + : null, + }, + 'grades': grades.take(20).map((g) => _gradeToJson(g)).toList(), + 'averages': { + 'overall': overallAverage, + 'subjects': subjectAverages.entries + .map( + (e) => { + 'uid': e.key, + 'name': _getSubjectNameFromGrades(e.key, grades), + 'average': e.value, + 'gradeCount': _getGradeCount(e.key, grades), + }, + ) + .toList(), + }, + }; + + final jsonString = jsonEncode(data); + debugPrint('[IOSWidget] JSON data length: ${jsonString.length} bytes'); + + final file = File('${dir.path}/widget_data.json'); + await file.writeAsString(jsonString); + debugPrint('[IOSWidget] File written to: ${file.path}'); + + final exists = await file.exists(); + debugPrint('[IOSWidget] File exists after write: $exists'); + + await reloadAllWidgets(); + debugPrint('[IOSWidget] Widget reload triggered'); + + // Send data to Watch + try { + await _watchChannel.invokeMethod('sendWidgetDataToWatch', jsonString); + debugPrint('[IOSWidget] Watch data sent'); + } catch (e) { + debugPrint('[IOSWidget] Watch sync skipped: $e'); + } + } + + /// Format DateTime with explicit timezone offset for proper Swift parsing + static String _formatDateTimeWithOffset(DateTime dt) { + final local = dt.toLocal(); + final offset = local.timeZoneOffset; + final sign = offset.isNegative ? '-' : '+'; + final hours = offset.inHours.abs().toString().padLeft(2, '0'); + final minutes = (offset.inMinutes.abs() % 60).toString().padLeft(2, '0'); + return '${local.toIso8601String()}$sign$hours:$minutes'; + } + + static Map _lessonToJson(Lesson lesson) { + final subject = lesson.subject; + return { + 'uid': lesson.uid, + 'date': lesson.date, + 'start': _formatDateTimeWithOffset(lesson.start), + 'end': _formatDateTimeWithOffset(lesson.end), + 'name': lesson.name, + 'lessonNumber': lesson.lessonNumber, + 'teacher': lesson.teacher, + 'subject': subject != null + ? { + 'uid': subject.uid, + 'name': subject.name, + 'category': { + 'uid': subject.category.uid, + 'name': subject.category.name, + 'description': subject.category.description, + }, + 'sortIndex': subject.sortIndex, + 'teacherName': null, + } + : { + 'uid': '', + 'name': lesson.name, + 'category': null, + 'sortIndex': 0, + 'teacherName': null, + }, + 'theme': lesson.theme, + 'roomName': lesson.roomName, + 'isCancelled': lesson.state.name.toLowerCase().contains('elmarad'), + 'isSubstitution': lesson.substituteTeacher != null, + }; + } + + static Map _gradeToJson(Grade grade) { + return { + 'uid': grade.uid, + 'recordDate': _formatDateTimeWithOffset(grade.creationDate), + 'subject': { + 'uid': grade.subject.uid, + 'name': grade.subject.name, + 'category': { + 'uid': grade.subject.category.uid, + 'name': grade.subject.category.name, + 'description': grade.subject.category.description, + }, + 'sortIndex': grade.subject.sortIndex, + // Use the grade's teacher field, not subject.teacherName (which is usually null for grades) + 'teacherName': grade.teacher, + }, + 'topic': grade.topic, + 'type': { + 'uid': grade.type.uid, + 'name': grade.type.name, + 'description': grade.type.description, + }, + 'numericValue': grade.numericValue, + 'strValue': grade.strValue, + 'weightPercentage': grade.weightPercentage, + }; + } + + static String _getSubjectNameFromGrades(String uid, List grades) { + try { + final grade = grades.firstWhere((g) => g.subject.uid == uid); + return grade.subject.name; + } catch (e) { + return uid; + } + } + + static int _getGradeCount(String uid, List grades) { + return grades.where((g) => g.subject.uid == uid).length; + } + + static Future reloadAllWidgets() async { + if (!Platform.isIOS) return; + + try { + await _channel.invokeMethod('reloadAllWidgets'); + } catch (e) { + debugPrint('Error reloading widgets: $e'); + } + } +} + +class WidgetBreakInfo { + final String name; + final String nameKey; + final DateTime endDate; + + WidgetBreakInfo({ + required this.name, + required this.nameKey, + required this.endDate, + }); +} diff --git a/firka/lib/data/widget.dart b/firka/lib/data/widget.dart index 1c11a9be..10c6103f 100644 --- a/firka/lib/data/widget.dart +++ b/firka/lib/data/widget.dart @@ -1,3 +1,4 @@ +import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:ui' as ui; @@ -6,6 +7,7 @@ import 'package:firka/core/settings/settings_repository.dart'; import 'package:firka/core/settings/settings_schema.dart'; import 'package:firka/api/client/kreta_client.dart'; import 'package:firka_common/data/database.dart'; +import 'package:firka/data/ios_widget_helper.dart'; import 'package:firka_common/data/models/lesson_cache_model.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -13,6 +15,7 @@ import 'package:home_widget/home_widget.dart'; import 'package:isar_community/isar.dart'; import 'package:kreta_api/kreta_api.dart'; import 'package:firka/core/debug_helper.dart'; +import 'package:flutter/scheduler.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; @@ -252,4 +255,144 @@ class WidgetCacheHelper { displayDate: displayDate, ); } + + /// Comprehensive iOS widget refresh that collects all necessary data + /// Call this on: app open, user switch, data refresh + static Future refreshIOSWidgets( + KretaClient client, + SettingsRepository settings, + ) async { + if (!Platform.isIOS) return; + + try { + final language = settings.get(SettingsRegistry.language); + String locale; + switch (language) { + case AppLanguage.hu: + locale = 'hu'; + break; + case AppLanguage.en: + locale = 'en'; + break; + case AppLanguage.de: + locale = 'de'; + break; + case AppLanguage.auto: + locale = 'hu'; + } + + final themeBrightness = settings.get(SettingsRegistry.themeBrightness); + String theme; + switch (themeBrightness) { + case ThemeBrightness.light: + theme = 'light'; + break; + case ThemeBrightness.dark: + theme = 'dark'; + break; + case ThemeBrightness.auto: + theme = + SchedulerBinding.instance.platformDispatcher.platformBrightness == + Brightness.light + ? 'light' + : 'dark'; + } + + final now = timeNow(); + final todayMidnight = DateTime(now.year, now.month, now.day); + final tomorrowMidnight = todayMidnight.add(Duration(days: 1)); + + await client.getLessons( + todayMidnight, + todayMidnight.add(Duration(hours: 23, minutes: 59)), + ); + await client.getLessons( + tomorrowMidnight, + tomorrowMidnight.add(Duration(hours: 23, minutes: 59)), + ); + + final todayLessons = []; + final tomorrowLessons = []; + + debugPrint( + 'iOS widget refresh: ${todayLessons.length} today lessons, ${tomorrowLessons.length} tomorrow lessons', + ); + + List nextSchoolDayLessons = []; + DateTime? nextSchoolDayDate; + if (tomorrowLessons.isEmpty) { + for (int i = 2; i <= 7; i++) { + final dayMidnight = todayMidnight.add(Duration(days: i)); + await client.getLessons( + dayMidnight, + dayMidnight.add(Duration(hours: 23, minutes: 59)), + ); + final dayLessons = []; + if (dayLessons.isNotEmpty) { + nextSchoolDayLessons = dayLessons; + nextSchoolDayDate = dayMidnight; + debugPrint( + 'iOS widget: Next school day found $i days ahead with ${dayLessons.length} lessons', + ); + break; + } + } + } + + final gradesResponse = await client.getGrades(); + final grades = []; + + debugPrint( + 'iOS widget refresh: ${grades.length} grades fetched (cached: $gradesResponse)', + ); + + final Map subjectAverages = {}; + final HashSet subjects = HashSet( + hashCode: (s) => s.uid.hashCode, + equals: (s, s2) => s.uid == s2.uid, + ); + + subjects.addAll(grades.map((g) => g.subject)); + + WidgetBreakInfo? currentBreak; + + await IOSWidgetHelper.updateWidgetData( + locale: locale, + theme: theme, + todayLessons: [], + tomorrowLessons: [], + nextSchoolDayLessons: nextSchoolDayLessons, + nextSchoolDayDate: nextSchoolDayDate, + grades: [], + subjectAverages: subjectAverages, + overallAverage: 0.0, + currentBreak: currentBreak, + ); + + debugPrint('iOS widgets refreshed successfully'); + } catch (e) { + debugPrint('Error refreshing iOS widgets: $e'); + } + } + + /// Clear iOS widget data (call on logout) + static Future clearIOSWidgets() async { + if (!Platform.isIOS) return; + + try { + await IOSWidgetHelper.updateWidgetData( + locale: 'hu', + theme: 'light', + todayLessons: [], + tomorrowLessons: [], + grades: [], + subjectAverages: {}, + overallAverage: null, + currentBreak: null, + ); + debugPrint('iOS widgets cleared'); + } catch (e) { + debugPrint('Error clearing iOS widgets: $e'); + } + } } diff --git a/firka/lib/services/fcm_headless_bootstrap.dart b/firka/lib/services/fcm_headless_bootstrap.dart index 3b088fac..6f7b2de4 100644 --- a/firka/lib/services/fcm_headless_bootstrap.dart +++ b/firka/lib/services/fcm_headless_bootstrap.dart @@ -14,11 +14,11 @@ import 'package:firka_common/data/database.dart'; /// the global `initData` (for `userAgent`/`toastCubit`) unconditionally, so /// something has to populate it before a background wakeup can fetch data. /// -/// Deliberately skips everything UI/theming/watch-sync related: those -/// either don't apply headlessly or actively assume a running app (native -/// platform channels registered on the main FlutterEngine, etc). Idempotent -/// per isolate — a warm background isolate handling multiple wakeups only -/// bootstraps once. +/// Deliberately skips everything UI/theming/watch-sync/live-activity +/// related: those either don't apply headlessly or actively assume a +/// running app (native platform channels registered on the main +/// FlutterEngine, iCloud sync, etc). Idempotent per isolate — a warm +/// background isolate handling multiple wakeups only bootstraps once. Future bootstrapHeadless() async { if (initDone) return; diff --git a/firka/lib/services/fcm_service.dart b/firka/lib/services/fcm_service.dart index 8e12413c..4a32284b 100644 --- a/firka/lib/services/fcm_service.dart +++ b/firka/lib/services/fcm_service.dart @@ -43,9 +43,11 @@ Future firebaseMessagingBackgroundHandler(RemoteMessage message) async { } /// Coordinates FCM push notification registration with firka's backend. -/// Android-only: `flutterfire configure` has only been run for Android, so -/// `DefaultFirebaseOptions.currentPlatform` throws on other platforms. The -/// `Platform.isAndroid` guard in [initialize] reflects that. +/// Android-only for now: `flutterfire configure` has only been run for +/// Android, so `DefaultFirebaseOptions.currentPlatform` throws on iOS. Once +/// iOS is configured (re-run `flutterfire configure` with both platforms +/// selected), drop the `Platform.isAndroid` guard in [initialize] to make +/// this cross-platform like the rest of the service already assumes. /// Push is enabled by default; the master switch is SettingsRegistry.notifyAll, /// toggleable from the notifications settings page. class FcmService { @@ -157,6 +159,16 @@ class FcmService { if (_pendingPermissionRequest != null) { return await _pendingPermissionRequest!; } + if (Platform.isIOS) { + final settings = await FirebaseMessaging.instance.requestPermission( + alert: true, + badge: true, + sound: true, + ); + return settings.authorizationStatus == AuthorizationStatus.authorized || + settings.authorizationStatus == AuthorizationStatus.provisional; + } + final status = await Permission.notification.status; if (status.isGranted) return true; diff --git a/firka/lib/services/live_activity_manager.dart b/firka/lib/services/live_activity_manager.dart new file mode 100644 index 00000000..59f45442 --- /dev/null +++ b/firka/lib/services/live_activity_manager.dart @@ -0,0 +1,252 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/services.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:logging/logging.dart'; + +class LiveActivityManager { + static const MethodChannel _channel = MethodChannel( + 'firka.app/live_activity', + ); + static final Logger _logger = Logger('LiveActivityManager'); + + static String? _activityId; + static bool _isActivityActive = false; + static Function(String activityId, String pushToken)? _onPushTokenReceived; + + static Future initialize() async { + if (!Platform.isIOS) return; + try { + _channel.setMethodCallHandler(_handleMethodCall); + await _channel.invokeMethod('initialize'); + await _syncActivityState(); + _logger.info('LiveActivity initialized'); + } catch (e) { + _logger.warning('Failed to initialize LiveActivity: $e'); + } + } + + static Future _syncActivityState() async { + if (!Platform.isIOS) return; + try { + final activeActivities = await getActiveActivities(); + if (activeActivities.isNotEmpty) { + _activityId = activeActivities.first; + _isActivityActive = true; + _logger.info( + 'Synced activity state: Found existing activity $_activityId', + ); + } else { + _activityId = null; + _isActivityActive = false; + _logger.info('Synced activity state: No active activities found'); + } + } catch (e) { + _logger.warning('Failed to sync activity state: $e'); + } + } + + static Future _handleMethodCall(MethodCall call) async { + switch (call.method) { + case 'onPushTokenReceived': + final args = call.arguments as Map; + final activityId = args['activityId'] as String; + final pushToken = args['pushToken'] as String; + _logger.info( + 'Received LiveActivity push token: ${pushToken.substring(0, 10)}...', + ); + _onPushTokenReceived?.call(activityId, pushToken); + break; + default: + _logger.warning('Unknown method call from Swift: ${call.method}'); + } + } + + static void setOnPushTokenReceived( + Function(String activityId, String pushToken) callback, + ) { + _onPushTokenReceived = callback; + } + + static Future getDeviceToken() async { + if (!Platform.isIOS) return null; + try { + return await _channel.invokeMethod('getDeviceToken'); + } catch (e) { + _logger.warning('Failed to get device token: $e'); + return null; + } + } + + static Future registerForPushNotifications() async { + if (!Platform.isIOS) return null; + try { + return await _channel.invokeMethod('registerForPushNotifications'); + } catch (e) { + _logger.warning('Failed to register for push notifications: $e'); + return null; + } + } + + static Future startActivity({ + required String studentName, + required String schoolName, + required Lesson currentLesson, + Lesson? nextLesson, + bool isBreak = false, + String? mode, + }) async { + if (!Platform.isIOS) return false; + try { + await _syncActivityState(); + if (_isActivityActive) { + _logger.info( + 'Activity already exists, ending it to create new one with fresh token', + ); + await endAllActivities(); + await Future.delayed(const Duration(milliseconds: 500)); + } + + final contentState = _createContentState( + currentLesson: currentLesson, + nextLesson: nextLesson, + isBreak: isBreak, + mode: mode, + ); + final attributes = {'studentName': studentName, 'schoolName': schoolName}; + + final result = await _channel.invokeMethod('startActivity', { + 'attributes': jsonEncode(attributes), + 'contentState': jsonEncode(contentState), + }); + + if (result is String) { + _activityId = result; + _isActivityActive = true; + _logger.info('LiveActivity started with ID: $_activityId'); + return true; + } + return false; + } catch (e) { + _logger.warning('Failed to start LiveActivity: $e'); + return false; + } + } + + static Future updateActivity({ + required Lesson currentLesson, + Lesson? nextLesson, + bool isBreak = false, + String? mode, + }) async { + if (!Platform.isIOS) return false; + await _syncActivityState(); + if (!_isActivityActive || _activityId == null) { + _logger.warning('Cannot update: No active Live Activity found.'); + return false; + } + + try { + final contentState = _createContentState( + currentLesson: currentLesson, + nextLesson: nextLesson, + isBreak: isBreak, + mode: mode, + ); + await _channel.invokeMethod('updateActivity', { + 'activityId': _activityId, + 'contentState': jsonEncode(contentState), + }); + _logger.info('LiveActivity updated.'); + return true; + } catch (e) { + _logger.warning('Failed to update LiveActivity: $e'); + return false; + } + } + + static Future endActivity() async { + if (!Platform.isIOS) return; + await _syncActivityState(); + if (!_isActivityActive || _activityId == null) return; + + try { + await _channel.invokeMethod('endActivity', {'activityId': _activityId}); + _activityId = null; + _isActivityActive = false; + _logger.info('LiveActivity ended.'); + } catch (e) { + _logger.warning('Failed to end LiveActivity: $e'); + } + } + + static Future> getActiveActivities() async { + if (!Platform.isIOS) return []; + try { + final result = await _channel.invokeMethod('getActiveActivities'); + return (result as List?)?.cast() ?? []; + } catch (e) { + _logger.warning('Failed to get active activities: $e'); + return []; + } + } + + static Future endAllActivities() async { + if (!Platform.isIOS) return; + try { + await _channel.invokeMethod('endAllActivities'); + _activityId = null; + _isActivityActive = false; + _logger.info('All LiveActivities ended.'); + } catch (e) { + _logger.warning('Failed to end all activities: $e'); + } + } + + static Map _createContentState({ + required Lesson currentLesson, + Lesson? nextLesson, + bool isBreak = false, + String? mode, + }) { + final now = DateTime.now(); + final isBeforeSchool = mode == 'beforeSchool'; + + DateTime startTimeForActivity; + DateTime endTimeForActivity; + + if (isBeforeSchool) { + startTimeForActivity = now; + endTimeForActivity = currentLesson.start; + } else { + startTimeForActivity = currentLesson.start; + endTimeForActivity = currentLesson.end; + } + + final nextStartTimeForActivity = nextLesson?.start; + + final payload = { + 'isBreak': isBeforeSchool ? false : isBreak, + 'lessonName': isBeforeSchool + ? currentLesson.name + : (isBreak ? 'Szünet' : currentLesson.name), + 'lessonTheme': (isBeforeSchool || isBreak) ? null : currentLesson.theme, + 'roomName': (isBeforeSchool || isBreak) ? null : currentLesson.roomName, + 'teacherName': (isBeforeSchool || isBreak) ? null : currentLesson.teacher, + 'startTime': startTimeForActivity.toUtc().toIso8601String(), + 'endTime': endTimeForActivity.toUtc().toIso8601String(), + 'lessonNumber': (isBeforeSchool || isBreak) + ? null + : currentLesson.lessonNumber, + 'nextLessonName': isBeforeSchool ? null : nextLesson?.name, + 'nextRoomName': isBeforeSchool ? null : nextLesson?.roomName, + 'nextStartTime': nextStartTimeForActivity?.toUtc().toIso8601String(), + 'isSubstitution': currentLesson.substituteTeacher != null, + 'isCancelled': currentLesson.state.name.toLowerCase().contains('elmarad'), + 'substituteTeacher': currentLesson.substituteTeacher, + 'currentTime': now.toUtc().toIso8601String(), + 'mode': mode, + }; + return payload; + } +} diff --git a/firka/lib/services/live_activity_service.dart b/firka/lib/services/live_activity_service.dart new file mode 100644 index 00000000..468eb252 --- /dev/null +++ b/firka/lib/services/live_activity_service.dart @@ -0,0 +1,2064 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:math'; +import 'package:firka/api/client/kreta_client.dart'; +import 'package:firka/api/client/live_activity_backend_client.dart'; +import 'package:firka/data/widget.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:firka/services/live_activity_manager.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; +import 'package:firka/ui/phone/screens/live_activity/live_activity_consent_screen.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:logging/logging.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:firka/app/app_state.dart'; + +/// Service that coordinates LiveActivity functionality +/// Handles timetable synchronization, device token management, and activity updates +class LiveActivityService { + static final Logger _logger = Logger('LiveActivityService'); + static final LiveActivityBackendClient _backendClient = + LiveActivityBackendClient(); + + static const String _deviceTokenKey = 'live_activity_device_token'; + static const String _lastTimetableUpdateKey = 'live_activity_last_update'; + static const String _isRegisteredKey = 'live_activity_is_registered'; + + static Timer? _updateTimer; + static String? _cachedDeviceToken; + static bool _isInitialized = false; + + static Timer? _bellDelayDebounceTimer; + static double? _pendingBellDelay; + static double? _lastSentBellDelay; + static const Duration _bellDelayDebounceInterval = Duration(seconds: 3); + + static Timer? _morningNotificationDebounceTimer; + static double? _pendingMorningNotificationTime; + static bool? _pendingMorningNotificationEnabled; + static double? _lastSentMorningNotificationTime; + static bool? _lastSentMorningNotificationEnabled; + static const Duration _morningNotificationDebounceInterval = Duration( + seconds: 3, + ); + + static bool _tokenExpired = false; + + /// Check if token has expired (for UI notification) + static bool get isTokenExpired => _tokenExpired; + + /// Clear token expiration flag (call after successful login) + static void clearTokenExpiration() { + _tokenExpired = false; + _logger.info('Token expiration flag cleared'); + } + + /// Get current user's studentId for user-specific settings + /// If client is provided, use it directly instead of initData.client + static String? _getCurrentStudentId({KretaClient? client}) { + try { + if (client != null) { + return client.cache.token.username; + } + if (!initDone) { + return null; + } + return initData.client!.cache.token.username; + } catch (e) { + _logger.warning('Error getting current studentId: $e'); + return null; + } + } + + /// Get user-specific Live Activity enabled state from SharedPreferences + static Future _getUserLiveActivityEnabled({KretaClient? client}) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return false; + + final prefs = await SharedPreferences.getInstance(); + final key = 'live_activity_enabled_$studentId'; + return prefs.getBool(key) ?? false; + } + + /// Set user-specific Live Activity enabled state to SharedPreferences + static Future _setUserLiveActivityEnabled( + bool value, { + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return; + + final prefs = await SharedPreferences.getInstance(); + final key = 'live_activity_enabled_$studentId'; + await prefs.setBool(key, value); + _logger.info('Saved LiveActivity enabled=$value for user $studentId'); + } + + /// Get user-specific privacy declined state from SharedPreferences + static Future _getUserPrivacyEverDeclined({KretaClient? client}) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return false; + + final prefs = await SharedPreferences.getInstance(); + final key = 'live_activity_privacy_ever_declined_$studentId'; + return prefs.getBool(key) ?? false; + } + + /// Set user-specific privacy declined state to SharedPreferences + static Future _setUserPrivacyEverDeclined( + bool value, { + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return; + + final prefs = await SharedPreferences.getInstance(); + final key = 'live_activity_privacy_ever_declined_$studentId'; + await prefs.setBool(key, value); + _logger.info('Saved privacy ever declined=$value for user $studentId'); + } + + /// Get user-specific morning notification enabled state from SharedPreferences + static Future _getUserMorningNotificationEnabled({ + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return true; + + final prefs = await SharedPreferences.getInstance(); + final key = 'morning_notification_enabled_$studentId'; + return prefs.getBool(key) ?? true; + } + + /// Set user-specific morning notification enabled state to SharedPreferences + static Future _setUserMorningNotificationEnabled( + bool value, { + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return; + + final prefs = await SharedPreferences.getInstance(); + final key = 'morning_notification_enabled_$studentId'; + await prefs.setBool(key, value); + _logger.info( + 'Saved morning notification enabled=$value for user $studentId', + ); + } + + /// Get user-specific morning notification time from SharedPreferences + static Future _getUserMorningNotificationTime({ + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return 120; + + final prefs = await SharedPreferences.getInstance(); + final key = 'morning_notification_time_$studentId'; + return prefs.getInt(key) ?? 120; + } + + /// Set user-specific morning notification time to SharedPreferences + static Future _setUserMorningNotificationTime( + int value, { + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return; + + final prefs = await SharedPreferences.getInstance(); + final key = 'morning_notification_time_$studentId'; + await prefs.setInt(key, value); + _logger.info('Saved morning notification time=$value for user $studentId'); + } + + /// Get user-specific bell delay from SharedPreferences + static Future _getUserBellDelay({KretaClient? client}) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return 0.0; + + final prefs = await SharedPreferences.getInstance(); + final key = 'bell_delay_$studentId'; + return prefs.getDouble(key) ?? 0.0; + } + + /// Set user-specific bell delay to SharedPreferences + static Future _setUserBellDelay( + double value, { + KretaClient? client, + }) async { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) return; + + final prefs = await SharedPreferences.getInstance(); + final key = 'bell_delay_$studentId'; + await prefs.setDouble(key, value); + _logger.info('Saved bell delay=$value for user $studentId'); + } + + /// Sync global settings with current user's settings + /// This ensures the Settings UI shows the correct state for the current user + static Future syncGlobalSettingWithCurrentUser({ + KretaClient? client, + }) async { + if (!Platform.isIOS) return; + + try { + final studentId = _getCurrentStudentId(client: client); + if (studentId == null) { + _logger.warning('Cannot sync global setting: no current user'); + return; + } + + final userLiveActivityEnabled = await _getUserLiveActivityEnabled( + client: client, + ); + if (Settings.liveActivityEnabled.value != userLiveActivityEnabled) { + await Settings.liveActivityEnabled.setSilently(userLiveActivityEnabled); + _logger.info( + 'Global LiveActivity setting synced: $userLiveActivityEnabled for user $studentId', + ); + } + + final userMorningEnabled = await _getUserMorningNotificationEnabled( + client: client, + ); + if (Settings.morningNotificationEnabled.value != userMorningEnabled) { + await Settings.morningNotificationEnabled.setSilently( + userMorningEnabled, + ); + _logger.info( + 'Global morning notification enabled synced: $userMorningEnabled for user $studentId', + ); + } + + final userMorningTime = await _getUserMorningNotificationTime( + client: client, + ); + if (Settings.morningNotificationTime.value.toInt() != userMorningTime) { + await Settings.morningNotificationTime.setSilently( + userMorningTime.toDouble(), + ); + _logger.info( + 'Global morning notification time synced: $userMorningTime for user $studentId', + ); + } + + final userBellDelay = await _getUserBellDelay(client: client); + if (Settings.bellDelay.value != userBellDelay) { + await Settings.bellDelay.setSilently(userBellDelay); + _logger.info( + 'Global bell delay synced: $userBellDelay for user $studentId', + ); + } + + initData.themeCubit.refresh(); + } catch (e) { + _logger.warning('Error syncing global settings: $e'); + } + } + + /// Get current language code from settings + static String? _getCurrentLanguageCode() { + try { + if (!initDone) { + return 'hu'; + } + + switch (Settings.language.value) { + case AppLanguage.hu: + return 'hu'; + case AppLanguage.en: + return 'en'; + case AppLanguage.de: + return 'de'; + case AppLanguage.auto: + final systemLang = Platform.localeName.split('_').first; + if (['hu', 'en', 'de'].contains(systemLang)) { + return systemLang; + } + return 'hu'; + } + } catch (e) { + _logger.warning('Error getting current language: $e'); + return 'hu'; + } + } + + /// Update language preference on backend for Live Activity localization + static Future updateLanguagePreference(String languageCode) async { + try { + if (!Platform.isIOS) return; + + final isEnabled = await _getUserLiveActivityEnabled(); + if (!isEnabled) { + _logger.fine('Skipping language update: Live Activity is disabled'); + return; + } + + final prefs = await SharedPreferences.getInstance(); + final deviceToken = prefs.getString(_deviceTokenKey); + + if (deviceToken == null) { + _logger.warning('Cannot update language: device token not found'); + return; + } + + final success = await _backendClient.updateLanguage( + deviceToken: deviceToken, + language: languageCode, + ); + + if (success) { + _logger.info('Language preference updated to $languageCode'); + } else { + _logger.warning('Failed to update language preference'); + } + } catch (e) { + _logger.severe('Error updating language preference: $e'); + } + } + + /// Today's cache models mapped back to [Lesson], the type the backend payload is built from. + static Future> _lessonsBetween( + KretaClient client, + DateTime from, + DateTime to, + ) async { + final lessons = await client.getLessons(from, to); + return lessons + .map( + (l) => Lesson( + uid: l.uid ?? '', + date: l.start.toIso8601String(), + start: l.start, + end: l.end, + name: l.name, + lessonNumber: l.dailyNth, + lessonSeqNumber: l.yearlyNth, + teacher: l.teacher, + theme: l.topic, + roomName: l.roomName, + type: NameUidDesc(uid: '', name: l.type, description: ''), + state: NameUidDesc(uid: '', name: l.state, description: ''), + substituteTeacher: l.substituteTeacher, + canStudentEditHomework: false, + isHomeworkComplete: false, + attachments: const [], + isDigitalLesson: false, + digitalSupportDeviceTypeList: const [], + createdAt: l.createdAt, + lastModifiedAt: l.createdAt, + ), + ) + .toList(); + } + + /// Initialize the LiveActivity service + static Future initialize() async { + if (!Platform.isIOS) { + return; + } + + _isInitialized = false; + _cachedDeviceToken = null; + + try { + await LiveActivityManager.initialize(); + + LiveActivityManager.setOnPushTokenReceived(_onPushTokenReceived); + + final deviceToken = + await LiveActivityManager.registerForPushNotifications(); + + if (deviceToken != null) { + _cachedDeviceToken = deviceToken; + await _saveDeviceToken(deviceToken); + } + + _setupBackgroundFetchChannel(); + + _isInitialized = true; + } catch (e, stackTrace) { + _logger.severe('Failed to initialize LiveActivity: $e', e, stackTrace); + } + } + + /// Setup method channel for background fetch + static void _setupBackgroundFetchChannel() { + const platform = MethodChannel('firka.app/background_fetch'); + platform.setMethodCallHandler((call) async { + if (call.method == 'performBackgroundFetch') { + _logger.info('Background fetch triggered by iOS'); + final success = await _performBackgroundFetch(); + return success; + } + return false; + }); + } + + /// Schedule background fetch on iOS + static Future scheduleBackgroundFetch() async { + if (!Platform.isIOS) return; + + try { + const platform = MethodChannel('firka.app/background_fetch'); + await platform.invokeMethod('scheduleBackgroundFetch'); + _logger.info('Background fetch scheduled'); + } catch (e) { + _logger.warning('Failed to schedule background fetch: $e'); + } + } + + /// Cancel background fetch on iOS + static Future cancelBackgroundFetch() async { + if (!Platform.isIOS) return; + + try { + const platform = MethodChannel('firka.app/background_fetch'); + await platform.invokeMethod('cancelBackgroundFetch'); + _logger.info('Background fetch cancelled'); + } catch (e) { + _logger.warning('Failed to cancel background fetch: $e'); + } + } + + /// Perform background fetch - fetch fresh timetable from KRÉTA API and send to backend + /// This is called by iOS BGTaskScheduler when the app is in background + static Future _performBackgroundFetch() async { + if (!Platform.isIOS || !_isInitialized || !initDone) { + _logger.warning( + 'Background fetch skipped: not initialized or initDone=false', + ); + return false; + } + + try { + final client = initData.client!; + + final enabled = await isEnabled(initData.settings, client); + if (!enabled) { + _logger.info('Background fetch skipped: LiveActivity disabled'); + return false; + } + + _logger.info('Background fetch: fetching fresh timetable from KRÉTA API'); + + final now = DateTime.now(); + final todayStart = DateTime(now.year, now.month, now.day); + final startOfWeek = todayStart.subtract(Duration(days: now.weekday - 1)); + final endOfWeek = startOfWeek.add(const Duration(days: 6)); + + List allLessons = []; + + try { + _logger.info( + 'Background fetch: attempting to fetch fresh data from KRÉTA API', + ); + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + _logger.info( + 'Background fetch: successfully fetched ${allLessons.length} lessons from KRÉTA API', + ); + } catch (e) { + _logger.warning( + 'Background fetch: KRÉTA API failed ($e), falling back to cache', + ); + try { + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + _logger.info( + 'Background fetch: successfully loaded ${allLessons.length} lessons from cache', + ); + } catch (cacheError) { + _logger.severe( + 'Background fetch: cache fallback also failed: $cacheError', + ); + return false; + } + } + + try { + _logger.info('Background fetch: refreshing iOS widgets...'); + await WidgetCacheHelper.refreshIOSWidgets(client, initData.settings); + _logger.info('Background fetch: iOS widgets refreshed successfully'); + } catch (e) { + _logger.warning('Background fetch: failed to refresh iOS widgets: $e'); + } + + bool foundFirstSchoolDay = false; + for (int dayOffset = 1; dayOffset <= 5; dayOffset++) { + final candidateDay = endOfWeek.add(Duration(days: dayOffset)); + + if (candidateDay.weekday == DateTime.saturday || + candidateDay.weekday == DateTime.sunday) { + continue; + } + + try { + final candidateDayEnd = candidateDay.add(const Duration(days: 1)); + final fetched = await _lessonsBetween(client, candidateDay, candidateDayEnd); + + if (fetched.isNotEmpty) { + final schoolLessons = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + return uid.contains('orarendiora') || + uid.contains('tanitasiora') || + uid.contains('uresora'); + }).toList(); + + if (schoolLessons.isNotEmpty) { + schoolLessons.sort((a, b) => a.start.compareTo(b.start)); + final firstLesson = schoolLessons.first; + + final markedLesson = Lesson( + uid: '${firstLesson.uid}__FOR_NOTIFICATION_ONLY', + date: firstLesson.date, + start: firstLesson.start, + end: firstLesson.end, + name: firstLesson.name, + lessonNumber: firstLesson.lessonNumber, + teacher: firstLesson.teacher, + theme: firstLesson.theme, + roomName: firstLesson.roomName, + substituteTeacher: firstLesson.substituteTeacher, + type: firstLesson.type, + state: firstLesson.state, + canStudentEditHomework: firstLesson.canStudentEditHomework, + isHomeworkComplete: firstLesson.isHomeworkComplete, + attachments: firstLesson.attachments, + isDigitalLesson: firstLesson.isDigitalLesson, + digitalSupportDeviceTypeList: + firstLesson.digitalSupportDeviceTypeList, + createdAt: firstLesson.createdAt, + lastModifiedAt: firstLesson.lastModifiedAt, + ); + + allLessons.add(markedLesson); + + const dayNames = [ + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + ]; + final dayName = dayNames[candidateDay.weekday - 1]; + _logger.info( + 'Background fetch: added first lesson from next week $dayName (${firstLesson.name}) marked for notification scheduling only', + ); + + foundFirstSchoolDay = true; + break; + } + } + } catch (e) { + _logger.warning( + 'Background fetch: could not fetch lessons for day offset $dayOffset: $e', + ); + } + } + + if (!foundFirstSchoolDay) { + _logger.info( + 'Background fetch: no school lessons found in next week for push notification scheduling', + ); + } + + if (allLessons.isEmpty) { + _logger.info('Background fetch: no lessons to send'); + return true; + } + + final deviceToken = await _getOrWaitDeviceToken(); + if (deviceToken == null) { + _logger.warning('Background fetch: no device token available'); + return false; + } + + final userBellDelay = await _getUserBellDelay(); + _logger.info( + 'Background fetch: sending ${allLessons.length} lessons to backend', + ); + final success = await _backendClient.updateTimetable( + deviceToken: deviceToken, + timetable: allLessons, + bellDelay: userBellDelay, + ); + + if (success) { + await _saveLastUpdate(); + _logger.info( + 'Background fetch: successfully sent timetable to backend', + ); + _logger.info('Background fetch: keeping periodic scheduling active'); + return true; + } else { + _logger.warning( + 'Background fetch: failed to send timetable to backend', + ); + return false; + } + } catch (e, stackTrace) { + _logger.severe('Background fetch: unexpected error: $e', e, stackTrace); + return false; + } + } + + /// Check if LiveActivity is enabled in settings + static Future isEnabled([ + SettingsRepository? settingsStore, + KretaClient? client, + ]) async { + try { + return await _getUserLiveActivityEnabled(client: client); + } catch (e) { + _logger.warning('Error reading LiveActivity setting: $e'); + return false; + } + } + + /// Handle LiveActivity enabled state change + /// Called from settings toggle callback + static Future handleEnabledChange( + bool enabled, { + bool isManual = false, + KretaClient? client, + }) async { + if (!Platform.isIOS) return; + + try { + final effectiveClient = initData.client!; + final studentId = _getCurrentStudentId(client: effectiveClient); + if (studentId == null) { + _logger.warning('Cannot change LiveActivity state: no current user'); + return; + } + + if (!enabled) { + final deviceToken = + _cachedDeviceToken ?? await LiveActivityManager.getDeviceToken(); + if (deviceToken != null) { + _logger.info('Notifying backend that Live Activity is disabled'); + await _backendClient.toggleLiveActivity( + deviceToken: deviceToken, + liveActivityEnabled: false, + ); + } + + _logger.info('Ending all LiveActivities'); + await LiveActivityManager.endAllActivities(); + + _logger.info('Clearing cache'); + await _clearCache(); + + _logger.info('Stopping timetable monitoring'); + _stopTimetableMonitoring(); + + await _setUserLiveActivityEnabled(false, client: effectiveClient); + await syncGlobalSettingWithCurrentUser(client: effectiveClient); + + _logger.info( + 'LiveActivity disabled and user data cleared (device remains in backend for push notifications)', + ); + } else { + _logger.info('Showing privacy consent screen (manual: $isManual)'); + final bool? accepted = await _showPrivacyConsentScreen(); + + if (accepted == true) { + _logger.info('User accepted privacy policy'); + + await _setUserLiveActivityEnabled(true, client: effectiveClient); + await syncGlobalSettingWithCurrentUser(client: effectiveClient); + + final deviceToken = + _cachedDeviceToken ?? await LiveActivityManager.getDeviceToken(); + + if (deviceToken != null) { + _logger.info('Notifying backend that Live Activity is enabled'); + await _backendClient.toggleLiveActivity( + deviceToken: deviceToken, + liveActivityEnabled: true, + ); + } + + await effectiveClient.getStudent(); + final activeToken = initData.client!.cache.token; + final studentName = activeToken.username; + + await onUserLogin( + client: effectiveClient, + studentName: studentName, + settingsStore: initData.settings, + ); + } else { + _logger.info('User declined privacy policy or swiped back'); + + await _setUserLiveActivityEnabled(false, client: effectiveClient); + await _setUserPrivacyEverDeclined(true, client: effectiveClient); + + await syncGlobalSettingWithCurrentUser(client: effectiveClient); + } + } + } catch (e) { + _logger.warning('Error handling LiveActivity enabled change: $e'); + } + } + + /// Show privacy consent screen automatically on first use or user switch + /// Only shows if user hasn't declined before + static Future showConsentScreenIfNeeded({KretaClient? client}) async { + if (!Platform.isIOS) return; + + try { + final effectiveClient = client ?? initData.client; + final studentId = _getCurrentStudentId(client: effectiveClient); + if (studentId == null) { + _logger.warning('Cannot check consent screen: no current user'); + return; + } + + await syncGlobalSettingWithCurrentUser(client: effectiveClient); + + final enabled = await _getUserLiveActivityEnabled( + client: effectiveClient, + ); + final everDeclined = await _getUserPrivacyEverDeclined( + client: effectiveClient, + ); + + if (!enabled && !everDeclined) { + _logger.info( + 'First use or new user - showing privacy consent automatically', + ); + await handleEnabledChange( + true, + isManual: false, + client: effectiveClient, + ); + } else { + _logger.info( + 'User already has LiveActivity setting: enabled=$enabled, declined=$everDeclined', + ); + } + } catch (e) { + _logger.warning('Error checking if consent screen needed: $e'); + } + } + + /// Show privacy consent screen + static Future _showPrivacyConsentScreen() async { + final context = initData.navigatorKey.currentContext; + if (context == null) { + _logger.warning('No context available to show consent screen'); + return false; + } + + final bool? result = await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => LiveActivityConsentScreen(data: initData), + ), + ); + + return result; + } + + /// Handle token expiration - deactivate LiveActivity + static Future onTokenExpired() async { + if (!Platform.isIOS) return; + + try { + _logger.info('Token expired, deactivating LiveActivity'); + + await LiveActivityManager.endAllActivities(); + + _stopTimetableMonitoring(); + } catch (e) { + _logger.severe('Error handling token expiration for LiveActivity: $e'); + } + } + + /// Handle LiveActivity push token received from Swift side + static Future _onPushTokenReceived( + String activityId, + String pushToken, + ) async { + _logger.info('LiveActivity push token received, updating backend...'); + + try { + final deviceToken = + _cachedDeviceToken ?? await LiveActivityManager.getDeviceToken(); + if (deviceToken == null) { + _logger.warning('No device token available to update push token'); + return; + } + + final success = await _backendClient.updatePushToken( + deviceToken: deviceToken, + pushToken: pushToken, + ); + + if (success) { + _logger.info('LiveActivity push token updated successfully in backend'); + } else { + _logger.warning('Failed to update LiveActivity push token in backend'); + } + } catch (e) { + _logger.severe('Error updating LiveActivity push token: $e'); + } + } + + /// Called when user logs in successfully + /// Registers the device and uploads the *full* timetable + static Future onUserLogin({ + required KretaClient client, + required String studentName, + SettingsRepository? settingsStore, + }) async { + _logger.info('onUserLogin: Function called for $studentName'); + + if (!Platform.isIOS || !_isInitialized) { + _logger.warning( + 'onUserLogin: Returning early - Platform.isIOS=${Platform.isIOS}, _isInitialized=$_isInitialized', + ); + return; + } + + final liveActivityEnabled = await isEnabled(settingsStore, client); + final morningNotificationEnabled = + _getCurrentMorningNotificationEnabled() ?? false; + _logger.info( + 'onUserLogin: liveActivityEnabled=$liveActivityEnabled, morningNotificationEnabled=$morningNotificationEnabled', + ); + + if (!liveActivityEnabled && !morningNotificationEnabled) { + _logger.warning( + 'onUserLogin: Both Live Activity and Morning Notifications are disabled, returning early', + ); + return; + } + + try { + _logger.info('onUserLogin: Starting timetable fetch'); + final now = DateTime.now(); + final todayStart = DateTime(now.year, now.month, now.day); + final startOfWeek = todayStart.subtract(Duration(days: now.weekday - 1)); + final endOfWeek = startOfWeek.add(const Duration(days: 6)); + + List allLessons = []; + + try { + _logger.info( + 'onUserLogin: Attempting to fetch fresh timetable from KRÉTA API', + ); + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + _logger.info( + 'onUserLogin: Successfully fetched ${allLessons.length} lessons from KRÉTA API', + ); + } catch (e) { + _logger.warning( + 'onUserLogin: KRÉTA API failed ($e), falling back to cache', + ); + try { + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + _logger.info( + 'onUserLogin: Successfully loaded ${allLessons.length} lessons from cache', + ); + } catch (cacheError) { + _logger.severe( + 'onUserLogin: Cache fallback also failed: $cacheError', + ); + return; + } + } + + if (allLessons.isEmpty) { + _logger.warning('onUserLogin: No lessons found, returning early'); + return; + } + + final nextWeekStart = endOfWeek.add(const Duration(days: 1)); + final nextWeekEnd = nextWeekStart.add(const Duration(days: 6)); + + _logger.info( + '[GlobalSearch] onUserLogin: Checking next week (${nextWeekStart.toString().split(' ')[0]} - ${nextWeekEnd.toString().split(' ')[0]}) for events', + ); + + List nextWeekBreakEvents = []; + try { + final fetched = await _lessonsBetween(client, nextWeekStart, nextWeekEnd); + + if (fetched.isNotEmpty) { + nextWeekBreakEvents = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + final name = lesson.name.toLowerCase(); + return uid.contains('tanevrendjeesemeny') && + !name.contains('tanítási nap') && + (name.contains('szünet') || + name.contains('pihenőnap') || + name.contains('munkaszüneti') || + name.contains('ünnepnap') || + name.contains('tanítás nélküli') || + name.contains('nem órarendi nap')); + }).toList(); + + if (nextWeekBreakEvents.isNotEmpty) { + _logger.info( + '[GlobalSearch] onUserLogin: Found ${nextWeekBreakEvents.length} break event(s) in next week - triggering global searcher', + ); + } + } + } catch (e) { + _logger.warning( + '[GlobalSearch] onUserLogin: Could not fetch next week: $e', + ); + } + + if (nextWeekBreakEvents.isNotEmpty) { + nextWeekBreakEvents.sort((a, b) => a.start.compareTo(b.start)); + final firstBreakEvent = nextWeekBreakEvents.first; + + _logger.info( + '[GlobalSearch] onUserLogin: Triggering global break searcher from ${firstBreakEvent.date.split('T')[0]}', + ); + + final searchResult = await _globalBreakSearcher( + client: client, + searchStartDate: nextWeekStart, + ); + + if (searchResult.tokenExpired) { + _tokenExpired = true; + _logger.warning( + '[GlobalSearch] onUserLogin: Token expired during global search', + ); + } + + allLessons.addAll(searchResult.allLessons); + + _logger.info( + '[GlobalSearch] onUserLogin: Global searcher returned ${searchResult.allLessons.length} lessons', + ); + + if (searchResult.firstSchoolDayAfterBreak != null) { + final notificationLesson = Lesson( + uid: + '${searchResult.firstSchoolDayAfterBreak!.uid}__FOR_NOTIFICATION_ONLY', + date: searchResult.firstSchoolDayAfterBreak!.date, + start: searchResult.firstSchoolDayAfterBreak!.start, + end: searchResult.firstSchoolDayAfterBreak!.end, + name: searchResult.firstSchoolDayAfterBreak!.name, + lessonNumber: searchResult.firstSchoolDayAfterBreak!.lessonNumber, + teacher: searchResult.firstSchoolDayAfterBreak!.teacher, + theme: searchResult.firstSchoolDayAfterBreak!.theme, + roomName: searchResult.firstSchoolDayAfterBreak!.roomName, + substituteTeacher: + searchResult.firstSchoolDayAfterBreak!.substituteTeacher, + type: searchResult.firstSchoolDayAfterBreak!.type, + state: searchResult.firstSchoolDayAfterBreak!.state, + canStudentEditHomework: + searchResult.firstSchoolDayAfterBreak!.canStudentEditHomework, + isHomeworkComplete: + searchResult.firstSchoolDayAfterBreak!.isHomeworkComplete, + attachments: searchResult.firstSchoolDayAfterBreak!.attachments, + isDigitalLesson: + searchResult.firstSchoolDayAfterBreak!.isDigitalLesson, + digitalSupportDeviceTypeList: searchResult + .firstSchoolDayAfterBreak! + .digitalSupportDeviceTypeList, + createdAt: searchResult.firstSchoolDayAfterBreak!.createdAt, + lastModifiedAt: + searchResult.firstSchoolDayAfterBreak!.lastModifiedAt, + ); + + allLessons.add(notificationLesson); + _logger.info( + '[GlobalSearch] onUserLogin: Added first school day after break for push notification: ${notificationLesson.date.split('T')[0]}', + ); + } + } else { + _logger.info( + '[GlobalSearch] onUserLogin: No break events in next week, searching for first school day...', + ); + + bool foundFirstSchoolDay = false; + for (int dayOffset = 1; dayOffset <= 14; dayOffset++) { + final candidateDay = endOfWeek.add(Duration(days: dayOffset)); + + try { + final candidateDayEnd = candidateDay.add(const Duration(days: 1)); + final fetched = await _lessonsBetween(client, candidateDay, candidateDayEnd); + + if (fetched.isNotEmpty) { + final schoolLessons = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + return uid.contains('orarendiora') || + uid.contains('tanitasiora') || + uid.contains('uresora'); + }).toList(); + + if (schoolLessons.isNotEmpty) { + schoolLessons.sort((a, b) => a.start.compareTo(b.start)); + final firstLesson = schoolLessons.first; + + final markedLesson = Lesson( + uid: '${firstLesson.uid}__FOR_NOTIFICATION_ONLY', + date: firstLesson.date, + start: firstLesson.start, + end: firstLesson.end, + name: firstLesson.name, + lessonNumber: firstLesson.lessonNumber, + teacher: firstLesson.teacher, + theme: firstLesson.theme, + roomName: firstLesson.roomName, + substituteTeacher: firstLesson.substituteTeacher, + type: firstLesson.type, + state: firstLesson.state, + canStudentEditHomework: firstLesson.canStudentEditHomework, + isHomeworkComplete: firstLesson.isHomeworkComplete, + attachments: firstLesson.attachments, + isDigitalLesson: firstLesson.isDigitalLesson, + digitalSupportDeviceTypeList: + firstLesson.digitalSupportDeviceTypeList, + createdAt: firstLesson.createdAt, + lastModifiedAt: firstLesson.lastModifiedAt, + ); + + allLessons.add(markedLesson); + _logger.info( + '[GlobalSearch] onUserLogin: Found first school day for push notification: ${candidateDay.toString().split(' ')[0]}', + ); + + foundFirstSchoolDay = true; + break; + } + } + } catch (e) { + _logger.warning( + '[GlobalSearch] onUserLogin: Could not fetch day offset $dayOffset: $e', + ); + } + } + + if (!foundFirstSchoolDay) { + _logger.info( + '[GlobalSearch] onUserLogin: No school lessons found in next 14 days for push notification scheduling', + ); + } + } + + final deviceToken = await _getOrWaitDeviceToken(); + + if (deviceToken == null) { + return; + } + + String? currentLanguage = _getCurrentLanguageCode(); + + final userMorningNotificationTime = + await _getUserMorningNotificationTime(); + final userMorningNotificationEnabled = + await _getUserMorningNotificationEnabled(); + final userLiveActivityEnabled = await _getUserLiveActivityEnabled(); + final userBellDelay = await _getUserBellDelay(); + + final success = await _backendClient.registerDevice( + deviceToken: deviceToken, + timetable: allLessons, + language: currentLanguage, + bellDelay: userBellDelay, + morningNotificationTime: userMorningNotificationTime, + morningNotificationEnabled: userMorningNotificationEnabled, + liveActivityEnabled: userLiveActivityEnabled, + ); + + if (success) { + await _markAsRegistered(); + await _saveLastUpdate(); + + if (liveActivityEnabled) { + await _startPlaceholderActivity(allLessons, studentName); + } + + await _startTimetableMonitoring( + client: client, + studentName: studentName, + settingsStore: settingsStore, + ); + + await scheduleBackgroundFetch(); + + _logger.info('LiveActivity registration completed for $studentName'); + } else { + _logger.warning('Failed to register device with backend'); + } + } catch (e, st) { + _logger.severe('Error during onUserLogin: $e', e, st); + } + } + + /// Called when user logs out + static Future onUserLogout() async { + _logger.info('onUserLogout: Function called'); + + if (!Platform.isIOS) { + _logger.warning('onUserLogout: Not iOS, returning early'); + return; + } + + try { + _logger.info('onUserLogout: Ending all activities'); + await LiveActivityManager.endAllActivities(); + + final deviceToken = + _cachedDeviceToken ?? await LiveActivityManager.getDeviceToken(); + _logger.info( + 'onUserLogout: Device token = ${deviceToken?.substring(0, 10)}...', + ); + + if (deviceToken != null) { + _logger.info('onUserLogout: Unregistering device from backend'); + await _backendClient.unregisterDevice(deviceToken: deviceToken); + } + + _logger.info('onUserLogout: Clearing cache'); + await _clearCache(); + + _logger.info('onUserLogout: Stopping timetable monitoring'); + _stopTimetableMonitoring(); + + _logger.info('User logout processed for LiveActivity'); + } catch (e) { + _logger.severe('Error processing user logout for LiveActivity: $e'); + } + } + + /// Check for timetable changes and update if necessary + static Future checkAndUpdateTimetable({ + required KretaClient client, + required String studentName, + SettingsRepository? settingsStore, + bool forceUpdate = false, + }) async { + if (!Platform.isIOS || !_isInitialized) return; + + final liveActivityEnabled = await isEnabled(settingsStore, client); + final morningNotificationEnabled = + _getCurrentMorningNotificationEnabled() ?? false; + + if (!liveActivityEnabled && !morningNotificationEnabled) { + _logger.info( + 'Both Live Activity and Morning Notifications are disabled, skipping timetable fetch', + ); + return; + } + + try { + final now = DateTime.now(); + final todayStart = DateTime(now.year, now.month, now.day); + final startOfWeek = todayStart.subtract(Duration(days: now.weekday - 1)); + final endOfWeek = startOfWeek.add(const Duration(days: 6)); + + List allLessons = []; + + try { + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + } catch (e) { + _logger.warning( + 'checkAndUpdateTimetable: KRÉTA API failed ($e), falling back to cache', + ); + try { + allLessons = await _lessonsBetween(client, startOfWeek, endOfWeek); + } catch (cacheError) { + _logger.severe( + 'checkAndUpdateTimetable: Cache fallback also failed: $cacheError', + ); + return; + } + } + + final nextWeekStart = endOfWeek.add(const Duration(days: 1)); + final nextWeekEnd = nextWeekStart.add(const Duration(days: 6)); + + _logger.info( + '[GlobalSearch] Checking next week (${nextWeekStart.toString().split(' ')[0]} - ${nextWeekEnd.toString().split(' ')[0]}) for events', + ); + + List nextWeekBreakEvents = []; + try { + final fetched = await _lessonsBetween(client, nextWeekStart, nextWeekEnd); + + if (fetched.isNotEmpty) { + nextWeekBreakEvents = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + final name = lesson.name.toLowerCase(); + return uid.contains('tanevrendjeesemeny') && + !name.contains('tanítási nap') && + (name.contains('szünet') || + name.contains('pihenőnap') || + name.contains('munkaszüneti') || + name.contains('ünnepnap') || + name.contains('tanítás nélküli') || + name.contains('nem órarendi nap')); + }).toList(); + + if (nextWeekBreakEvents.isNotEmpty) { + _logger.info( + '[GlobalSearch] Found ${nextWeekBreakEvents.length} break event(s) in next week - triggering global searcher', + ); + } + } + } catch (e) { + _logger.warning('[GlobalSearch] Could not fetch next week: $e'); + } + + if (nextWeekBreakEvents.isNotEmpty) { + nextWeekBreakEvents.sort((a, b) => a.start.compareTo(b.start)); + final firstBreakEvent = nextWeekBreakEvents.first; + + _logger.info( + '[GlobalSearch] Triggering global break searcher from ${firstBreakEvent.date.split('T')[0]}', + ); + + final searchResult = await _globalBreakSearcher( + client: client, + searchStartDate: nextWeekStart, + ); + + if (searchResult.tokenExpired) { + _tokenExpired = true; + _logger.warning('[GlobalSearch] Token expired during global search'); + } + + allLessons.addAll(searchResult.allLessons); + + _logger.info( + '[GlobalSearch] Global searcher returned ${searchResult.allLessons.length} lessons', + ); + + if (searchResult.firstSchoolDayAfterBreak != null) { + final notificationLesson = Lesson( + uid: + '${searchResult.firstSchoolDayAfterBreak!.uid}__FOR_NOTIFICATION_ONLY', + date: searchResult.firstSchoolDayAfterBreak!.date, + start: searchResult.firstSchoolDayAfterBreak!.start, + end: searchResult.firstSchoolDayAfterBreak!.end, + name: searchResult.firstSchoolDayAfterBreak!.name, + lessonNumber: searchResult.firstSchoolDayAfterBreak!.lessonNumber, + teacher: searchResult.firstSchoolDayAfterBreak!.teacher, + theme: searchResult.firstSchoolDayAfterBreak!.theme, + roomName: searchResult.firstSchoolDayAfterBreak!.roomName, + substituteTeacher: + searchResult.firstSchoolDayAfterBreak!.substituteTeacher, + type: searchResult.firstSchoolDayAfterBreak!.type, + state: searchResult.firstSchoolDayAfterBreak!.state, + canStudentEditHomework: + searchResult.firstSchoolDayAfterBreak!.canStudentEditHomework, + isHomeworkComplete: + searchResult.firstSchoolDayAfterBreak!.isHomeworkComplete, + attachments: searchResult.firstSchoolDayAfterBreak!.attachments, + isDigitalLesson: + searchResult.firstSchoolDayAfterBreak!.isDigitalLesson, + digitalSupportDeviceTypeList: searchResult + .firstSchoolDayAfterBreak! + .digitalSupportDeviceTypeList, + createdAt: searchResult.firstSchoolDayAfterBreak!.createdAt, + lastModifiedAt: + searchResult.firstSchoolDayAfterBreak!.lastModifiedAt, + ); + + allLessons.add(notificationLesson); + _logger.info( + '[GlobalSearch] Added first school day after break for push notification: ${notificationLesson.date.split('T')[0]}', + ); + } + } else { + _logger.info( + '[GlobalSearch] No break events in next week, searching for first school day...', + ); + + bool foundFirstSchoolDay = false; + for (int dayOffset = 1; dayOffset <= 14; dayOffset++) { + final candidateDay = endOfWeek.add(Duration(days: dayOffset)); + + try { + final candidateDayEnd = candidateDay.add(const Duration(days: 1)); + final fetched = await _lessonsBetween(client, candidateDay, candidateDayEnd); + + if (fetched.isNotEmpty) { + final schoolLessons = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + return uid.contains('orarendiora') || + uid.contains('tanitasiora') || + uid.contains('uresora'); + }).toList(); + + if (schoolLessons.isNotEmpty) { + schoolLessons.sort((a, b) => a.start.compareTo(b.start)); + final firstLesson = schoolLessons.first; + + final markedLesson = Lesson( + uid: '${firstLesson.uid}__FOR_NOTIFICATION_ONLY', + date: firstLesson.date, + start: firstLesson.start, + end: firstLesson.end, + name: firstLesson.name, + lessonNumber: firstLesson.lessonNumber, + teacher: firstLesson.teacher, + theme: firstLesson.theme, + roomName: firstLesson.roomName, + substituteTeacher: firstLesson.substituteTeacher, + type: firstLesson.type, + state: firstLesson.state, + canStudentEditHomework: firstLesson.canStudentEditHomework, + isHomeworkComplete: firstLesson.isHomeworkComplete, + attachments: firstLesson.attachments, + isDigitalLesson: firstLesson.isDigitalLesson, + digitalSupportDeviceTypeList: + firstLesson.digitalSupportDeviceTypeList, + createdAt: firstLesson.createdAt, + lastModifiedAt: firstLesson.lastModifiedAt, + ); + + allLessons.add(markedLesson); + _logger.info( + '[GlobalSearch] Found first school day for push notification: ${candidateDay.toString().split(' ')[0]}', + ); + + foundFirstSchoolDay = true; + break; + } + } + } catch (e) { + _logger.warning( + '[GlobalSearch] Could not fetch day offset $dayOffset: $e', + ); + } + } + + if (!foundFirstSchoolDay) { + _logger.info( + '[GlobalSearch] No school lessons found in next 14 days for push notification scheduling', + ); + } + } + + if (allLessons.isEmpty) { + await LiveActivityManager.endAllActivities(); + return; + } + + final deviceToken = await _getOrWaitDeviceToken(); + if (deviceToken == null) return; + + bool shouldUpdate = forceUpdate; + + if (!forceUpdate) { + final lastUpdate = await _getLastUpdate(); + final hasChanges = await _backendClient.checkTimetableChanges( + deviceToken: deviceToken, + lastUpdated: lastUpdate, + ); + shouldUpdate = hasChanges; + } + + if (shouldUpdate) { + if (forceUpdate) { + _logger.info( + 'Forcing timetable update (notification settings changed)...', + ); + } else { + _logger.info('Timetable changes detected, sending to backend...'); + } + + final userBellDelay = await _getUserBellDelay(); + final success = await _backendClient.updateTimetable( + deviceToken: deviceToken, + timetable: allLessons, + bellDelay: userBellDelay, + ); + + if (success) { + await _saveLastUpdate(); + _logger.info( + 'Timetable sent to backend successfully. Backend will update LiveActivity.', + ); + } + } + } catch (e) { + _logger.severe('Error checking and updating timetable: $e'); + } + } + + /// Start monitoring timetable and updating LiveActivity + static Future _startTimetableMonitoring({ + required KretaClient client, + required String studentName, + SettingsRepository? settingsStore, + }) async { + _stopTimetableMonitoring(); + + await checkAndUpdateTimetable( + client: client, + studentName: studentName, + settingsStore: settingsStore, + ); + + // Pediódikus frissítés (minden 30 percben) + // Ez azért kell, hogy a KRETA változásokat észleljük, + // és összevessük az adatbázisban tárolt adatokkal. + _updateTimer = Timer.periodic(const Duration(minutes: 30), (timer) async { + await checkAndUpdateTimetable( + client: client, + studentName: studentName, + settingsStore: settingsStore, + ); + }); + + _logger.info('Timetable monitoring started'); + } + + /// Stop monitoring timetable + static void _stopTimetableMonitoring() { + _updateTimer?.cancel(); + _updateTimer = null; + _logger.info('Timetable monitoring stopped'); + } + + /// Force update LiveActivity with latest data + static Future forceUpdate({ + required KretaClient client, + required String studentName, + }) async { + await checkAndUpdateTimetable(client: client, studentName: studentName); + } + + /// Starts a minimal placeholder activity shell - backend will update with real data + static Future _startPlaceholderActivity( + List allLessons, + String studentName, { + bool isBackground = false, + }) async { + if (isBackground) { + _logger.info( + '_startPlaceholderActivity: Called from background context, skipping to preserve existing activity', + ); + return; + } + + // Always end existing activities to ensure fresh token (8-hour expiration) + final activeActivities = await LiveActivityManager.getActiveActivities(); + if (activeActivities.isNotEmpty) { + _logger.info( + '_startPlaceholderActivity: Ending existing activities before creating new one', + ); + await LiveActivityManager.endAllActivities(); + await Future.delayed(const Duration(milliseconds: 500)); + } + + _logger.info( + '_startPlaceholderActivity: Creating minimal loading shell, backend will update.', + ); + + final now = DateTime.now(); + + Lesson placeholderLesson; + if (allLessons.isNotEmpty) { + final template = allLessons.first; + placeholderLesson = Lesson( + uid: 'loading-placeholder', + date: now.toIso8601String(), + start: now, + end: now.add(const Duration(minutes: 1)), + name: 'Betöltés...', + type: template.type, + state: template.state, + canStudentEditHomework: false, + isHomeworkComplete: false, + attachments: [], + isDigitalLesson: false, + digitalSupportDeviceTypeList: [], + createdAt: now, + lastModifiedAt: now, + ); + } else { + final emptyType = NameUidDesc( + uid: 'placeholder', + name: 'Placeholder', + description: '', + ); + final emptyState = NameUidDesc( + uid: 'active', + name: 'Active', + description: '', + ); + + placeholderLesson = Lesson( + uid: 'loading-placeholder', + date: now.toIso8601String(), + start: now, + end: now.add(const Duration(minutes: 1)), + name: 'Betöltés...', + type: emptyType, + state: emptyState, + canStudentEditHomework: false, + isHomeworkComplete: false, + attachments: [], + isDigitalLesson: false, + digitalSupportDeviceTypeList: [], + createdAt: now, + lastModifiedAt: now, + ); + } + + await LiveActivityManager.startActivity( + studentName: studentName, + schoolName: 'Iskola', + currentLesson: placeholderLesson, + isBreak: false, + mode: 'loading', + ); + + _logger.info( + '_startPlaceholderActivity: Placeholder created, waiting for backend update.', + ); + } + + static Future _saveDeviceToken(String token) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_deviceTokenKey, token); + } + + static Future _getDeviceToken() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getString(_deviceTokenKey); + } + + static Future _saveLastUpdate() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString( + _lastTimetableUpdateKey, + DateTime.now().toIso8601String(), + ); + } + + static Future _getLastUpdate() async { + final prefs = await SharedPreferences.getInstance(); + final lastUpdateStr = prefs.getString(_lastTimetableUpdateKey); + if (lastUpdateStr != null) { + return DateTime.parse(lastUpdateStr); + } + return DateTime.now().subtract(const Duration(days: 365)); + } + + static Future _markAsRegistered() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_isRegisteredKey, true); + } + + /*static Future _isRegistered() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getBool(_isRegisteredKey) ?? false; + }*/ + + static Future _clearCache() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_lastTimetableUpdateKey); + await prefs.remove(_isRegisteredKey); + } + + /// Try to get cached token or wait a short period until iOS provides it + static Future _getOrWaitDeviceToken({ + Duration timeout = const Duration(seconds: 5), + }) async { + if (_cachedDeviceToken != null) { + return _cachedDeviceToken; + } + + final saved = await _getDeviceToken(); + if (saved != null) { + _cachedDeviceToken = saved; + return saved; + } + + final start = DateTime.now(); + String? token = await LiveActivityManager.getDeviceToken(); + while (token == null && DateTime.now().difference(start) < timeout) { + await Future.delayed(const Duration(milliseconds: 300)); + token = await LiveActivityManager.getDeviceToken(); + } + // The push server only uses this as a device id, so a random one works without APNs. + token ??= List.generate( + 16, + (_) => Random.secure().nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + _cachedDeviceToken = token; + await _saveDeviceToken(token); + return token; + } + + /// Send a test notification (for debugging) + static Future sendTestNotification() async { + if (!Platform.isIOS || !_isInitialized) return false; + + try { + final deviceToken = await _getOrWaitDeviceToken(); + if (deviceToken == null) { + _logger.warning('No device token available for test notification'); + return false; + } + + final success = await _backendClient.sendTestNotification( + deviceToken: deviceToken, + ); + + if (success) { + _logger.info('Test notification sent successfully'); + } else { + _logger.warning('Failed to send test notification'); + } + + return success; + } catch (e) { + _logger.severe('Error sending test notification: $e'); + return false; + } + } + + /// Handle bellDelay change with debounce + /// Waits 3 seconds after the last change before sending update to backend + /// If value changes during the wait, reschedules the update with the new value + /// Also saves the setting per-user immediately + static void onBellDelayChanged(double newValue) { + if (!Platform.isIOS || !_isInitialized) return; + + _logger.info( + 'BellDelay changed to $newValue minutes, scheduling debounced update', + ); + + _setUserBellDelay(newValue); + + _bellDelayDebounceTimer?.cancel(); + + _pendingBellDelay = newValue; + + _bellDelayDebounceTimer = Timer(_bellDelayDebounceInterval, () async { + await _sendBellDelayUpdate(); + }); + } + + /// Internal function to send bellDelay update to backend + static Future _sendBellDelayUpdate() async { + if (_pendingBellDelay == null) return; + + final bellDelayToSend = _pendingBellDelay!; + + if (_lastSentBellDelay == bellDelayToSend) { + _logger.info( + 'BellDelay $bellDelayToSend already sent to backend, skipping', + ); + _pendingBellDelay = null; + return; + } + + try { + final deviceToken = await _getOrWaitDeviceToken(); + if (deviceToken == null) { + _logger.warning('No device token available to update bellDelay'); + return; + } + + _logger.info( + 'Sending bellDelay update to backend: $bellDelayToSend minutes', + ); + + final success = await _backendClient.updateBellDelay( + deviceToken: deviceToken, + bellDelay: bellDelayToSend, + ); + + if (success) { + _lastSentBellDelay = bellDelayToSend; + _logger.info('BellDelay updated successfully in backend'); + + if (_pendingBellDelay != bellDelayToSend) { + _logger.info( + 'BellDelay changed to $_pendingBellDelay during update, scheduling another update', + ); + _bellDelayDebounceTimer?.cancel(); + _bellDelayDebounceTimer = Timer(_bellDelayDebounceInterval, () async { + await _sendBellDelayUpdate(); + }); + } else { + _pendingBellDelay = null; + } + } else { + _logger.warning('Failed to update bellDelay in backend'); + } + } catch (e) { + _logger.severe('Error updating bellDelay: $e'); + } + } + + /// Handle morning notification enabled change with debounce + /// Waits 3 seconds after the last change before sending update to backend + /// Also saves the setting per-user immediately + static void onMorningNotificationEnabledChanged(bool newValue) { + if (!Platform.isIOS || !_isInitialized) return; + + _logger.info( + 'Morning notification enabled changed to $newValue, scheduling debounced update', + ); + + _setUserMorningNotificationEnabled(newValue); + + _morningNotificationDebounceTimer?.cancel(); + + _pendingMorningNotificationEnabled = newValue; + + _morningNotificationDebounceTimer = Timer( + _morningNotificationDebounceInterval, + () async { + await _sendMorningNotificationUpdate(); + }, + ); + } + + /// Handle morning notification time change with debounce + /// Waits 3 seconds after the last change before sending update to backend + /// Also saves the setting per-user immediately + static void onMorningNotificationTimeChanged(double newValue) { + if (!Platform.isIOS || !_isInitialized) return; + + _logger.info( + 'Morning notification time changed to $newValue minutes, scheduling debounced update', + ); + + _setUserMorningNotificationTime(newValue.toInt()); + + _morningNotificationDebounceTimer?.cancel(); + + _pendingMorningNotificationTime = newValue; + + _morningNotificationDebounceTimer = Timer( + _morningNotificationDebounceInterval, + () async { + await _sendMorningNotificationUpdate(); + }, + ); + } + + /// Internal function to send morning notification settings update to backend + static Future _sendMorningNotificationUpdate() async { + final enabledToSend = + _pendingMorningNotificationEnabled ?? + _getCurrentMorningNotificationEnabled(); + final timeToSend = + _pendingMorningNotificationTime ?? _getCurrentMorningNotificationTime(); + + if (_lastSentMorningNotificationEnabled == enabledToSend && + _lastSentMorningNotificationTime == timeToSend) { + _logger.info( + 'Morning notification settings already sent to backend, skipping', + ); + _pendingMorningNotificationEnabled = null; + _pendingMorningNotificationTime = null; + return; + } + + try { + final deviceToken = await _getOrWaitDeviceToken(); + if (deviceToken == null) { + _logger.warning( + 'No device token available to update morning notification settings', + ); + return; + } + + _logger.info( + 'Sending morning notification settings update to backend: enabled=$enabledToSend, time=$timeToSend minutes', + ); + + final success = await _backendClient.updateMorningNotificationSettings( + deviceToken: deviceToken, + morningNotificationEnabled: enabledToSend, + morningNotificationTime: timeToSend?.toInt(), + ); + + if (success) { + final wasDisabled = _lastSentMorningNotificationEnabled == false; + final isNowEnabled = enabledToSend == true; + + _lastSentMorningNotificationEnabled = enabledToSend; + _lastSentMorningNotificationTime = timeToSend; + _logger.info( + 'Morning notification settings updated successfully in backend', + ); + + if (wasDisabled && isNowEnabled) { + _logger.info( + 'Morning notifications re-enabled, fetching timetable to recreate notifications', + ); + try { + final client = initData.client!; + final settingsStore = initData.settings; + + final studentResp = await client.getStudent(); + final studentName = studentResp.name; + + await checkAndUpdateTimetable( + client: client, + studentName: studentName, + settingsStore: settingsStore, + forceUpdate: true, + ); + _logger.info( + 'Timetable fetch completed after re-enabling notifications', + ); + } catch (e) { + _logger.severe( + 'Error fetching timetable after re-enabling notifications: $e', + ); + } + } + + final currentEnabled = + _pendingMorningNotificationEnabled ?? + _getCurrentMorningNotificationEnabled(); + final currentTime = + _pendingMorningNotificationTime ?? + _getCurrentMorningNotificationTime(); + + if (_lastSentMorningNotificationEnabled != currentEnabled || + _lastSentMorningNotificationTime != currentTime) { + _logger.info( + 'Morning notification settings changed during update, scheduling another update', + ); + _morningNotificationDebounceTimer?.cancel(); + _morningNotificationDebounceTimer = Timer( + _morningNotificationDebounceInterval, + () async { + await _sendMorningNotificationUpdate(); + }, + ); + } else { + _pendingMorningNotificationEnabled = null; + _pendingMorningNotificationTime = null; + } + } else { + _logger.warning( + 'Failed to update morning notification settings in backend', + ); + } + } catch (e) { + _logger.severe('Error updating morning notification settings: $e'); + } + } + + /// Get current morning notification enabled value from settings + static bool? _getCurrentMorningNotificationEnabled() { + try { + if (!initDone) { + return null; + } + return Settings.morningNotificationEnabled.value; + } catch (e) { + _logger.warning('Error getting current morning notification enabled: $e'); + return null; + } + } + + /// Get current morning notification time value from settings + static double? _getCurrentMorningNotificationTime() { + try { + if (!initDone) { + return null; + } + return Settings.morningNotificationTime.value; + } catch (e) { + _logger.warning('Error getting current morning notification time: $e'); + return null; + } + } + + /// Global break searcher result + static Future<_GlobalSearchResult> _globalBreakSearcher({ + required KretaClient client, + required DateTime searchStartDate, + }) async { + List allLessons = []; + Lesson? lastBreakDay; + Lesson? firstSchoolDayAfterBreak; + bool tokenExpired = false; + + DateTime currentSearchDate = searchStartDate; + int weeksSearched = 0; + const maxWeeks = 26; + + _logger.info( + '[GlobalBreakSearcher] Starting search from ${currentSearchDate.toString().split(' ')[0]}', + ); + + while (weeksSearched < maxWeeks) { + final weekStart = currentSearchDate; + final weekEnd = weekStart.add(const Duration(days: 6)); + + _logger.info( + '[GlobalBreakSearcher] Fetching week ${weeksSearched + 1}: ${weekStart.toString().split(' ')[0]} - ${weekEnd.toString().split(' ')[0]}', + ); + + try { + final fetched = await _lessonsBetween(client, weekStart, weekEnd); + + if (fetched.isNotEmpty) { + final breakEvents = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + final name = lesson.name.toLowerCase(); + return uid.contains('tanevrendjeesemeny') && + !name.contains('tanítási nap') && + (name.contains('pihenőnap') || + name.contains('munkaszüneti') || + name.contains('ünnepnap') || + name.contains('tanítás nélküli') || + name.contains('nem órarendi nap')); + }).toList(); + + final schoolLessons = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + return uid.contains('orarendiora') || + uid.contains('tanitasiora') || + uid.contains('uresora'); + }).toList(); + + allLessons.addAll(fetched); + + if (breakEvents.isNotEmpty) { + breakEvents.sort((a, b) => a.start.compareTo(b.start)); + lastBreakDay = breakEvents.last; + _logger.info( + '[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in week ${weeksSearched + 1}, last: $lastBreakDay on $lastBreakDay', + ); + } else if (schoolLessons.isNotEmpty) { + schoolLessons.sort((a, b) => a.start.compareTo(b.start)); + firstSchoolDayAfterBreak = schoolLessons.first; + _logger.info( + '[GlobalBreakSearcher] Found first school day after break: $firstSchoolDayAfterBreak on $firstSchoolDayAfterBreak', + ); + break; + } else { + _logger.info( + '[GlobalBreakSearcher] Week ${weeksSearched + 1} is empty, continuing search...', + ); + } + } + } catch (e) { + final isTokenError = + e.toString().contains('TokenExpiredException') || + e.toString().contains('InvalidGrantException'); + + if (isTokenError) { + tokenExpired = true; + _logger.warning( + '[GlobalBreakSearcher] Token expired during week ${weeksSearched + 1}, falling back to cache', + ); + } else { + _logger.warning( + '[GlobalBreakSearcher] Error fetching week ${weeksSearched + 1}: $e', + ); + } + + try { + final fetched = await _lessonsBetween(client, weekStart, weekEnd); + + if (fetched.isNotEmpty) { + final weekLessons = fetched; + _logger.info( + '[GlobalBreakSearcher] Loaded ${weekLessons.length} lessons from cache for week ${weeksSearched + 1}', + ); + + final breakEvents = weekLessons.where((lesson) { + final uid = lesson.uid.toLowerCase(); + final name = lesson.name.toLowerCase(); + return uid.contains('tanevrendjeesemeny') && + !name.contains('tanítási nap') && + (name.contains('pihenőnap') || + name.contains('munkaszüneti') || + name.contains('ünnepnap') || + name.contains('tanítás nélküli') || + name.contains('nem órarendi nap')); + }).toList(); + + final schoolLessons = fetched.where((lesson) { + final uid = lesson.uid.toLowerCase(); + return uid.contains('orarendiora') || + uid.contains('tanitasiora') || + uid.contains('uresora'); + }).toList(); + + allLessons.addAll(fetched); + + if (breakEvents.isNotEmpty) { + breakEvents.sort((a, b) => a.start.compareTo(b.start)); + lastBreakDay = breakEvents.last; + _logger.info( + '[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in cached week ${weeksSearched + 1}, last: $lastBreakDay on $lastBreakDay', + ); + } else if (schoolLessons.isNotEmpty) { + schoolLessons.sort((a, b) => a.start.compareTo(b.start)); + firstSchoolDayAfterBreak = schoolLessons.first; + _logger.info( + '[GlobalBreakSearcher] Found first school day after break in cache: $firstSchoolDayAfterBreak on $firstSchoolDayAfterBreak', + ); + break; + } + } + } catch (cacheError) { + _logger.warning( + '[GlobalBreakSearcher] Cache fallback also failed for week ${weeksSearched + 1}: $cacheError', + ); + } + } + + currentSearchDate = currentSearchDate.add(const Duration(days: 7)); + weeksSearched++; + + if (lastBreakDay != null && firstSchoolDayAfterBreak != null) { + break; + } + } + + if (weeksSearched >= maxWeeks) { + _logger.warning( + '[GlobalBreakSearcher] Reached maximum search limit ($maxWeeks weeks)', + ); + } + + _logger.info( + '[GlobalBreakSearcher] Search completed: ${allLessons.length} lessons found, last break: ${lastBreakDay?.date.split('T')[0] ?? 'none'}, first school day: ${firstSchoolDayAfterBreak?.date.split('T')[0] ?? 'none'}, tokenExpired: $tokenExpired', + ); + + return _GlobalSearchResult( + allLessons: allLessons, + lastBreakDay: lastBreakDay, + firstSchoolDayAfterBreak: firstSchoolDayAfterBreak, + tokenExpired: tokenExpired, + ); + } +} + +/// Result of global break searcher +class _GlobalSearchResult { + final List allLessons; + final Lesson? lastBreakDay; + final Lesson? firstSchoolDayAfterBreak; + final bool tokenExpired; + + _GlobalSearchResult({ + required this.allLessons, + this.lastBreakDay, + this.firstSchoolDayAfterBreak, + this.tokenExpired = false, + }); +} diff --git a/firka/lib/services/local_notification_service.dart b/firka/lib/services/local_notification_service.dart index 69803959..da15a654 100644 --- a/firka/lib/services/local_notification_service.dart +++ b/firka/lib/services/local_notification_service.dart @@ -21,8 +21,9 @@ class LocalNotificationService { if (_initialized) return; const androidInit = AndroidInitializationSettings('ic_notification'); + const iosInit = DarwinInitializationSettings(); await _plugin.initialize( - const InitializationSettings(android: androidInit), + const InitializationSettings(android: androidInit, iOS: iosInit), ); const channel = AndroidNotificationChannel( @@ -69,6 +70,7 @@ class LocalNotificationService { importance: Importance.defaultImportance, priority: Priority.defaultPriority, ), + iOS: DarwinNotificationDetails(), ), ); } diff --git a/firka/lib/services/watch_sync_helper.dart b/firka/lib/services/watch_sync_helper.dart new file mode 100644 index 00000000..be569dbf --- /dev/null +++ b/firka/lib/services/watch_sync_helper.dart @@ -0,0 +1,1102 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:firka_common/data/database.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:isar_community/isar.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:watch_connectivity/watch_connectivity.dart'; + +import 'package:firka/app/app_state.dart'; +import 'package:firka/services/wear_sync_cache.dart'; +import 'package:firka/api/client/kreta_client.dart'; +import 'package:firka_common/data/models/token_model.dart'; + +/// Helper class for Watch ↔ iPhone token sync (iOS) and Wear OS sync (Android). +class WatchSyncHelper { + static const _watchChannel = MethodChannel('app.firka/watch_sync'); + static const _wearSyncChannel = MethodChannel('app.firka/wear_sync'); + static WatchConnectivity? _androidWatchConnectivity; + static WatchConnectivity get _watchConnectivityAndroid { + _androidWatchConnectivity ??= WatchConnectivity(); + return _androidWatchConnectivity!; + } + + static const _leaseOwnerIPhone = 'iphone'; + static bool _initialized = false; + static bool _watchAppInstalledCache = false; + static DateTime? _lastWatchInstallCheckAt; + static const Duration _watchInstallCheckCooldown = Duration(seconds: 10); + static const Duration _tokenUsableSkew = Duration(seconds: 60); + static const Duration _leasePollInterval = Duration(milliseconds: 250); + static const Duration _iPhoneRefreshLeaseTtl = Duration(seconds: 120); + static const Duration _watchRefreshLeaseMaxWait = Duration(seconds: 150); + static const String _iosFreshInstallHandledKey = + 'ios_fresh_install_cleanup_done_v1'; + + /// Invoke method with timeout to prevent infinite blocking + static Future _invokeMethodWithTimeout( + String method, [ + dynamic arguments, + Duration timeout = const Duration(seconds: 10), + ]) async { + try { + return await _watchChannel + .invokeMethod(method, arguments) + .timeout( + timeout, + onTimeout: () { + debugPrint( + '[WatchSync] Timeout calling $method after ${timeout.inSeconds}s', + ); + return null; + }, + ); + } catch (e) { + debugPrint('[WatchSync] Error calling $method: $e'); + return null; + } + } + + static int? _asInt(dynamic value) { + if (value is int) return value; + if (value is double) return value.toInt(); + if (value is String) return int.tryParse(value); + return null; + } + + static int? _extractTokenVersionFromIdToken(String? idToken) { + if (idToken == null || idToken.isEmpty) return null; + final parts = idToken.split('.'); + if (parts.length < 2) return null; + + try { + final payloadJson = utf8.decode( + base64Url.decode(base64Url.normalize(parts[1])), + ); + final payload = jsonDecode(payloadJson); + if (payload is! Map) return null; + final iatSeconds = _asInt(payload['iat']); + if (iatSeconds == null || iatSeconds <= 0) return null; + return iatSeconds * 1000; + } catch (_) { + return null; + } + } + + static int? _resolveIncomingTokenVersion(Map tokenData) { + return _asInt(tokenData['tokenVersion']) ?? + _extractTokenVersionFromIdToken(tokenData['idToken'] as String?); + } + + static int? _resolveTokenVersionForModel(TokenModel token) { + final tokenVersion = token.tokenVersion; + if (tokenVersion != null && tokenVersion > 0) { + return tokenVersion; + } + return _extractTokenVersionFromIdToken(token.idToken); + } + + static int? _resolveUpdatedAtForModel(TokenModel token) { + final updatedAtMs = token.updatedAtMs; + if (updatedAtMs != null && updatedAtMs > 0) { + return updatedAtMs; + } + return null; + } + + static bool _isIncomingTokenNewerThanCurrent({ + required DateTime incomingExpiry, + required String? incomingIdToken, + required String? incomingRefreshToken, + required int? incomingTokenVersion, + required int? incomingUpdatedAtMs, + required TokenModel currentToken, + }) { + final currentExpiry = currentToken.expiryDate; + + final incomingVersion = + incomingTokenVersion ?? + _extractTokenVersionFromIdToken(incomingIdToken); + final currentVersion = _resolveTokenVersionForModel(currentToken); + final currentUpdatedAtMs = _resolveUpdatedAtForModel(currentToken); + + if (incomingVersion != null && + currentVersion != null && + incomingVersion != currentVersion) { + return incomingVersion > currentVersion; + } + + if (incomingExpiry.isAfter(currentExpiry)) { + return true; + } + if (incomingExpiry.isBefore(currentExpiry)) { + return false; + } + + if (incomingVersion != null && currentVersion == null) { + return true; + } + if (incomingVersion == null && currentVersion != null) { + return false; + } + + if (incomingUpdatedAtMs != null && + currentUpdatedAtMs != null && + incomingUpdatedAtMs != currentUpdatedAtMs) { + return incomingUpdatedAtMs > currentUpdatedAtMs; + } + if (incomingUpdatedAtMs != null && currentUpdatedAtMs == null) { + return true; + } + if (incomingUpdatedAtMs == null && currentUpdatedAtMs != null) { + return false; + } + + final currentRefresh = currentToken.refreshToken; + if (incomingRefreshToken != null && + incomingRefreshToken != currentRefresh) { + if (incomingIdToken != null && incomingIdToken != currentToken.idToken) { + return true; + } + return false; + } + + return false; + } + + static bool _isAccessTokenUsable( + DateTime? expiryDate, { + Duration skew = _tokenUsableSkew, + }) { + if (expiryDate == null) return false; + return expiryDate.isAfter(DateTime.now().add(skew)); + } + + static Map _buildTokenSyncPayload( + TokenModel token, { + bool includeSentAt = false, + }) { + final nowMs = DateTime.now().millisecondsSinceEpoch; + final tokenVersion = _resolveTokenVersionForModel(token) ?? nowMs; + final updatedAtMs = (token.updatedAtMs != null && token.updatedAtMs! > 0) + ? token.updatedAtMs! + : nowMs; + final payload = { + 'studentId': token.username, + 'studentIdNorm': token.key, + 'iss': token.iss, + 'idToken': token.idToken, + 'accessToken': token.accessToken, + 'refreshToken': token.refreshToken, + 'expiryDate': token.expiryDate.millisecondsSinceEpoch, + 'tokenVersion': tokenVersion, + 'updatedAtMs': updatedAtMs, + }; + if (includeSentAt) { + payload['sentAtMs'] = nowMs; + } + return payload; + } + + static void initialize() { + if (!Platform.isIOS) return; + if (_initialized) return; + _initialized = true; + + _watchChannel.setMethodCallHandler(_handleMethodCall); + debugPrint('[WatchSync] Handler initialized'); + unawaited( + _invokeMethodWithTimeout( + 'watchSyncReady', + null, + const Duration(seconds: 2), + ), + ); + } + + static Future isWatchAppInstalled({bool forceRefresh = false}) async { + if (!Platform.isIOS) return false; + if (_watchAppInstalledCache && !forceRefresh) return true; + + final now = DateTime.now(); + if (!forceRefresh && + _lastWatchInstallCheckAt != null && + now.difference(_lastWatchInstallCheckAt!) < + _watchInstallCheckCooldown) { + return _watchAppInstalledCache; + } + _lastWatchInstallCheckAt = now; + + final result = await _invokeMethodWithTimeout( + 'isWatchAppInstalled', + null, + const Duration(seconds: 2), + ); + _watchAppInstalledCache = result == true; + return _watchAppInstalledCache; + } + + static Future isWatchReachable({ + bool forceRefreshInstall = false, + }) async { + if (!Platform.isIOS) return false; + + final watchInstalled = await isWatchAppInstalled( + forceRefresh: forceRefreshInstall, + ); + if (!watchInstalled) return false; + + final result = await _invokeMethodWithTimeout( + 'isWatchReachable', + null, + const Duration(seconds: 2), + ); + return result == true; + } + + static Future clearICloudToken({bool notifyWatch = false}) async { + if (!Platform.isIOS) return; + await _invokeMethodWithTimeout( + 'clearICloudToken', + null, + const Duration(seconds: 5), + ); + if (notifyWatch) { + await notifyWatchForceLogout(); + } + } + + static Future notifyWatchForceLogout() async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(forceRefresh: true); + if (!watchInstalled) return; + await _invokeMethodWithTimeout( + 'sendLogoutToWatch', + null, + const Duration(seconds: 5), + ); + } + + static Future waitForWatchRefreshLease({ + required int studentIdNorm, + Duration maxWait = _watchRefreshLeaseMaxWait, + }) async { + if (!Platform.isIOS) return true; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return true; + + final timeout = maxWait + const Duration(seconds: 5); + final result = + await _invokeMethodWithTimeout('waitForPeerRefreshLease', { + 'owner': _leaseOwnerIPhone, + 'studentIdNorm': studentIdNorm, + 'maxWaitMs': maxWait.inMilliseconds, + 'pollIntervalMs': _leasePollInterval.inMilliseconds, + }, timeout); + + if (result is! Map) { + debugPrint('[WatchSync] Lease wait returned invalid response: $result'); + return true; + } + + final ready = result['ready'] == true; + final status = result['status']; + final waitedMs = result['waitedMs']; + final leaseChanged = result['leaseChanged'] == true; + debugPrint( + '[WatchSync] Lease wait status=$status ready=$ready waitedMs=$waitedMs leaseChanged=$leaseChanged', + ); + return ready; + } + + static Future acquireIPhoneRefreshLease({ + required int studentIdNorm, + Duration ttl = _iPhoneRefreshLeaseTtl, + }) async { + if (!Platform.isIOS) return null; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return null; + + final result = + await _invokeMethodWithTimeout('acquireRefreshLease', { + 'owner': _leaseOwnerIPhone, + 'studentIdNorm': studentIdNorm, + 'ttlMs': ttl.inMilliseconds, + }, const Duration(seconds: 5)); + + if (result is! Map) { + debugPrint( + '[WatchSync] Lease acquire returned invalid response: $result', + ); + return null; + } + if (result['skipped'] == true) { + return null; + } + final operationId = result['operationId'] as String?; + if (operationId == null || operationId.isEmpty) { + debugPrint('[WatchSync] Lease acquire response missing operationId'); + return null; + } + return operationId; + } + + static Future releaseIPhoneRefreshLease({ + required int studentIdNorm, + required String operationId, + }) async { + if (!Platform.isIOS) return; + await _invokeMethodWithTimeout('releaseRefreshLease', { + 'owner': _leaseOwnerIPhone, + 'studentIdNorm': studentIdNorm, + 'operationId': operationId, + }, const Duration(seconds: 5)); + } + + static Future clearRefreshLeaseForAccount(int studentIdNorm) async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return; + await _invokeMethodWithTimeout('clearRefreshLeaseForAccount', { + 'studentIdNorm': studentIdNorm, + }, const Duration(seconds: 5)); + } + + static Future clearAllRefreshLeases() async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return; + await _invokeMethodWithTimeout( + 'clearAllRefreshLeases', + null, + const Duration(seconds: 5), + ); + } + + static Future clearSharedLanguageState() async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return; + await _invokeMethodWithTimeout( + 'clearSharedLanguageState', + null, + const Duration(seconds: 5), + ); + } + + static Future runFreshInstallCleanupIfNeeded({ + required Isar isar, + }) async { + if (!Platform.isIOS) return false; + + final prefs = await SharedPreferences.getInstance(); + final cleanupHandled = prefs.getBool(_iosFreshInstallHandledKey) ?? false; + if (cleanupHandled) { + return false; + } + + debugPrint( + '[WatchSync] Fresh iOS install detected, clearing iCloud and local auth state', + ); + await clearICloudToken(notifyWatch: true); + await clearAllRefreshLeases(); + + await isar.writeTxn(() async { + await isar.tokenModels.clear(); + }); + + if (initDone) initData.toastCubit.clear(); + + await prefs.setBool(_iosFreshInstallHandledKey, true); + return true; + } + + static Future _handleMethodCall(MethodCall call) async { + switch (call.method) { + case 'getTokenForWatch': + return _getTokenForWatch(); + case 'getLanguageForWatch': + return _getLanguageForWatch(); + case 'watchAppInstalled': + debugPrint('[WatchSync] Watch app installed detected'); + _watchAppInstalledCache = true; + _lastWatchInstallCheckAt = DateTime.now(); + return null; + case 'onTokenFromWatch': + debugPrint('[WatchSync] Token received from Watch'); + return await _processTokenFromWatch(call.arguments); + case 'onTokenRecoveredFromiCloud': + debugPrint( + '[WatchSync] Token recovered from iCloud notification received', + ); + await _handleTokenRecoveredFromiCloud(); + return null; + case 'onWatchMessage': + _handleWatchMessage(call.arguments); + return null; + default: + return null; + } + } + + /// Callback for Watch pairing message events. + /// Set by main.dart to handle "ping" messages for Watch pairing flow. + static void Function(Map message)? onWatchMessage; + + static void _handleWatchMessage(dynamic arguments) { + if (arguments == null) return; + try { + final Map message; + if (arguments is Map) { + message = arguments; + } else if (arguments is Map) { + message = Map.from(arguments); + } else { + debugPrint( + '[WatchSync] onWatchMessage: unexpected type ${arguments.runtimeType}', + ); + return; + } + debugPrint('[WatchSync] Received Watch message: ${message["id"]}'); + onWatchMessage?.call(message); + } catch (e) { + debugPrint('[WatchSync] Error handling Watch message: $e'); + } + } + + /// Called when iOS receives a fresh token from iCloud (e.g., Watch refreshed) + /// This clears the reauth flag if it was set, since we now have a valid token + static Future _handleTokenRecoveredFromiCloud() async { + if (!initDone) { + debugPrint( + '[WatchSync] Cannot handle iCloud recovery: app not initialized', + ); + return; + } + + try { + final recovered = await checkAndRecoverFromiCloud( + isar: initData.isar, + client: initData.client, + ); + + if (recovered) { + debugPrint( + '[WatchSync] Token recovered from iCloud, reauth flag cleared', + ); + } else { + final token = initData.client!.cache.token; + final expiryDate = token.expiryDate; + if (expiryDate.isAfter(DateTime.now())) { + if (initDone) initData.toastCubit.clear(); + debugPrint( + '[WatchSync] Cleared reauth flag after iCloud notification (token is valid)', + ); + } + } + } catch (e) { + debugPrint('[WatchSync] Failed to handle iCloud recovery: $e'); + } + } + + static Map? _getTokenForWatch() { + if (!initDone) { + debugPrint('[WatchSync] No token available'); + return {'error': 'no_token'}; + } + + final token = initData.client!.cache.token; + + if (initData.client!.needsReauth) { + debugPrint('[WatchSync] iPhone needs reauth'); + return {'error': 'needsReauth'}; + } + + if (!_isAccessTokenUsable(token.expiryDate, skew: const Duration())) { + debugPrint( + '[WatchSync] Active iPhone token access is expired, forwarding token to Watch for recovery', + ); + } + + final tokenData = _buildTokenSyncPayload(token, includeSentAt: true); + + debugPrint('[WatchSync] Returning token for Watch'); + return tokenData; + } + + /// Send a fire-and-forget message to Watch via WatchSessionManager (iOS) or watch_connectivity (Android). + /// On Android the payload is sent as a JSON string for reliable transport. + static Future sendMessageToWatch(Map message) async { + if (Platform.isAndroid) { + await _watchConnectivityAndroid.sendMessage({ + 'data': jsonEncode(message), + }); + return; + } + if (!Platform.isIOS) return; + await _invokeMethodWithTimeout('sendMessageToWatch', message); + } + + /// Starts the Wear sync foreground service (Android only). Call after writing initial cache. + /// [appDirPath] is the application documents directory path (for the background isolate). + static Future startWearSyncService( + String cachePath, + String appDirPath, + ) async { + if (!Platform.isAndroid) return; + await _wearSyncChannel.invokeMethod( + 'startWearSyncService', + {'cachePath': cachePath, 'appDirPath': appDirPath}, + ); + } + + /// Builds fresh sync payload, writes cache, and starts the Wear sync service (Android only). + /// Use when enabling Wear OS support or on app launch when support is already enabled. + static Future startWearSyncServiceWithFreshCache( + KretaClient client, + String appDirPath, + ) async { + if (!Platform.isAndroid) return; + final payload = await buildWearSyncPayload(client); + if (payload == null) return; + final path = await getWearSyncCachePath(); + await writeWearSyncCache(path, payload); + await startWearSyncService(path, appDirPath); + } + + /// Sets the method call handler for getLocalizedString (Android). Call once when initData is ready. + static void setWearSyncMethodCallHandler() { + if (!Platform.isAndroid) return; + _wearSyncChannel.setMethodCallHandler((MethodCall call) async { + if (call.method == 'getLocalizedString') { + final key = call.arguments as String?; + return getLocalizedString(key); + } + return null; + }); + } + + /// Returns the localized string for [key] from l10n. Used by Kotlin for notification title/text. + static String? getLocalizedString(String? key) { + if (key == null || !initDone) return null; + switch (key) { + case 'wearSyncNotificationTitle': + return initData.l10n.wearSyncNotificationTitle; + case 'wearSyncNotificationText': + return initData.l10n.wearSyncNotificationText; + default: + return null; + } + } + + /// Stops the Wear sync foreground service (Android only). + static Future stopWearSyncService() async { + if (!Platform.isAndroid) return; + await _wearSyncChannel.invokeMethod('stopWearSyncService'); + } + + /// Runs sync in foreground: fetches timetable + grades, writes cache, sends sync_data to watch. + /// Used when app is in foreground and watch sends request_sync (Android) or equivalent. + static Future runWearSyncInForeground(KretaClient client) async { + final payload = await buildWearSyncPayload(client); + if (payload == null) return; + final path = await getWearSyncCachePath(); + await writeWearSyncCache(path, payload); + await sendMessageToWatch({'id': 'sync_data', ...payload}); + } + + /// Stream of messages from the watch (Android: watch_connectivity). Use for request_sync etc. + static Stream> get watchMessageStream { + if (!Platform.isAndroid) return const Stream.empty(); + return _watchConnectivityAndroid.messageStream.map((m) { + final map = Map.from(m); + final data = map['data']; + if (data is String) { + return jsonDecode(data) as Map; + } + return map; + }); + } + + static Future sendTokenToWatch() async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) return; + + final tokenData = _getTokenForWatch(); + if (tokenData == null) return; + + await _invokeMethodWithTimeout('sendTokenToWatch', tokenData); + debugPrint('[WatchSync] Token send requested to Watch (async delivery)'); + } + + /// Sends a specific token directly to Watch. + /// Useful during app initialization before global init state is fully ready. + static Future sendTokenModelToWatch( + TokenModel token, { + bool allowExpiredAccessToken = false, + }) async { + if (!Platform.isIOS) return; + await _sendTokenToWatchInternal( + token, + allowExpiredAccessToken: allowExpiredAccessToken, + ); + } + + static Future> _processTokenFromWatch( + dynamic arguments, + ) async { + if (!initDone) { + debugPrint('[WatchSync] Cannot process Watch token: app not initialized'); + return {'success': false, 'error': 'not_initialized'}; + } + + try { + final tokenData = arguments as Map; + + final watchExpiry = tokenData['expiryDate'] as int?; + if (watchExpiry == null) { + debugPrint('[WatchSync] Watch token has no expiry'); + return {'success': false, 'error': 'no_expiry'}; + } + + final watchStudentIdNorm = tokenData['studentIdNorm'] as int?; + if (watchStudentIdNorm == null) { + debugPrint('[WatchSync] Watch token has no studentIdNorm'); + return {'success': false, 'error': 'no_student_id_norm'}; + } + + final expectedStudentIdNorm = initData.client!.cache.token.key; + final currentToken = initData.client!.cache.token; + + final watchExpiryDate = DateTime.fromMillisecondsSinceEpoch(watchExpiry); + if (!_isAccessTokenUsable(watchExpiryDate, skew: const Duration())) { + debugPrint( + '[WatchSync] Rejecting expired token from Watch, expiry: $watchExpiryDate', + ); + return {'success': false, 'error': 'expired_token'}; + } + final watchTokenVersion = _resolveIncomingTokenVersion(tokenData); + final watchUpdatedAtMs = _asInt(tokenData['updatedAtMs']); + final watchIdToken = tokenData['idToken'] as String?; + final watchRefreshToken = tokenData['refreshToken'] as String?; + + final isForActiveAccount = watchStudentIdNorm == expectedStudentIdNorm; + if (isForActiveAccount && currentToken.key == watchStudentIdNorm) { + if (!_isIncomingTokenNewerThanCurrent( + incomingExpiry: watchExpiryDate, + incomingIdToken: watchIdToken, + incomingRefreshToken: watchRefreshToken, + incomingTokenVersion: watchTokenVersion, + incomingUpdatedAtMs: watchUpdatedAtMs, + currentToken: currentToken, + )) { + debugPrint( + '[WatchSync] Ignoring stale token from Watch for active account. Incoming expiry: $watchExpiryDate, incomingVersion: $watchTokenVersion', + ); + return {'success': false, 'error': 'stale_token'}; + } + } + + debugPrint( + '[WatchSync] Accepting token from Watch, expiry: $watchExpiryDate (expired: ${watchExpiryDate.isBefore(DateTime.now())})', + ); + + final newToken = TokenModel.fromValues( + watchStudentIdNorm, + tokenData['studentId'] as String, + tokenData['iss'] as String, + tokenData['idToken'] as String, + tokenData['accessToken'] as String, + tokenData['refreshToken'] as String, + watchExpiry, + tokenVersion: watchTokenVersion, + updatedAtMs: watchUpdatedAtMs ?? DateTime.now().millisecondsSinceEpoch, + ); + + await initData.isar.writeTxn(() async { + await initData.isar.tokenModels.put(newToken); + }); + + if (isForActiveAccount) { + initData.client!.cache.token = newToken; + if (initDone) initData.toastCubit.clear(); + } else { + debugPrint( + '[WatchSync] Stored token for inactive account ($watchStudentIdNorm), active is $expectedStudentIdNorm', + ); + } + + debugPrint('[WatchSync] Token from Watch saved successfully'); + return {'success': true}; + } catch (e) { + debugPrint('[WatchSync] Failed to process Watch token: $e'); + return {'success': false, 'error': e.toString()}; + } + } + + static Future _sendTokenToWatchInternal( + TokenModel token, { + bool allowExpiredAccessToken = false, + }) async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) { + debugPrint('[WatchSync] No paired Watch app, skipping token send'); + return; + } + + final accessExpired = !_isAccessTokenUsable( + token.expiryDate, + skew: const Duration(), + ); + if (accessExpired && !allowExpiredAccessToken) { + debugPrint('[WatchSync] Token expired, not sending to Watch'); + return; + } + if (accessExpired && allowExpiredAccessToken) { + debugPrint( + '[WatchSync] Sending expired-access token to Watch for account-switch recovery', + ); + } + + final tokenData = _buildTokenSyncPayload(token, includeSentAt: true); + + await _invokeMethodWithTimeout('sendTokenToWatch', tokenData); + debugPrint('[WatchSync] iPhone token sent to Watch (or timeout)'); + } + + static String? _getLanguageForWatch() { + if (!initDone) { + debugPrint( + '[WatchSync] App not initialized yet, language unavailable for Watch', + ); + return null; + } + + final languageCode = initData.l10n.localeName; + debugPrint('[WatchSync] Returning language for Watch: $languageCode'); + return languageCode; + } + + static Future sendLanguageToWatch() async { + if (!Platform.isIOS) return; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) { + debugPrint('[WatchSync] No paired Watch app, skipping language publish'); + return; + } + + final languageCode = _getLanguageForWatch(); + if (languageCode == null) return; + + await _invokeMethodWithTimeout('sendLanguageToWatch', languageCode); + debugPrint( + '[WatchSync] Language sent to Watch: $languageCode (or timeout)', + ); + } + + /// Check iCloud for a fresher token and update local storage if found. + /// This should be called on app startup BEFORE any API calls. + /// Returns true if a fresher token was found and applied. + static Future checkAndRecoverFromiCloud({ + Isar? isar, + List? tokens, + KretaClient? client, + bool allowExpiredAccessToken = false, + }) async { + if (!Platform.isIOS) return false; + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) { + return false; + } + + final effectiveIsar = isar ?? (initDone ? initData.isar : null); + final effectiveClient = client ?? (initDone ? initData.client : null); + + if (effectiveIsar == null) { + debugPrint('[WatchSync] Cannot check iCloud: no isar available'); + return false; + } + + try { + debugPrint('[WatchSync] Checking iCloud for fresher token...'); + final result = await _invokeMethodWithTimeout( + 'checkiCloudToken', + null, + const Duration(seconds: 5), + ); + + if (result == null) { + debugPrint('[WatchSync] No response from native (timeout or error)'); + return false; + } + + final tokenData = result as Map; + if (tokenData.containsKey('error')) { + debugPrint('[WatchSync] iCloud check returned: ${tokenData['error']}'); + return false; + } + + final expectedStudentIdNorm = initData.client!.cache.token.key; + + final iCloudStudentIdNorm = tokenData['studentIdNorm'] as int?; + if (iCloudStudentIdNorm != expectedStudentIdNorm) { + debugPrint( + '[WatchSync] iCloud token belongs to different account ($iCloudStudentIdNorm), active is $expectedStudentIdNorm - ignoring', + ); + return false; + } + + final iCloudExpiry = tokenData['expiryDate'] as int?; + if (iCloudExpiry == null) { + debugPrint('[WatchSync] iCloud token has no expiry'); + return false; + } + + final iCloudExpiryDate = DateTime.fromMillisecondsSinceEpoch( + iCloudExpiry, + ); + final iCloudAccessExpired = !_isAccessTokenUsable( + iCloudExpiryDate, + skew: const Duration(), + ); + if (iCloudAccessExpired && !allowExpiredAccessToken) { + debugPrint( + '[WatchSync] iCloud token access is expired (expiry: $iCloudExpiryDate), skipping direct apply', + ); + return false; + } + final iCloudTokenVersion = _resolveIncomingTokenVersion(tokenData); + final iCloudUpdatedAtMs = _asInt(tokenData['updatedAtMs']); + final iCloudIdToken = tokenData['idToken'] as String?; + final iCloudRefreshToken = tokenData['refreshToken'] as String?; + + final currentToken = initData.client!.cache.token; + final localExpiry = currentToken.expiryDate; + final shouldAccept = _isIncomingTokenNewerThanCurrent( + incomingExpiry: iCloudExpiryDate, + incomingIdToken: iCloudIdToken, + incomingRefreshToken: iCloudRefreshToken, + incomingTokenVersion: iCloudTokenVersion, + incomingUpdatedAtMs: iCloudUpdatedAtMs, + currentToken: currentToken, + ); + + if (shouldAccept) { + debugPrint( + '[WatchSync] iCloud has fresher token! iCloud: $iCloudExpiryDate, Local: $localExpiry, iCloudVersion: $iCloudTokenVersion', + ); + + final newToken = TokenModel.fromValues( + (tokenData['studentIdNorm'] as int?) ?? 0, + tokenData['studentId'] as String, + tokenData['iss'] as String, + tokenData['idToken'] as String, + tokenData['accessToken'] as String, + tokenData['refreshToken'] as String, + iCloudExpiry, + tokenVersion: iCloudTokenVersion, + updatedAtMs: + iCloudUpdatedAtMs ?? DateTime.now().millisecondsSinceEpoch, + ); + + await effectiveIsar.writeTxn(() async { + await effectiveIsar.tokenModels.put(newToken); + }); + + if (effectiveClient != null && newToken.key == expectedStudentIdNorm) { + effectiveClient.cache.token = newToken; + } + + final shouldClearReauth = + !iCloudAccessExpired && newToken.key == expectedStudentIdNorm; + if (shouldClearReauth) { + if (initDone) initData.toastCubit.clear(); + } + + debugPrint( + '[WatchSync] Token recovered from iCloud! New expiry: $iCloudExpiryDate', + ); + return true; + } else { + debugPrint( + '[WatchSync] Local token is same or fresher. Local: $localExpiry, iCloud: $iCloudExpiryDate', + ); + return false; + } + } catch (e) { + debugPrint('[WatchSync] Failed to check iCloud: $e'); + return false; + } + } + + /// Save token to iCloud. Call this after refreshing token on iPhone. + static Future saveTokenToiCloud( + TokenModel token, { + bool forceAccountSwitch = false, + }) async { + if (!Platform.isIOS) return; + + final watchInstalled = await isWatchAppInstalled(); + if (!watchInstalled) { + debugPrint( + '[WatchSync] Skipping iCloud token save because no paired Watch app is installed', + ); + return; + } + + final tokenData = _buildTokenSyncPayload(token); + tokenData['forceAccountSwitch'] = forceAccountSwitch; + + await _invokeMethodWithTimeout( + 'saveTokeToniCloud', + tokenData, + const Duration(seconds: 5), + ); + debugPrint('[WatchSync] Token saved to iCloud (or timeout)'); + } + + static Future syncTokenFromWatch({ + Isar? isar, + List? tokens, + KretaClient? client, + }) async { + if (!Platform.isIOS || !initDone) return; + + try { + debugPrint('[WatchSync] Requesting token from Watch...'); + final result = await _invokeMethodWithTimeout( + 'requestTokenFromWatch', + null, + const Duration(seconds: 10), + ); + final expectedStudentIdNorm = initData.client!.cache.token.key; + final currentToken = initData.client!.cache.token; + + if (result == null) { + debugPrint('[WatchSync] No response from Watch'); + if (!initData.client!.needsReauth) { + debugPrint('[WatchSync] Sending iPhone token to Watch (no response)'); + await _sendTokenToWatchInternal( + currentToken, + allowExpiredAccessToken: true, + ); + } + return; + } + + final tokenData = result as Map; + if (tokenData.containsKey('error')) { + debugPrint('[WatchSync] Watch returned error: ${tokenData['error']}'); + if (!initData.client!.needsReauth) { + debugPrint( + '[WatchSync] Sending iPhone token to Watch (Watch has no token)', + ); + await _sendTokenToWatchInternal( + currentToken, + allowExpiredAccessToken: true, + ); + } + return; + } + + final watchExpiry = tokenData['expiryDate'] as int?; + if (watchExpiry == null) { + debugPrint('[WatchSync] Watch token has no expiry'); + return; + } + + final watchStudentIdNorm = tokenData['studentIdNorm'] as int?; + if (watchStudentIdNorm == null) { + debugPrint('[WatchSync] Watch token has no studentIdNorm'); + return; + } + + if (watchStudentIdNorm != expectedStudentIdNorm) { + debugPrint( + '[WatchSync] Watch token belongs to different account ($watchStudentIdNorm), active is $expectedStudentIdNorm - keeping active account', + ); + if (!(initData.client!.needsReauth)) { + await _sendTokenToWatchInternal( + currentToken, + allowExpiredAccessToken: true, + ); + } + return; + } + + final watchExpiryDate = DateTime.fromMillisecondsSinceEpoch(watchExpiry); + if (!_isAccessTokenUsable(watchExpiryDate, skew: const Duration())) { + debugPrint( + '[WatchSync] Watch provided expired token, ignoring and keeping iPhone token', + ); + if (_isAccessTokenUsable( + currentToken.expiryDate, + skew: const Duration(), + ) && + !initData.client!.needsReauth) { + await _sendTokenToWatchInternal( + currentToken, + allowExpiredAccessToken: true, + ); + } + return; + } + final watchTokenVersion = _resolveIncomingTokenVersion(tokenData); + final watchUpdatedAtMs = _asInt(tokenData['updatedAtMs']); + final watchIdToken = tokenData['idToken'] as String?; + final watchRefreshToken = tokenData['refreshToken'] as String?; + final shouldAccept = _isIncomingTokenNewerThanCurrent( + incomingExpiry: watchExpiryDate, + incomingIdToken: watchIdToken, + incomingRefreshToken: watchRefreshToken, + incomingTokenVersion: watchTokenVersion, + incomingUpdatedAtMs: watchUpdatedAtMs, + currentToken: currentToken, + ); + if (shouldAccept) { + debugPrint('[WatchSync] Watch has newer token, updating iPhone'); + final newToken = TokenModel.fromValues( + tokenData['studentIdNorm'] as int, + tokenData['studentId'] as String, + tokenData['iss'] as String, + tokenData['idToken'] as String, + tokenData['accessToken'] as String, + tokenData['refreshToken'] as String, + watchExpiry, + tokenVersion: watchTokenVersion, + updatedAtMs: + watchUpdatedAtMs ?? DateTime.now().millisecondsSinceEpoch, + ); + + await isarInit.writeTxn(() async { + await isarInit.tokenModels.put(newToken); + }); + + initData.client!.cache.token = newToken; + + if (newToken.key == expectedStudentIdNorm) { + if (initDone) initData.toastCubit.clear(); + } + + debugPrint( + '[WatchSync] Token updated from Watch. New expiry: $watchExpiryDate', + ); + } else { + debugPrint( + '[WatchSync] iPhone token is same or newer, sending to Watch', + ); + await _sendTokenToWatchInternal( + currentToken, + allowExpiredAccessToken: true, + ); + } + } catch (e) { + debugPrint('[WatchSync] Failed to sync token from Watch: $e'); + } + } +} diff --git a/firka/lib/services/wear_sync_helper.dart b/firka/lib/services/wear_sync_helper.dart deleted file mode 100644 index fde6ee26..00000000 --- a/firka/lib/services/wear_sync_helper.dart +++ /dev/null @@ -1,114 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:flutter/services.dart'; -import 'package:watch_connectivity/watch_connectivity.dart'; - -import 'package:firka/app/app_state.dart'; -import 'package:firka/services/wear_sync_cache.dart'; -import 'package:firka/api/client/kreta_client.dart'; - -/// Helper class for Wear OS sync (Android). -class WatchSyncHelper { - static const _wearSyncChannel = MethodChannel('app.firka/wear_sync'); - static WatchConnectivity? _androidWatchConnectivity; - static WatchConnectivity get _watchConnectivityAndroid { - _androidWatchConnectivity ??= WatchConnectivity(); - return _androidWatchConnectivity!; - } - - /// Callback for Watch pairing message events (Android Wear OS pairing flow). - /// Set by initialization_screen.dart to handle "ping" messages for Watch pairing. - static void Function(Map message)? onWatchMessage; - - /// Send a fire-and-forget message to Watch via watch_connectivity (Android). - /// The payload is sent as a JSON string for reliable transport. - static Future sendMessageToWatch(Map message) async { - if (!Platform.isAndroid) return; - await _watchConnectivityAndroid.sendMessage({ - 'data': jsonEncode(message), - }); - } - - /// Starts the Wear sync foreground service (Android only). Call after writing initial cache. - /// [appDirPath] is the application documents directory path (for the background isolate). - static Future startWearSyncService( - String cachePath, - String appDirPath, - ) async { - if (!Platform.isAndroid) return; - await _wearSyncChannel.invokeMethod( - 'startWearSyncService', - {'cachePath': cachePath, 'appDirPath': appDirPath}, - ); - } - - /// Builds fresh sync payload, writes cache, and starts the Wear sync service (Android only). - /// Use when enabling Wear OS support or on app launch when support is already enabled. - static Future startWearSyncServiceWithFreshCache( - KretaClient client, - String appDirPath, - ) async { - if (!Platform.isAndroid) return; - final payload = await buildWearSyncPayload(client); - if (payload == null) return; - final path = await getWearSyncCachePath(); - await writeWearSyncCache(path, payload); - await startWearSyncService(path, appDirPath); - } - - /// Sets the method call handler for getLocalizedString (Android). Call once when initData is ready. - static void setWearSyncMethodCallHandler() { - if (!Platform.isAndroid) return; - _wearSyncChannel.setMethodCallHandler((MethodCall call) async { - if (call.method == 'getLocalizedString') { - final key = call.arguments as String?; - return getLocalizedString(key); - } - return null; - }); - } - - /// Returns the localized string for [key] from l10n. Used by Kotlin for notification title/text. - static String? getLocalizedString(String? key) { - if (key == null || !initDone) return null; - switch (key) { - case 'wearSyncNotificationTitle': - return initData.l10n.wearSyncNotificationTitle; - case 'wearSyncNotificationText': - return initData.l10n.wearSyncNotificationText; - default: - return null; - } - } - - /// Stops the Wear sync foreground service (Android only). - static Future stopWearSyncService() async { - if (!Platform.isAndroid) return; - await _wearSyncChannel.invokeMethod('stopWearSyncService'); - } - - /// Runs sync in foreground: fetches timetable + grades, writes cache, sends sync_data to watch. - /// Used when app is in foreground and watch sends request_sync (Android) or equivalent. - static Future runWearSyncInForeground(KretaClient client) async { - final payload = await buildWearSyncPayload(client); - if (payload == null) return; - final path = await getWearSyncCachePath(); - await writeWearSyncCache(path, payload); - await sendMessageToWatch({'id': 'sync_data', ...payload}); - } - - /// Stream of messages from the watch (Android: watch_connectivity). Use for request_sync etc. - static Stream> get watchMessageStream { - if (!Platform.isAndroid) return const Stream.empty(); - return _watchConnectivityAndroid.messageStream.map((m) { - final map = Map.from(m); - final data = map['data']; - if (data is String) { - return jsonDecode(data) as Map; - } - return map; - }); - } -} diff --git a/firka/lib/ui/phone/pages/extras/main_wear_pair.dart b/firka/lib/ui/phone/pages/extras/main_wear_pair.dart index fe98521b..fbd12251 100644 --- a/firka/lib/ui/phone/pages/extras/main_wear_pair.dart +++ b/firka/lib/ui/phone/pages/extras/main_wear_pair.dart @@ -1,5 +1,5 @@ import 'package:firka/app/app_state.dart'; -import 'package:firka/services/wear_sync_helper.dart'; +import 'package:firka/services/watch_sync_helper.dart'; import 'package:firka/services/wear_sync_cache.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/firka/lib/ui/phone/screens/debug/debug_screen.dart b/firka/lib/ui/phone/screens/debug/debug_screen.dart index 5e3d11bc..bdedd4fe 100644 --- a/firka/lib/ui/phone/screens/debug/debug_screen.dart +++ b/firka/lib/ui/phone/screens/debug/debug_screen.dart @@ -395,12 +395,15 @@ class _DebugScreen extends FirkaState { await isar.teacherModels.clear(); await isar.homeworkCacheModels.clear(); }); - final dataDir = await getApplicationDocumentsDirectory(); - final widgetFile = File( - p.join(dataDir.path, 'widget_state.json'), - ); - if (await widgetFile.exists()) { - await widgetFile.delete(); + if (Platform.isIOS) { + } else { + final dataDir = await getApplicationDocumentsDirectory(); + final widgetFile = File( + p.join(dataDir.path, 'widget_state.json'), + ); + if (await widgetFile.exists()) { + await widgetFile.delete(); + } } if (!context.mounted) return; ScaffoldMessenger.of(context).showSnackBar( diff --git a/firka/lib/ui/phone/screens/home/home_screen.dart b/firka/lib/ui/phone/screens/home/home_screen.dart index a7795349..620b1911 100644 --- a/firka/lib/ui/phone/screens/home/home_screen.dart +++ b/firka/lib/ui/phone/screens/home/home_screen.dart @@ -2,7 +2,10 @@ import 'dart:async'; import 'dart:io'; import 'package:firka/core/bloc/toast_cubit.dart'; import 'package:firka/core/firka_bundle.dart'; +import 'package:firka/services/live_activity_service.dart'; import 'package:firka/core/settings.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; import 'package:firka/app/app_state.dart'; import 'package:firka/services/progress_notification_service.dart'; import 'package:firka/ui/theme/style.dart'; @@ -36,6 +39,7 @@ class HomeScreen extends StatefulWidget { class _HomeScreenState extends FirkaState with WidgetsBindingObserver { bool _disposed = false; + bool _didRunLiveActivityLogin = false; bool _hasCompletedFirstPrefetch = false; void _setupNotificationListener() { @@ -56,6 +60,42 @@ class _HomeScreenState extends FirkaState }); } + void _setupWidgetDeepLinkListener() { + if (!Platform.isIOS) return; + + final widgetChannel = MethodChannel('firka.app/widget_deep_link'); + + WidgetsBinding.instance.addPostFrameCallback((_) { + widgetChannel.invokeMethod('getPendingDeepLink').then((link) { + if (link != null) _handleWidgetDeepLink(link); + }); + }); + + widgetChannel.setMethodCallHandler((call) async { + if (call.method == 'onWidgetDeepLink') { + final link = call.arguments as String?; + if (link != null) _handleWidgetDeepLink(link); + } + }); + } + + void _handleWidgetDeepLink(String link) { + logger.info('Widget deep link received: $link'); + switch (link) { + case 'home': + appRouter?.go('/home'); + break; + case 'timetable': + appRouter?.go('/timetable'); + break; + case 'grades': + appRouter?.go('/grades'); + break; + default: + logger.warning('Unknown widget deep link: $link'); + } + } + void prefetch() async { if (_prefetched || _fetching) return; @@ -76,6 +116,21 @@ class _HomeScreenState extends FirkaState if (Platform.isAndroid) { await WidgetCacheHelper.updateWidgetCacheFromIsar(); } + + if (Platform.isIOS) { + if (!_didRunLiveActivityLogin) { + _didRunLiveActivityLogin = true; + final token = initData.client!.cache.token; + final studentName = token.username; + LiveActivityService.onUserLogin( + client: initData.client!, + studentName: studentName, + settingsStore: initData.settings, + ).catchError((e, st) { + logger.severe('LiveActivity registration failed: $e', e, st); + }); + } + } } catch (e) { if (_disposed) return; (context); @@ -98,9 +153,21 @@ class _HomeScreenState extends FirkaState WidgetsBinding.instance.addObserver(this); _setupNotificationListener(); + _setupWidgetDeepLinkListener(); prefetch(); _preloadImages(); + + if (Platform.isIOS && Settings.betaWarning.value) { + Future.delayed(Duration(seconds: 3), () async { + await LiveActivityService.showConsentScreenIfNeeded(); + }); + } + if (Platform.isIOS) { + Future.delayed(const Duration(seconds: 4), () { + if (!_disposed) _runLiveActivityLoginIfNeeded(); + }); + } } void _preloadImages() async { @@ -176,6 +243,11 @@ class _HomeScreenState extends FirkaState unawaited(ProgressNotificationService.checkAndStartOnAppOpen()); + if (Platform.isIOS) { + _refreshLiveActivityOnResume(); + _runLiveActivityLoginIfNeeded(); + } + final lastPrefetch = _lastPrefetchAt; if (lastPrefetch != null && DateTime.now().difference(lastPrefetch) < _prefetchCooldown) { @@ -191,6 +263,41 @@ class _HomeScreenState extends FirkaState setState(() {}); } + /// Fallback: if Live Activity login never ran (e.g. prefetch bailed on lifecycle + /// or fetchData didn't complete), run it once when app is resumed. + void _runLiveActivityLoginIfNeeded() { + if (_didRunLiveActivityLogin || _disposed) return; + Future.delayed(const Duration(milliseconds: 500), () async { + if (_disposed || _didRunLiveActivityLogin) return; + _didRunLiveActivityLogin = true; + final studentName = initData.client!.cache.token.username; + LiveActivityService.onUserLogin( + client: initData.client!, + studentName: studentName, + settingsStore: initData.settings, + ).catchError((e, st) { + _didRunLiveActivityLogin = false; + logger.severe('LiveActivity registration failed: $e', e, st); + }); + }); + } + + void _refreshLiveActivityOnResume() async { + if (!_hasCompletedFirstPrefetch) return; + try { + final studentName = initData.client!.cache.token.username; + await LiveActivityService.checkAndUpdateTimetable( + client: initData.client!, + studentName: studentName, + settingsStore: initData.settings, + ); + } catch (e) { + logger.warning( + '[Home] LiveActivity timetable update on resume failed: $e', + ); + } + } + @override void dispose() { WidgetsBinding.instance.removeObserver(this); diff --git a/firka/lib/ui/phone/screens/live_activity/full_privacy_policy_screen.dart b/firka/lib/ui/phone/screens/live_activity/full_privacy_policy_screen.dart new file mode 100644 index 00000000..9b64f2f9 --- /dev/null +++ b/firka/lib/ui/phone/screens/live_activity/full_privacy_policy_screen.dart @@ -0,0 +1,138 @@ +import 'package:firka/app/app_state.dart'; +import 'package:firka/ui/theme/style.dart'; +import 'package:firka/ui/shared/firka_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:majesticons_flutter/majesticons_flutter.dart'; + +import 'package:firka/core/state/firka_state.dart'; + +class FullPrivacyPolicyScreen extends StatefulWidget { + final AppInitialization data; + + const FullPrivacyPolicyScreen({required this.data, super.key}); + + @override + State createState() => + _FullPrivacyPolicyScreenState(); +} + +class _FullPrivacyPolicyScreenState + extends FirkaState { + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: appStyle.colors.background, + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.all(20.0), + child: Row( + children: [ + GestureDetector( + onTap: () { + Navigator.pop(context); + }, + child: FirkaIconWidget( + FirkaIconType.majesticons, + Majesticon.chevronLeftLine, + color: appStyle.colors.textSecondary, + ), + ), + SizedBox(width: 8), + Expanded( + child: Text( + widget.data.l10n.la_privacy_header, + style: appStyle.fonts.H_H2.apply( + color: appStyle.colors.textPrimary, + ), + ), + ), + ], + ), + ), + + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.data.l10n.la_privacy_intro, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + SizedBox(height: 24), + _buildPrivacySection( + widget.data.l10n.la_privacy_section1_title, + widget.data.l10n.la_privacy_section1_body, + ), + _buildPrivacySection( + widget.data.l10n.la_privacy_section2_title, + widget.data.l10n.la_privacy_section2_body, + ), + _buildPrivacySection( + widget.data.l10n.la_privacy_section3_title, + widget.data.l10n.la_privacy_section3_body, + ), + _buildPrivacySection( + widget.data.l10n.la_privacy_section4_title, + widget.data.l10n.la_privacy_section4_body, + ), + _buildPrivacySection( + widget.data.l10n.la_privacy_section5_title, + widget.data.l10n.la_privacy_section5_body, + ), + SizedBox(height: 16), + Text( + widget.data.l10n.la_privacy_footer, + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textTertiary, + ), + ), + SizedBox(height: 8), + Text( + widget.data.l10n.la_privacy_contact, + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textTertiary, + ), + ), + SizedBox(height: 24), + ], + ), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildPrivacySection(String title, String body) { + return Padding( + padding: const EdgeInsets.only(bottom: 20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: appStyle.fonts.H_16px.apply( + color: appStyle.colors.textPrimary, + ), + ), + SizedBox(height: 10), + Text( + body, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ), + ); + } +} diff --git a/firka/lib/ui/phone/screens/live_activity/live_activity_consent_screen.dart b/firka/lib/ui/phone/screens/live_activity/live_activity_consent_screen.dart new file mode 100644 index 00000000..b122a6d1 --- /dev/null +++ b/firka/lib/ui/phone/screens/live_activity/live_activity_consent_screen.dart @@ -0,0 +1,254 @@ +import 'dart:typed_data'; + +import 'package:firka/ui/components/firka_button.dart'; +import 'package:firka_common/ui/components/firka_card.dart'; +import 'package:firka/app/app_state.dart'; +import 'package:firka/ui/theme/style.dart'; +import 'package:firka/ui/phone/screens/live_activity/full_privacy_policy_screen.dart'; +import 'package:firka/ui/shared/firka_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:majesticons_flutter/majesticons_flutter.dart'; + +import 'package:firka/core/state/firka_state.dart'; + +class LiveActivityConsentScreen extends StatefulWidget { + final AppInitialization data; + + const LiveActivityConsentScreen({required this.data, super.key}); + + @override + State createState() => + _LiveActivityConsentScreenState(); +} + +class _LiveActivityConsentScreenState + extends FirkaState { + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: appStyle.colors.background, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + FirkaIconWidget( + FirkaIconType.majesticons, + Majesticon.bellSolid, + color: appStyle.colors.accent, + size: 32, + ), + SizedBox(width: 12), + Expanded( + child: Text( + widget.data.l10n.la_title, + style: appStyle.fonts.H_H1.apply( + color: appStyle.colors.textPrimary, + ), + ), + ), + ], + ), + SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: Text( + widget.data.l10n.la_subtitle, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + maxLines: null, + softWrap: true, + ), + ), + SizedBox(height: 24), + + Card( + color: appStyle.colors.warningCard, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + ), + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + FirkaIconWidget( + FirkaIconType.majesticons, + Majesticon.shieldSolid, + color: appStyle.colors.warningAccent, + size: 24, + ), + SizedBox(width: 8), + Expanded( + child: Text( + widget.data.l10n.la_privacy_title, + style: appStyle.fonts.H_16px.apply( + color: appStyle.colors.warningText, + ), + ), + ), + ], + ), + SizedBox(height: 8), + Text( + widget.data.l10n.la_privacy_required, + style: appStyle.fonts.B_14R.apply( + color: appStyle.colors.warningText, + ), + softWrap: true, + ), + ], + ), + ), + ), + SizedBox(height: 16), + + Expanded( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.data.l10n.la_privacy_intro, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + SizedBox(height: 20), + _buildPrivacySummaryItem( + icon: Majesticon.editPen4Solid, + title: widget.data.l10n.la_privacy_section1_title, + description: widget.data.l10n.la_privacy_summary1, + ), + _buildPrivacySummaryItem( + icon: Majesticon.lockSolid, + title: widget.data.l10n.la_privacy_section2_title, + description: widget.data.l10n.la_privacy_summary2, + ), + _buildPrivacySummaryItem( + icon: Majesticon.clockSolid, + title: widget.data.l10n.la_privacy_section3_title, + description: widget.data.l10n.la_privacy_summary3, + ), + SizedBox(height: 16), + GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + FullPrivacyPolicyScreen(data: widget.data), + ), + ); + }, + child: FirkaCard( + color: appStyle.colors.buttonSecondaryFill, + left: [], + center: [ + Text( + widget.data.l10n.la_learn_more, + style: appStyle.fonts.B_16SB.apply( + color: appStyle.colors.textSecondary, + ), + ), + SizedBox(width: 8), + FirkaIconWidget( + FirkaIconType.majesticons, + Majesticon.chevronRightLine, + color: appStyle.colors.textSecondary, + ), + ], + ), + ), + ], + ), + ), + ), + + SizedBox(height: 16), + + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + GestureDetector( + onTap: () { + Navigator.pop(context, true); + }, + child: FirkaButton( + text: widget.data.l10n.la_accept, + bgColor: appStyle.colors.accent, + fontStyle: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + ), + SizedBox(height: 12), + GestureDetector( + onTap: () { + Navigator.pop(context, false); + }, + child: FirkaButton( + text: widget.data.l10n.la_decline, + bgColor: appStyle.colors.buttonSecondaryFill, + fontStyle: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _buildPrivacySummaryItem({ + required Uint8List icon, + required String title, + required String description, + }) { + return Padding( + padding: const EdgeInsets.only(bottom: 16.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FirkaIconWidget( + FirkaIconType.majesticons, + icon, + color: appStyle.colors.accent, + size: 24, + ), + SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: appStyle.fonts.B_16SB.apply( + color: appStyle.colors.textPrimary, + ), + ), + SizedBox(height: 6), + Text( + description, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/firka/lib/ui/phone/screens/settings/settings_account_picker.dart b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart index 356c0251..33c24cb4 100644 --- a/firka/lib/ui/phone/screens/settings/settings_account_picker.dart +++ b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart @@ -1,7 +1,11 @@ +import "dart:io"; + import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart"; import "package:firka/app/app_state.dart"; import "package:firka/app/initialization.dart"; import "package:firka/services/notification_delivery_service.dart"; +import "package:firka/services/live_activity_service.dart"; +import "package:firka/services/watch_sync_helper.dart"; import "package:firka/ui/shared/firka_icon.dart"; import "package:firka/ui/theme/style.dart"; import "package:firka/ui/phone/widgets/login_webview.dart"; @@ -137,7 +141,25 @@ class SettingsAccountPickerView extends StatelessWidget { return; } + final previousAccountId = data.client!.cache.token.key; await NotificationDeliveryService.onUserLogout(); + if (Platform.isIOS) { + await LiveActivityService.onUserLogout(); + try { + await WatchSyncHelper.clearSharedLanguageState(); + } catch (e) { + logger.warning( + '[Settings] Failed to clear shared language state on account switch: $e', + ); + } + try { + await WatchSyncHelper.clearRefreshLeaseForAccount(previousAccountId); + } catch (e) { + logger.warning( + '[Settings] Failed to clear refresh lease on account switch: $e', + ); + } + } await data.settings.setSelectedAccountKey(token.key); await initializeApp(); @@ -148,6 +170,43 @@ class SettingsAccountPickerView extends StatelessWidget { ); } + if (Platform.isIOS) { + var watchReachable = false; + try { + watchReachable = await WatchSyncHelper.isWatchReachable( + forceRefreshInstall: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to query Watch reachability on account switch: $e', + ); + } + + if (watchReachable) { + try { + await WatchSyncHelper.sendTokenModelToWatch( + token, + allowExpiredAccessToken: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to send switched account token to reachable Watch: $e', + ); + } + } else { + try { + await WatchSyncHelper.saveTokenToiCloud( + token, + forceAccountSwitch: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to sync switched account token to iCloud: $e', + ); + } + } + } + if (!context.mounted) return; final nav = Navigator.of(context); if (nav.canPop()) nav.pop(); @@ -157,8 +216,27 @@ class SettingsAccountPickerView extends StatelessWidget { Future _logout(BuildContext context) async { try { await NotificationDeliveryService.onUserLogout(); + if (Platform.isIOS) { + await LiveActivityService.onUserLogout(); + } final active = data.client!.cache.token.key; + if (Platform.isIOS) { + try { + await WatchSyncHelper.clearRefreshLeaseForAccount(active); + } catch (e) { + logger.warning( + '[Settings] Failed to clear refresh lease for active account: $e', + ); + } + try { + await WatchSyncHelper.clearSharedLanguageState(); + } catch (e) { + logger.warning( + '[Settings] Failed to clear shared language state on logout: $e', + ); + } + } try { await data.client!.cache.clearAccountData(); @@ -173,6 +251,55 @@ class SettingsAccountPickerView extends StatelessWidget { final accounts = await data.isar.tokenModels.where().findAll(); + if (accounts.isEmpty) { + if (Platform.isIOS) { + try { + await WatchSyncHelper.clearICloudToken(notifyWatch: true); + await WatchSyncHelper.clearAllRefreshLeases(); + } catch (e) { + logger.warning('[Settings] Failed to clear iCloud token: $e'); + } + } + } else { + if (Platform.isIOS) { + final nextToken = accounts.first; + var watchReachable = false; + try { + watchReachable = await WatchSyncHelper.isWatchReachable( + forceRefreshInstall: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to query Watch reachability after logout: $e', + ); + } + + if (watchReachable) { + try { + await WatchSyncHelper.sendTokenModelToWatch( + nextToken, + allowExpiredAccessToken: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to send next account token to reachable Watch after logout: $e', + ); + } + } else { + try { + await WatchSyncHelper.saveTokenToiCloud( + nextToken, + forceAccountSwitch: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to sync next account token to iCloud after logout: $e', + ); + } + } + } + } + await initializeApp(); if (context.mounted) { diff --git a/firka/pubspec.yaml b/firka/pubspec.yaml index 03010b1f..90342979 100644 --- a/firka/pubspec.yaml +++ b/firka/pubspec.yaml @@ -47,6 +47,7 @@ dependencies: flutter_staggered_grid_view: ^0.7.0 package_info_plus: ^9.0.0 smart_scroll: ^1.0.0 + live_activities: ^2.4.1 logging: ^1.3.0 share_plus: ^12.0.0 sensors_plus: ^6.1.1 diff --git a/firka/scripts/codegen.dart b/firka/scripts/codegen.dart index ace99d24..663dd741 100644 --- a/firka/scripts/codegen.dart +++ b/firka/scripts/codegen.dart @@ -11,7 +11,6 @@ const _cacheFileName = '.codegen-cache.yaml'; void main() async { final root = _projectRoot(); stdout.writeln(root); - _cleanIos(root); var ran = false; if (_iconsOutOfDate(root)) { @@ -33,7 +32,6 @@ void main() async { runInShell: true, ); if (iconResult.exitCode == 0) { - _cleanIos(root); _updateLockWithHashes(root, 'icons', _computeHashes(root, inputs)); ran = true; } @@ -83,12 +81,10 @@ void main() async { 'Splash out of date, running flutter_native_splash:create...', ); await _run('dart', ['run', 'flutter_native_splash:create'], root); - _cleanIos(root); _updateLockWithHashes(root, 'splash', _computeHashes(root, inputs)); ran = true; } - _cleanIos(root); if (!ran) { stdout.writeln('All generated files are up to date.'); @@ -202,13 +198,6 @@ void _updateCacheWithHashes( _writeYamlFile(_cachePath(root), cache); } -void _cleanIos(String root) { - final iosDir = Directory(p.join(root, 'ios')); - if (iosDir.existsSync()) { - iosDir.deleteSync(recursive: true); - } -} - List _iconsInputs(String root) { final config = File(p.join(root, 'flutter_launcher_icons.yaml')); final pubspec = File(p.join(root, 'pubspec.yaml')); diff --git a/firka/test/api/live_activity_schedule_test.dart b/firka/test/api/live_activity_schedule_test.dart new file mode 100644 index 00000000..6dfe9da6 --- /dev/null +++ b/firka/test/api/live_activity_schedule_test.dart @@ -0,0 +1,47 @@ +import 'package:firka/api/client/live_activity_backend_client.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:kreta_api/kreta_api.dart'; + +Lesson _lesson(String uid, DateTime start, {String state = 'Ervenyes'}) => + Lesson( + uid: uid, + date: start.toIso8601String(), + start: start, + end: start.add(const Duration(minutes: 45)), + name: 'Matematika', + lessonNumber: 1, + roomName: '12', + type: NameUidDesc(uid: '', name: 'TanitasiOra', description: ''), + state: NameUidDesc(uid: '', name: state, description: ''), + canStudentEditHomework: false, + isHomeworkComplete: false, + attachments: const [], + isDigitalLesson: false, + digitalSupportDeviceTypeList: const [], + createdAt: start, + lastModifiedAt: start, + ); + +void main() { + test('keeps only today, drops events and look-ahead lessons, applies bell delay', () { + final now = DateTime(2026, 11, 30, 7); + final first = DateTime(2026, 11, 30, 8); + final items = todayScheduleItems( + [ + _lesson('2,TanitasiOra', first.add(const Duration(hours: 1)), state: 'Elmaradt'), + _lesson('1,TanitasiOra', first), + _lesson('3,TanevRendjeEsemeny', first), + _lesson('4,TanitasiOra__FOR_NOTIFICATION_ONLY', first), + _lesson('5,TanitasiOra', first.add(const Duration(days: 1))), + ], + now, + 30, + ); + + expect(items.length, 2); + expect(items[0]['start'], first.add(const Duration(seconds: 30)).millisecondsSinceEpoch); + expect(items[0]['isCancelled'], false); + expect(items[1]['isCancelled'], true); + expect(items[0]['index'], '1'); + }); +}