44 Commits

Author SHA1 Message Date
Horváth Gergely
8f28fa328c Add force account-switch and iCloud recovery
Introduce forced account-switch handling and improve token selection/recovery logic.

- WatchConnectivityManager & ReauthRequiredView: parse sentAtMs robustly and compute a shouldForceAccountSwitch flag when an incoming token is for a different account; pass forceAccountSwitch to TokenManager.saveToken and include it in logs.
- TokenManager: add localTokenFromKeychainAndFile helper, prefer the active account when selecting a local token, and refine loadToken to prefer active-account tokens but fall back to the freshest available. saveToken now accepts forceAccountSwitch and will persist a token even if it switches accounts when requested. Adjust iCloud handling to skip iCloud token only if a local active-account token exists; improve diagnostic logging.
- WatchToken: enhance isNewer comparison to consider effectiveUpdatedAt and tokenVersion before falling back to expiryDate.
- HomeScreen (phone): import watch_sync_helper and run a secondary iCloud recovery pass on startup (with a short delay) to apply a fresher iCloud token to the app state if needed.

These changes aim to make cross-device token sync more robust, correctly handle account switches triggered from the watch, and recover stale auth state from iCloud on app startup.
2026-02-11 13:09:32 +01:00
Horváth Gergely
8af53422dc Merge branch 'dev' of https://github.com/hgeryy2004/firka into dev 2026-02-11 11:33:43 +01:00
Horváth Gergely
dda4bfd9d3 Improve iCloud / Watch token sync & recovery
Add robust handling for token synchronization and recovery across iOS/watchOS and Flutter.

- iOS (WatchSessionManager.swift): queue token events until Flutter signals watchSyncReady, flush queued auth events and iCloud recovery notifications when ready, forward tokens with de-duplication logic, provide fallback to iCloud when Flutter isn't ready, and avoid sending duplicate events. Adds helper methods for token payloads and comparison.
- Token management (TokenManager.swift): track active studentIdNorm in UserDefaults to prefer a single account, persist active account on saves, prefer freshest token within preferred account, improve proactive refresh with configurable lead time and cooldown, skip unnecessary recoveries when a valid token exists, and add cooldown for phone recovery requests.
- iCloud logic (iCloudTokenManager.swift): avoid overwriting tokens across accounts using updatedAt comparisons and only ignore truly stale saves.
- Dart client (kreta_client.dart): skip recovery if local token still valid, clearer iCloud recovery retry flow, fallbacks, and clear reauth flag when usable token applied.
- Token model (token_model.dart & generated .g.dart): add tokenVersion and updatedAtMs fields, populate them on creation/from response, and update Isar schema + generated query helpers.
- Watch sync helper (watch_sync_helper.dart): include tokenVersion/updatedAt in outgoing payloads, resolve incoming/current versions more robustly, use updatedAt when deciding freshness, and invoke watchSyncReady on init so native side can flush queued events.
- App init (main.dart): run an iCloud recovery check on iOS during startup and only clear reauth flag when the chosen token is still in the future.

These changes improve cross-device token consistency, reduce spurious reauth prompts, and make proactive refresh/recovery less noisy and more efficient.
2026-02-11 11:33:11 +01:00
B3ni
d92e420b34 Update main.dart 2026-02-11 11:27:04 +01:00
Horváth Gergely
b54fa36671 Token recovery and sync refactor; LiveActivity UI
Centralize and harden token recovery and synchronization across watch/phone components and update LiveActivity UI for iOS 18.

Highlights:
- Introduced a centralized recovery flow in TokenManager.recoverToken() with locking, multi-step recovery (local refresh, keychain/file/watch, iCloud retries) and refreshTokenInternal helper. Added proactive refresh and improved refresh logic to include tokenVersion/updatedAtMs metadata.
- Added tokenVersion and updatedAtMs to WatchToken and propagated these fields through iCloud, WatchConnectivity, WatchSessionManager, and ReauthRequiredView payloads. Many save/load paths now avoid unnecessary iCloud sync and ignore stale tokens based on version/timestamps.
- WatchConnectivityManager now filters stale incoming updates using sentAtMs and persists lastAppliedTokenUpdateMs to avoid regressions; payloads include updatedAtMs/tokenVersion when available.
- DataStore and KretaAPIClient use the centralized recovery API instead of ad-hoc retry logic or direct WatchConnectivity requests.
- iCloudTokenManager stores tokenVersion/updatedAtMs, ignores stale saves, and uses consistent timestamps.
- LiveActivityWidget and LiveActivity updated: iOS 18+ uses new adaptive/family-aware views (including a new SmallActivityView) while legacy behavior is preserved for iOS 16.2–17.x.

These changes aim to make token synchronization more reliable across devices and OS versions, reduce duplicate/conflicting writes, and provide a more adaptive live activity UI on newer iOS releases.
2026-02-11 10:37:14 +01:00
Horváth Gergely
60375e93d1 Add active account handling & token recovery
Introduce active account selection and robust token recovery across watch and phone code. Adds a new Dart helper (active_account_helper.dart) to resolve the active account/token and updates KretaClient, token refresh/grant flows, live activity, watch sync, main init and home UI to use pickActiveToken. On the watch side, implement refreshAllWithRecovery in DataStore and replace direct refreshAll calls with refreshAllWithRecovery everywhere (ContentView, BackgroundRefreshManager, WatchConnectivityManager, HomeView). Rewrite the token recovery logic to retry (with delays), prefer fresher iCloud/file/keychain tokens, attempt iPhone retrieval, and better distinguish transient network errors from permanent token invalidation. Also update TokenManager to choose the freshest local token between keychain and file, and add small sync/NULL-safety fixes and delay tweaks in home_screen to improve iCloud recovery behavior. These changes aim to avoid unnecessary reauth prompts, handle intermittent network issues, and support multi-account setups by always using the active token.
2026-02-10 15:04:32 +01:00
Horváth Gergely
eb1e4b4cfd Handle iCloud token recovery and notify Flutter
Add end-to-end handling for tokens recovered from iCloud: TokenManager now detects fresh iCloud tokens and posts a "TokenRecoveredFromiCloud" Notification on iOS; WatchSessionManager observes that notification and invokes the Flutter method "onTokenRecoveredFromiCloud". On the Dart side, WatchSyncHelper handles the new callback and runs checkAndRecoverFromiCloud (clearing the reauth flag when appropriate). HomeScreen now attempts proactive iCloud recovery on iOS during startup when the token is expired/expiring or reauth is required, retrying with incremental delays and updating the client/token cache on success. Also minor log text tweak in main.dart and necessary imports added to home_screen.dart.
2026-02-09 20:29:06 +01:00
Horváth Gergely
f4eb4e7487 Add auto-refresh and duplicate-call guard
Watch app: add Combine import, scenePhase tracking, a periodic timer and a 10-minute freshness threshold to auto-refresh data when the app becomes active or data becomes stale. Move refresh logic into onChange/onReceive handlers and add shouldAutoRefresh to avoid unnecessary refreshes; removed an immediate proactive token refresh in ContentView. DataStore.refreshAll now early-returns if a refresh is already in progress and logs the skip to prevent duplicate concurrent refreshes.
2026-02-09 18:23:55 +01:00
Horváth Gergely
584f340778 Handle percentage grades and token recovery
Add support for percentage-style grades and normalize them to standard grade scale across the watch app and shared models; show raw percentage in grade badge UI while keeping normalized coloring. Update WidgetGrade/KretaGrade to include valueType, add isPercentageGrade, percentageToGrade, normalizedNumericValue, displayTypeWithWeight and displayGradeValue helpers, and use normalized values in DataStore and views. Improve HomeView refresh button to reflect background loading, disable during datastore loading, and auto-transition success/failure states when background sync finishes. Enhance token recovery logic in Dart: KretaClient attempts watch/iCloud recovery twice (with a short delay) before forcing reauth, and token_grant tries to recover a fresher token from iCloud via WatchSyncHelper on 401 responses before throwing token errors.
2026-02-09 15:34:14 +01:00
Horváth Gergely
b9de46f0ed Add iCloud token sync & improve recovery
Add iCloud-based token recovery and saving across iOS/watch components. Introduces WatchSyncHelper.checkAndRecoverFromiCloud and saveTokenToiCloud to fetch/save fresher tokens via a method channel, calls the check on app init and before proactive refresh, and attempts to save refreshed tokens to iCloud. Adds native handlers in WatchSessionManager (checkiCloudToken, saveTokeToniCloud) and updates DataStore token recovery to distinguish network errors vs permanently invalid tokens (avoid unnecessary reauth). Update logging messages accordingly. Also update ubiquity-kvstore identifiers in entitlements to use explicit group.app.firka.firkaa and bump iOS build/version (CURRENT_PROJECT_VERSION and CFBundleVersion) to 1068.
2026-02-08 16:18:28 +01:00
Horváth Gergely
0f3dcf58a5 Add splash assets and watch token recovery
Add Android and iOS launch/splash assets and flutter_native_splash config, and update launch_background.xml/styles for Android 12 support and dark mode.

Implement robust Apple Watch token recovery and refresh behavior: add recovery state and async recovery flow to DataStore (iCloud check, API refresh, request from iPhone), show a recovering UI in ContentView, attempt proactive recoveries on startup, and add WatchToken/iCloudTokenManager model support. WatchConnectivityManager now attempts to refresh expired tokens before replying to iPhone requests. BackgroundRefreshManager scheduling was improved to choose intervals based on timetable and user settings with debug logs. SettingsView defaults to Auto (0) and adds the Auto picker option and localization strings.

Also update entitlements across watch/widget extensions to include com.apple.developer.ubiquity-kvstore-identifier, rename watch app icon entry, and add project.pbxproj references for new source files.
2026-02-06 22:23:18 +01:00
Horváth Gergely
b58e60a1f8 Enhance reauthentication process with token recovery from Apple Watch 2026-02-05 22:12:43 +01:00
Horváth Gergely
42b8eea0ba Improve watch sync error handling and reauthentication logic 2026-02-05 18:24:02 +01:00
Horváth Gergely
ce9781f1c0 Fix typo in import statement
Corrects a misspelled 'mport SwiftUI' to 'import SwiftUI' in LessonCard.swift, restoring the proper SwiftUI import and preventing compilation errors.
2026-02-05 16:04:54 +01:00
Horváth Gergely
e5224cbfff Add Apple Watch app and watch sync support
Add a new Firka Watch app target with UI components, views and services: DataStore, BackgroundRefreshManager, WatchConnectivity/WatchSession integration, localization (WatchL10n), entitlements and assets. Move widget/shared models into ios/Shared and update Xcode project/schemes; add native Kreta API client and TokenManager for watch use. Implement watch-side caching, proactive token refresh, background scheduling, and pairing/pairing UI. Update Flutter side (watch_sync_helper, main, API/token helper changes) and tweak iOS .gitignore and project metadata to enable the watch integration and data sync between phone and watch.
2026-02-05 16:01:58 +01:00
Horváth Gergely
2d14c41070 Add Shortcuts intents, entities & localizations
Introduce App Shortcuts and AppIntents support: add multiple shortcut intents (next/closest lesson, today/tomorrow/closest timetable, recent grades, subject/overall averages), AppShortcuts provider, and ShortcutError. Add AppEntity types (Average, Grade, Lesson, Subject) and corresponding entity queries. Refactor Controls to use AppIntent-based navigation (OpenHome/OpenGrades/OpenTimetable) with localized labels/descriptions and remove duplicate SubjectEntity from AveragesIntent. Update TimetableProvider to use a lock-screen-friendly timeline refresh policy. Add localization resources (AppShortcuts.strings and expanded Localizable.strings) for en/de/hu and register new strings in project files; update Info.plist/project.pbxproj accordingly.
2026-01-31 11:52:01 +01:00
Horváth Gergely
ecb1745d9e Show active break in timetable widget
Add break detection and UI for active breaks in timetable widgets. Introduces a new localization key "break_between" and a BreakIndicatorRow view that displays a break marker and minutes left. TimetableMediumView and TimetableLargeView now detect when the current time falls between consecutive lessons, reduce the number of visible lessons accordingly, and inject a BreakIndicatorRow between lessons when in a break (minutes are calculated using ceil of time interval). Also clean up commented/debug lines in the iOS widget cache helper (widget.dart) for locale/theme and removed a TODO comment.
2026-01-30 20:44:48 +01:00
Horváth Gergely
0abc568a64 Add next-school-day support to iOS widgets
Add support for showing the next school day in widgets. Changes include: new localization keys (next_school_day_timetable, no_lessons_ahead) and a formatShortDate helper; updated Hungarian hours abbreviation. Widget model updated (TimetableData) to include nextSchoolDay and nextSchoolDayDate. TimetableProvider now sets isNextSchoolDay/nextSchoolDayDate and returns an entry when a future school day is found. Views (inline, lock screen, small/medium/large) updated to display the next school day header/date and show no_lessons_ahead where appropriate. Flutter helpers (widget cache/IOS helper) extended to serialize nextSchoolDayLessons/nextSchoolDayDate and to search up to a week ahead for the next school day when tomorrow is empty.
2026-01-30 20:25:02 +01:00
Horváth Gergely
0845290929 Add logging, await token callback and widget refresh
Fixes async token handling and improves observability: await the callback in KretaClient to ensure proper async flow, add informative logs for token expiry/refresh and warn on empty 200/201 API responses. Enhance token refresh flow in token_grant with detailed info/warning/severe logs and exception logging for easier debugging. Update widget DB helper to force fresh fetches for timetables/grades when updating widget cache, avoid writing empty caches and add debug prints for counts and cache status. Wire widget refresh into LiveActivityService background fetch (with import and try/catch logging) so iOS widgets get refreshed during background processing.
2026-01-30 10:41:26 +01:00
Horváth Gergely
3a0eb5fe54 Add iOS Control widgets & timetable UI updates
Introduce iOS 18 Control widgets and improve timetable/widget UI and behavior.

- Add Home, Grades and Timetable Control widgets (AppIntents) that write a "controlNavigation" value into the app group (group.app.firka.firkaa) so the main app can open the requested page.
- Register control widgets in HomeWidgetsBundle for iOS 18+.
- Extend WidgetLocalization with short/abbrev strings (tomorrow_short, hours_abbrev, in_hours) and related localization keys.
- Enhance Lock Screen and Timetable widgets to handle next-day lessons, show hours when >60 minutes, and use localized hour/minute strings.
- Update TimetableProvider timeline generation to avoid producing per-minute entries far before the next lesson; if the next lesson is >60 minutes away, add only a single entry ~60 minutes before it.
- Adjust various widget views (Averages, Grades, Timetable) for more compact layout: spacing, font weights/sizes, compact modes, and added average color logic.
- Update project.pbxproj to add a file-system-synchronized exception for the HomeWidgetsExtension files in the Runner target.
- AppDelegate: read and remove "controlNavigation" from the shared app group and return it via the Flutter method channel as a pending deep link; fall back to existing pendingWidgetDeepLink.
- Flutter: map a received 'home' deep link to HomePage.home in the home screen navigation switch.

These changes add Control Center / Lock Screen launch shortcuts and refine widget presentation and timeline performance.
2026-01-29 23:48:59 +01:00
Horváth Gergely
503a51ca23 Add lock-screen/inline widgets & timeline updates
Introduce Lock Screen and Inline variants for Timetable, Grades and Averages widgets and register them in HomeWidgetsBundle. Add new views and widget configurations (accessoryInline, accessoryCircular, accessoryRectangular) under LockScreen/, plus grade badge and average display UI. Extend Localization with many new keys in Helpers/Localization.swift and add lock-screen descriptions in en/de/hu Localizable.strings. Update TimetableProvider timeline logic to generate more frequent (per-minute) update entries for lock-screen families, deduplicate timeline dates and ensure proper midnight transition. Adjust TimetableViews display logic to prefer next lesson when current is absent and fix displayed label selection. Apply project.pbxproj updates to file-exception/group entries and some build phase metadata.
2026-01-29 13:36:11 +01:00
Horváth Gergely
0781685015 iOS: rename LiveActivity widget & update configs
Rename TimetableWidget to LiveActivityWidget and clean up HomeWidgetsExtension targets/files. Update entitlements (group id and formatting) and remove duplicate HomeWidgetsExtensionExtension entitlements file. Update Runner.xcodeproj: bump objectVersion, rename targets/products/references, add WidgetExtension.xcconfig, switch entitlements/infoplist paths, set live-activity related flags, adjust deployment targets/locales and MARKETING_VERSION/CURRENT_PROJECT_VERSION to use Flutter variables. Change app display name to "Firka Testing" and move CFBundleVersion in Info.plist. Also change default widget style to .liquidGlass for Averages, Grades and Timetable intents and fix null-safety when serializing subject/grade category fields in ios_widget_helper.dart.
2026-01-29 02:33:39 +01:00
Horváth Gergely
2a4836c42f Improve iOS widgets: UI, timeline and JSON fixes
Multiple widget improvements and bug fixes:

- Models: WidgetGrade now exposes subjectNameWithWeight and teacherName for display.
- AveragesProvider: added isFiltered flag, improved subject filtering logic and propagated flag to entries.
- Averages views: show filtered count badge, use configurable max visible items, and respect isFiltered.
- Grades views: display subject name with weight, show teacher in grade rows (renamed flag to showTeacher) and preserve topic display.
- TimetableProvider: build unique transition times for timeline updates, sort entries, and determine current lesson using the provided date instead of Date().
- Timetable views: compute visibleLessons window around the current lesson based on entry.date and use isLessonActive checks against entry.date.
- iOS widget JSON helper: fix subject.category serialization structure, use grade.creationDate for recordDate, and use grade.teacher for teacherName.

These changes fix incorrect JSON exports, improve timeline accuracy, and enhance widget UX when subjects are filtered or when showing teacher/weight info.
2026-01-28 23:37:27 +01:00
Horváth Gergely
4ff6f2fdb0 Add deep link handling for widgets; implement navigation from widget links 2026-01-27 22:22:10 +01:00
Horváth Gergely
f80ce9bc4f Add iOS Home Widgets Extension with timetable, grades, and averages
Introduces a new HomeWidgetsExtension for iOS, including widgets for timetable, recent grades, and subject averages. Adds widget models, providers, intents, localization, and SwiftUI views. Updates project files and main app to support widget data sharing and communication. Also includes new Dart helper for widget data and updates to relevant Flutter screens.
2026-01-27 18:58:25 +01:00
Horváth Gergely
91bf7a359c Add tokenExpired property and update warning display logic in live activity 2025-12-30 04:03:09 +01:00
Horváth Gergely
6d7d3641ea Add user-specific bell delay settings; implement retrieval and storage in SharedPreferences 2025-12-29 22:07:13 +01:00
Horváth Gergely
873e0f209b Add morning notification settings; implement user-specific preferences for time and enabled state 2025-12-24 20:44:40 +01:00
Horváth Gergely
8d768ca6b8 Implement token expiration handling and reauthentication UI; add reauth toast and update seasonal icon logic 2025-12-19 14:51:12 +01:00
Horváth Gergely
229eabfd4f Refactor logging in live activity manager and backend client; streamline lesson data handling and improve break event detection logic 2025-12-18 00:33:13 +01:00
Horváth Gergely
80599c13d8 Refactor lesson filtering and add logic to handle break events in live activity manager 2025-12-15 23:06:28 +01:00
Horváth Gergely
c92e83aadd Enhance time formatting by adding language detection for compact time and seasonal break methods 2025-12-13 03:54:25 +01:00
Horváth Gergely
47670fb558 Add time formatting helper and update seasonal display logic 2025-12-13 03:31:03 +01:00
Horváth Gergely
b8058cd4cb Add morning notification settings and debounce handling for Live Activities 2025-12-12 23:59:32 +01:00
Horváth Gergely
4fd3e2a09b Refactor date calculations for start of the week in live activity service 2025-12-08 09:41:06 +01:00
Horváth Gergely
0e0fa549cf Reduce bellDelay debounce interval from 5 seconds to 3 seconds;
Enhance lesson fetching logic for improved notification scheduling
2025-12-04 13:54:30 +01:00
39e9c097a0 Update project settings and entitlements for improved configuration
- Bump object version in project.pbxproj
- Refactor TimetableWidget folder exceptions in project.pbxproj
- Add BGTaskSchedulerPermittedIdentifiers to Info.plist
- Update development team and product bundle identifiers in entitlements
- Mark subproject as dirty in l10n
2025-11-26 16:33:37 +01:00
Horváth Gergely
ea8315a993 - Fixed UI/UX bugs in the Live Activities
- Fixed the unhandled language get, when the Live Activity is turned off
- Fixed bellDelay bugs
2025-11-26 05:05:14 +01:00
Horváth Gergely
6d33f6b0d8 - Added bellDelay support for Live Activities; both standard push notifications and Live Activities now use the bellDelay value (default: 0). IMPORTANT: Holidays and school break(spring,summer,autumn,winter) activities do not apply bellDelay.
- Implemented background fetch on iOS: the app now refreshes every 30 minutes in the background and sends timetable changes to the backend if any are detected.
2025-11-25 19:07:30 +01:00
Horváth Gergely
8c4bbd0905 - Fixed user switching so previous user data is now properly cleared.
- Fixed re-login behavior: after every new login, the Live Activities privacy notice is shown as intended.
- Made the Live Activity toggle user-specific to prevent settings from carrying over after switching accounts.
- Fixed user logout so the backend now correctly removes all related data.
- Fixed first-install behavior so the Live Activities privacy notice no longer appears on the public beta screen; it now only appears after reaching the home page.
2025-11-25 14:18:23 +01:00
Horváth Gergely
fe70fc7bd1 - Fixed lesson language data; backend now passes the correct values.
- Updated handling of cancelled lessons: removed timer and now displaying the localized “Cancelled” text.
- Aligned the icon and lesson number in the Dynamic Island so they are now level with the label text.
2025-11-24 21:21:12 +01:00
Horváth Gergely
eb3ed957f1 Add data privacy consent dialog for Live Activity
A new data privacy consent dialog has been added to the Live Activity feature. Users must accept this dialog to use Live Activity. If they decline, all their data will be immediately deleted from the database, and cannot use the Live Activities feature. Additionally, users receive a detailed description explaining what data we store, for how long, and their GDPR rights.
2025-11-24 04:43:14 +01:00
cd525898bb Merge branch 'dev' of https://github.com/hgeryy2004/firka into dev 2025-11-20 09:00:31 +01:00
Horváth Gergely
626d6aefdd Added an example of the .env file. 2025-11-19 13:36:35 +01:00
285 changed files with 21325 additions and 17830 deletions

15
.gitmodules vendored
View File

@@ -1,9 +1,18 @@
[submodule "firka/vendor/isar_generator"]
path = firka/vendor/isar_generator
url = https://git.qwit.cloud/firka/isar_generator
[submodule "firka/vendor/isar"]
path = firka/vendor/isar
url = https://git.qwit.cloud/firka/isar
[submodule "firka/vendor/isar_flutter_libs"]
path = firka/vendor/isar_flutter_libs
url = https://git.qwit.cloud/firka/isar_flutter_libs
[submodule "firka/lib/l10n"]
path = firka/lib/l10n
url = https://github.com/QwIT-Development/firka-localization
[submodule "firka_wear/vendor/wear_plus"]
path = firka_wear/vendor/wear_plus
url = https://git.firka.app/firka/wear_plus
[submodule "firka/android/app/src/main/java/org/brotli"]
path = firka/android/app/src/main/java/org/brotli
url = https://git.firka.app/firka/org_brotli
[submodule "firka_wear/lib/l10n"]
path = firka_wear/lib/l10n
url = https://github.com/qwit-development/firka-localization

5
firka/.gitignore vendored
View File

@@ -49,7 +49,4 @@ app.*.map.json
/android/app/profile
/android/app/release
coverage
# Generated files
*.g.dart
coverage

View File

@@ -1,18 +1,36 @@
import org.apache.commons.io.FileUtils
import java.io.FileInputStream
import java.security.MessageDigest
import java.util.Properties
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import java.util.zip.ZipOutputStream.DEFLATED
import java.util.zip.ZipOutputStream.STORED
plugins {
id("com.android.application")
id("kotlin-android")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.plugin.compose") version "2.2.0"
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
fun loadProperties(file: File): Properties {
val properties = Properties()
FileInputStream(file).use { inputStream ->
properties.load(inputStream)
}
return properties
}
android {
namespace = "app.firka.naplo"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
ndkVersion = "27.0.12077973"
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
@@ -31,8 +49,8 @@ android {
applicationId = "app.firka.naplo"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
minSdk = 29
targetSdk = 36
versionCode = flutter.versionCode
versionName = flutter.versionName
}
@@ -41,7 +59,7 @@ android {
val propsFile = File(secretsDir, "keystore.properties")
if (propsFile.exists()) {
val props = Properties().apply { FileInputStream(propsFile).use { load(it) } }
val props = loadProperties(propsFile)
val store = File(secretsDir, props["storeFile"].toString())
signingConfigs {
@@ -50,10 +68,6 @@ android {
storePassword = props["storePassword"] as String
keyPassword = props["keyPassword"] as String
keyAlias = props["keyAlias"] as String
// Use APK Signature Scheme v3 (and v4 for streaming verification). See:
// https://source.android.com/docs/security/features/apksigning/v3
enableV3Signing = true
enableV4Signing = true
}
}
}
@@ -75,25 +89,808 @@ android {
}
}
dependencies {
implementation("androidx.wear:wear-ongoing:1.0.0")
implementation("androidx.glance:glance-appwidget:1.1.1")
implementation("com.google.android.gms:play-services-wearable:18.1.0")
}
// Ensure .env exists before Flutter bundles assets (copy from .env.example if missing)
val envFile = file("${project.projectDir}/../../.env")
val envExampleFile = file("${project.projectDir}/../../.env.example")
tasks.register("ensureEnv") {
doLast {
if (!envFile.exists() && envExampleFile.exists()) {
envExampleFile.copyTo(envFile, overwrite = false)
println("Created .env from .env.example for asset bundling.")
}
}
}
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
dependsOn("ensureEnv")
}
flutter {
source = "../.."
}
}
tasks.register("transformAndResignDebugApk") {
group = "build"
description = "Transform and resign APK with debug key"
dependsOn("assembleDebug")
doLast {
if (System.getenv("TRANSFORM_APK") != null
&& System.getenv("TRANSFORM_APK") == "true") {
transformApks(true)
}
}
}
tasks.register("transformAndResignReleaseApk") {
group = "build"
description = "Transform and resign APK with release key"
dependsOn("assembleRelease")
doLast {
checkReleaseKey()
if (System.getenv("TRANSFORM_APK") != null
&& System.getenv("TRANSFORM_APK") == "true") {
transformApks(false)
}
}
}
tasks.register("transformAndResignReleaseBundle") {
group = "build"
description = "Transform and resign bundle with release key"
dependsOn("bundleRelease")
doLast {
if (System.getenv("TRANSFORM_AAB") != null
&& System.getenv("TRANSFORM_AAB") == "true") {
transformAppBundle()
}
}
}
afterEvaluate {
tasks.findByName("assembleDebug")?.finalizedBy("transformAndResignDebugApk")
tasks.findByName("assembleRelease")?.finalizedBy("transformAndResignReleaseApk")
tasks.findByName("bundleRelease")?.finalizedBy("transformAndResignReleaseBundle")
}
fun checkReleaseKey() {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (propsFile.exists()) {
val props = loadProperties(propsFile)
val store = File(secretsDir, props["storeFile"].toString())
println(
"Signing with:\n" +
"\t- store: ${store.name}\n" +
"\t- key: ${props["keyAlias"]}"
)
} else {
throw Exception("Release keystore not found!")
}
}
fun transformApks(debug: Boolean, i : Int = 0) {
try {
_transformApks(debug)
} catch (e: Exception) {
if (i < 5) {
e.printStackTrace()
println("Retrying: ${i + 1}")
transformApks(debug, i + 1)
} else {
throw e
}
}
}
fun _transformApks(debug: Boolean) {
println("Starting APK transformation process...")
val buildDir = project.buildDir
val apkDir = File(buildDir, "outputs/flutter-apk")
val apks = getApks(debug)
var c = 0
apks
.forEach { c++; transformAndSignApk(apkDir, it.nameWithoutExtension, debug) }
println("Transformed: $c apks")
}
fun transformAndSignApk(apkDir: File, name: String, debug: Boolean) {
val originalApk = File(apkDir, "$name.apk")
val transformedApk = File(apkDir, "$name-transformed.apk")
val finalApk = File(apkDir, "$name-resigned.apk")
val finalIdsig = File(apkDir, "$name-resigned.apk.idsig")
if (!originalApk.exists()) {
throw GradleException("Original APK not found at: ${originalApk.absolutePath}")
}
if (transformedApk.exists()) transformedApk.delete()
if (finalApk.exists()) finalApk.delete()
println("Original APK: ${originalApk.absolutePath}")
try {
println("Transforming APK...")
transformApk(originalApk, transformedApk, if (debug) { "6" } else {"Z"})
if (debug) {
println("Signing with debug key...")
signWithDebugKey(transformedApk, finalApk)
} else {
println("Signing with release key...")
signWithReleaseKey(transformedApk, finalApk)
}
if (finalApk.exists()) {
originalApk.delete()
finalIdsig.delete()
finalApk.renameTo(originalApk)
println("APK successfully transformed")
println("Final APK: ${originalApk.absolutePath}")
}
transformedApk.delete()
} catch (e: Exception) {
throw GradleException("Failed to transform and resign APK: ${e.message}", e)
}
}
fun transformApk(input: File, output: File, compressionLevel: String = "Z") {
val tempDir = File(project.buildDir, "tmp/apk-transform")
val cacheDir = File(project.buildDir, "cache")
val optipngCacheDir = File(cacheDir, "optipng")
val assetCompressionDir = File(cacheDir, "assets")
tempDir.deleteRecursively()
tempDir.mkdirs()
if (!optipngCacheDir.exists()) optipngCacheDir.mkdirs()
if (!assetCompressionDir.exists()) assetCompressionDir.mkdirs()
val brotli = findToolInPath("brotli")
?: throw Exception("Brotli not found in path")
val optipng = findToolInPath("optipng")
if (optipng == null || optipng.isEmpty()) {
println("Optipng was not found in PATH, optimizing images will be skipped.")
}
copy {
from(zipTree(input))
into(tempDir)
}
val metaInf = File(tempDir, "META-INF")
val metaInfFiles = metaInf.listFiles()
for (file in metaInfFiles!!) {
if (file.name.endsWith("MF") || file.name.endsWith("SF")
|| file.name.endsWith("RSA")) {
file.delete()
}
}
val arches = File(tempDir, "lib").listFiles()
val compressedLibs = mutableMapOf<String, String>()
for (arch in arches!!) {
val libFlutter = File(arch, "libflutter.so")
if (!libFlutter.exists()) continue
val compressedFlutter = File(arch, "libflutter-br.so")
compressedLibs["libflutter.so"] = libFlutter.sha256()
println("Compressing ${arch.name}/libflutter.so with brotli")
exec {
commandLine(
brotli,
"-$compressionLevel",
libFlutter.absolutePath,
"-o", compressedFlutter.absolutePath
)
}
libFlutter.delete()
val json = groovy.json.JsonBuilder(compressedLibs)
File(arch, "index.so").writeText(json.toString())
}
val topDirL = tempDir.absolutePath.length + 1
val zos = ZipOutputStream(output.outputStream())
val coreCount = Runtime.getRuntime().availableProcessors()
val flutterResources = tempDir.walkTopDown().filter{f -> f.absolutePath.contains("flutter_assets")}
val pngFiles = tempDir.walkTopDown().filter{f -> f.name.endsWith(".png")}
val assetIndex = mutableMapOf<String, String>()
val indexReadWriteLock = ReentrantReadWriteLock()
if (compressionLevel == "Z") {
if (optipng != null) {
val executor = Executors.newFixedThreadPool(coreCount)
val futures = mutableListOf<Future<*>>()
pngFiles.forEach { pngFile ->
val cacheFile = File(optipngCacheDir, pngFile.sha256())
if (cacheFile.exists()) {
cacheFile.copyTo(pngFile, true)
} else {
val future = executor.submit {
exec {
commandLine(
optipng,
"-zm", "9",
"-zw", "32k",
"-o9",
pngFile.absolutePath
)
}
pngFile.copyTo(cacheFile, true)
}
futures.add(future)
}
}
futures.forEach { it.get() }
executor.shutdown()
}
val executor = Executors.newFixedThreadPool(coreCount)
val futures = mutableListOf<Future<*>>()
val blacklist = listOf(
// "AssetManifest.bin",
"AssetManifest.json",
"FontManifest.json",
"isolate_snapshot_data",
"kernel_blob.bin",
"NativeAssetsManifest.json",
"NOTICES.Z",
"vm_snapshot_data",
"fonts",
"shaders"
)
flutterResources.forEach { f ->
val relName = f.absolutePath.substring(topDirL).replace("\\", "/")
if (f.isDirectory) return@forEach
val cacheFileRaw = File(assetCompressionDir, f.sha256()+".r")
val cacheFileGz = File(assetCompressionDir, f.sha256()+".gz")
val cacheFileBr = File(assetCompressionDir, f.sha256()+".br")
if (cacheFileRaw.exists() || cacheFileGz.exists() || cacheFileBr.exists()) {
if (cacheFileRaw.exists()) {
cacheFileRaw.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "r"
indexReadWriteLock.writeLock().unlock()
} else if (cacheFileGz.exists()) {
cacheFileGz.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "g"
indexReadWriteLock.writeLock().unlock()
} else {
cacheFileBr.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "b"
indexReadWriteLock.writeLock().unlock()
}
} else {
val future = executor.submit {
val brTmp = File(f.absolutePath + ".br.tmp")
val gzTmp = File(f.absolutePath + ".gz.tmp")
var blacklisted = false
for (f in blacklist) {
if (relName.contains(f)) {
blacklisted = true
break
}
}
if (!blacklisted) {
println("$relName: Testing with brotli")
exec {
commandLine(
brotli,
"-$compressionLevel",
f.absolutePath,
"-o", brTmp.absolutePath
)
}
println("$relName: Testing with gzip")
ant.invokeMethod(
"gzip", mapOf(
"src" to f.absolutePath,
"destfile" to gzTmp.absolutePath,
)
)
println("$brTmp: ${brTmp.length()}")
println("$gzTmp: ${gzTmp.length()}")
if (f.length() < gzTmp.length() && f.length() < brTmp.length()) {
println("$relName: Raw file wins")
f.copyTo(cacheFileRaw, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "r"
indexReadWriteLock.writeLock().unlock()
} else {
if (brTmp.length() < gzTmp.length()) {
println("$relName: Brotli wins")
f.delete()
brTmp.copyTo(f, true)
brTmp.copyTo(cacheFileBr, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "b"
indexReadWriteLock.writeLock().unlock()
} else {
println("$relName: Gzip wins")
f.delete()
gzTmp.copyTo(f, true)
gzTmp.copyTo(cacheFileGz, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "g"
indexReadWriteLock.writeLock().unlock()
}
}
brTmp.delete()
gzTmp.delete()
}
}
futures.add(future)
}
}
futures.forEach { it.get() }
executor.shutdown()
}
tempDir.walkTopDown().forEach { f ->
if (f.absolutePath == tempDir.absolutePath) return@forEach
var relName = f.absolutePath.substring(topDirL).replace("\\", "/")
if (f.isDirectory && !relName.endsWith("/")) relName += "/"
if (compressionLevel == "Z") {
if (relName == "assets/flutter_assets/assets/firka.i") return@forEach
}
println(relName)
val compress = !relName.endsWith(".so") && !relName.endsWith(".arsc")
zos.setMethod(if (compress) { DEFLATED } else { STORED })
val entry = ZipEntry(relName)
if (!compress) {
entry.size = f.length()
entry.crc = FileUtils.checksumCRC32(f)
}
zos.putNextEntry(entry)
if (f.isFile) {
zos.write(f.readBytes())
}
zos.closeEntry()
}
if (compressionLevel == "Z") {
zos.setMethod(DEFLATED)
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
val indexUncompressed = File(tempDir, "index.json")
indexReadWriteLock.readLock().lock()
val json = groovy.json.JsonBuilder(assetIndex)
indexReadWriteLock.readLock().unlock()
indexUncompressed.writeText(json.toString())
val indexCompressed = File(tempDir, "index.json.br")
exec {
commandLine(
brotli,
"-$compressionLevel",
indexUncompressed.absolutePath,
"-o", indexCompressed.absolutePath
)
}
zos.write(indexCompressed.readBytes())
indexUncompressed.delete()
indexCompressed.delete()
zos.closeEntry()
}
zos.close()
tempDir.deleteRecursively()
println("APK transformed successfully")
}
fun transformAppBundle() {
val buildDir = project.buildDir
val bundle = File(buildDir, "outputs/bundle/release/app-release.aab")
val bundleTmp = File(buildDir, "outputs/bundle/release/tmp.zip")
val apks = getApks(false)
val apkCount = apks.count { it.name.startsWith("app-") && it.name.endsWith("-release.apk") }
if (!bundle.exists()) {
throw Exception("Bundle not found at: $bundle")
}
if (apkCount < 3) {
throw Exception("Excepected 3 apks per abi but only found $apkCount")
}
val aabTempDir = File(project.buildDir, "tmp/aab-transform")
aabTempDir.deleteRecursively()
aabTempDir.mkdirs()
val apksUnzipped = File(project.buildDir, "tmp/apks-unzipped")
apksUnzipped.deleteRecursively()
val arm32TempDir = File(apksUnzipped, "armeabi-v7a")
arm32TempDir.mkdirs()
val arm64TempDir = File(apksUnzipped, "arm64-v8a")
arm64TempDir.mkdirs()
val x86TempDir = File(apksUnzipped, "x86_64")
x86TempDir.mkdirs()
copy {
from(zipTree(bundle))
into(aabTempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("armeabi-v7a") }))
into(arm32TempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("arm64-v8a") }))
into(arm64TempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("x86_64") }))
into(x86TempDir)
}
val libs = File(aabTempDir, "base/lib").listFiles()!!
for (dstLibs in libs) {
println("Copying lib: ${dstLibs.name}")
val srcDir = File(apksUnzipped, dstLibs.name)
if (!srcDir.exists()) {
continue
}
val srcLibs = File(srcDir, "lib/${dstLibs.name}/")
dstLibs.listFiles()!!.forEach { it.delete() }
srcLibs.listFiles()!!.forEach { it.copyTo(File(dstLibs, it.name)) }
}
val zos = ZipOutputStream(bundleTmp.outputStream())
val bundleZip = ZipFile(bundle)
val bundleEntries = bundleZip.entries()
val brotli = findToolInPath("brotli")
?: throw Exception("Brotli not found in path")
val optipng = findToolInPath("optipng")
?: throw Exception("Optipng not found in path")
val indexReadWriteLock = ReentrantReadWriteLock()
val assetIndex = mutableMapOf<String, String>()
while (bundleEntries.hasMoreElements()) {
val entry = bundleEntries.nextElement()
/*
if (entry.name == "base/assets/flutter_assets/assets/firka.i") {
println("Patching: ${entry.name}")
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
val indexUncompressed = File(aabTempDir, "index.json")
indexReadWriteLock.readLock().lock()
val json = groovy.json.JsonBuilder(assetIndex)
indexReadWriteLock.readLock().unlock()
indexUncompressed.writeText(json.toString())
val indexCompressed = File(aabTempDir, "index.json.br")
exec {
commandLine(
brotli,
"-Z",
indexUncompressed.absolutePath,
"-o", indexCompressed.absolutePath
)
}
zos.write(indexCompressed.readBytes())
indexUncompressed.delete()
indexCompressed.delete()
zos.closeEntry()
continue
}
if (entry.name.startsWith("base/lib")) {
println("Patching: ${entry.name}")
zos.putNextEntry(ZipEntry(entry.name))
zos.closeEntry()
continue
}
*/
println("Adding: ${entry.name}")
zos.putNextEntry(ZipEntry(entry.name))
if (!entry.isDirectory) {
val data = bundleZip.getInputStream(entry).readAllBytes()
zos.write(data)
}
zos.closeEntry()
}
bundleZip.close()
zos.close()
bundle.delete()
signBundle(bundleTmp, bundle)
bundleTmp.delete()
aabTempDir.deleteRecursively()
println("AAB transformed successfully")
}
fun File.sha256(): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(this.readBytes())
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
fun getApks(debug: Boolean): List<File> {
val buildDir = project.buildDir
val apkDir = File(buildDir, "outputs/flutter-apk")
val apks = apkDir.listFiles()!!
val flavor = if (debug) { "debug" } else { "release" }
return apks
.filter { apk -> apk.name.startsWith("app-") && apk.name.endsWith("-$flavor.apk") }
.toList()
}
fun getDebugKeystorePath(): String {
val userHome = System.getProperty("user.home")
val debugKeystore = File(userHome, ".android/debug.keystore")
if (!debugKeystore.exists()) {
throw GradleException("Debug keystore not found at: ${debugKeystore.absolutePath}")
}
return debugKeystore.absolutePath
}
fun getDefaultAndroidSdkPath(): String? {
val os = System.getProperty("os.name").lowercase()
val userHome = System.getProperty("user.home")
val zipAlign = File("/usr/bin/zipalign")
if (zipAlign.exists()) {
return "/usr/bin"
}
return when {
os.contains("win") ->
"$userHome\\AppData\\Local\\Android\\Sdk"
os.contains("mac") ->
"$userHome/Library/Android/sdk"
os.contains("linux") ->
"$userHome/Android/Sdk"
else -> null
}
}
fun findToolInPath(toolName: String): String? {
val pathEnvironment = System.getenv("PATH")
val pathDirs = pathEnvironment.split(File.pathSeparator)
val executableNames = when {
System.getProperty("os.name").lowercase().contains("win") ->
listOf("$toolName.exe", toolName)
else ->
listOf(toolName)
}
for (pathDir in pathDirs) {
for (execName in executableNames) {
val possibleTool = File(pathDir, execName)
if (possibleTool.exists() && possibleTool.canExecute()) {
return possibleTool.absolutePath
}
}
}
return null
}
fun findToolInSdkPath(toolName: String): String? {
var androidHome : String? = System.getenv("ANDROID_HOME")
?: System.getenv("ANDROID_SDK_ROOT")
if (androidHome == null) androidHome = getDefaultAndroidSdkPath()
if (androidHome != null) {
val buildTools = File(androidHome, "build-tools")
if (buildTools.exists()) {
val latestVersion = buildTools.listFiles()
?.filter { it.isDirectory }
?.filter { it.name != "debian" }
?.maxByOrNull { it.name }
if (latestVersion != null) {
val toolExec = File(latestVersion, toolName)
if (toolExec.exists()) {
return toolExec.absolutePath
}
}
} else {
val toolExec = File(androidHome, toolName)
if (toolExec.exists()) {
return toolExec.absolutePath
}
}
}
if (!toolName.contains(".exe")) {
val exeTool = findToolInSdkPath("$toolName.exe")
if (exeTool != null) return exeTool
}
if (!toolName.contains(".sh")) {
val shTool = findToolInSdkPath("$toolName.sh")
if (shTool != null) return shTool
}
if (!toolName.contains(".bat")) {
val batTool = findToolInSdkPath("$toolName.bat")
if (batTool != null) return batTool
}
return null
}
fun signWithDebugKey(input: File, output: File) {
val debugKeystore = getDebugKeystorePath()
val debugKeystorePassword = "android"
val debugKeyAlias = "androiddebugkey"
val debugKeyPassword = "android"
val zipAlign: String = findToolInSdkPath("zipalign")
?: throw Exception("Could not find zipalign in ANDROID_SDK")
val apksigner: String = findToolInSdkPath("apksigner")
?: throw Exception("Could not find zipalign in ANDROID_SDK")
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
exec {
commandLine(
apksigner, "sign",
"--ks", debugKeystore,
"--ks-pass", "pass:$debugKeystorePassword",
"--ks-key-alias", debugKeyAlias,
"--key-pass", "pass:$debugKeyPassword",
output.absolutePath
)
}
println("APK signed and aligned successfully")
}
fun signWithReleaseKey(input: File, output: File) {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (!propsFile.exists()) {
throw Exception("Release keystore not found!")
}
val props = loadProperties(propsFile)
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
val releaseKeystorePassword = props["storePassword"] as String
val releaseKeyAlias = props["keyAlias"] as String
val releaseKeyPassword = props["keyPassword"] as String
val zipAlign: String = findToolInSdkPath("zipalign")
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
val apksigner: String = findToolInSdkPath("apksigner")
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
exec {
commandLine(
apksigner, "sign",
"--ks", releaseKeystore,
"--ks-pass", "pass:$releaseKeystorePassword",
"--ks-key-alias", releaseKeyAlias,
"--key-pass", "pass:$releaseKeyPassword",
output.absolutePath
)
}
println("APK signed and aligned successfully")
}
fun signBundle(input: File, output: File) {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (!propsFile.exists()) {
throw Exception("Release keystore not found!")
}
val props = loadProperties(propsFile)
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
val releaseKeystorePassword = props["storePassword"] as String
val releaseKeyAlias = props["keyAlias"] as String
val releaseKeyPassword = props["keyPassword"] as String
// val zipAlign: String = findToolInSdkPath("zipalign")
// ?: throw Exception("Could not find zipalign in ANDROID_SDK")
val jarsigner: String = findToolInPath("jarsigner")
?: throw Exception("Could not find jarsigner in PATH")
/*
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
*/
input.copyTo(output, true)
exec {
// -keystore $KEYSTORE -storetype $STORETYPE -storepass $STOREPASS -digestalg SHA1 -sigalg SHA256withRSA application.zip $KEYALIAS
commandLine(
jarsigner,
"-verbose",
"-sigalg", "SHA256withRSA",
"-digestalg", "SHA-256",
"-keystore", releaseKeystore,
"-storepass", releaseKeystorePassword,
output.absolutePath,
releaseKeyAlias
)
}
println("AAB signed and aligned successfully")
}

View File

@@ -5,18 +5,12 @@
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application
android:name=".AppMain"
android:icon="@mipmap/launcher_icon">
<service
android:name=".WearSyncForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<activity
android:name=".MainActivity"
android:exported="true"
@@ -41,7 +35,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_ace"
android:roundIcon="@mipmap/ic_ace_round" >
<intent-filter>
@@ -55,7 +49,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_ace_f"
android:roundIcon="@mipmap/ic_ace_f_round" >
<intent-filter>
@@ -69,7 +63,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_bi"
android:roundIcon="@mipmap/ic_bi_round" >
<intent-filter>
@@ -83,7 +77,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_bi_f"
android:roundIcon="@mipmap/ic_bi_f_round" >
<intent-filter>
@@ -97,7 +91,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_cactus"
android:roundIcon="@mipmap/ic_cactus_round" >
<intent-filter>
@@ -111,7 +105,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_cc"
android:roundIcon="@mipmap/ic_cc_round" >
<intent-filter>
@@ -125,7 +119,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_enby"
android:roundIcon="@mipmap/ic_enby_round" >
<intent-filter>
@@ -139,7 +133,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_enby_f"
android:roundIcon="@mipmap/ic_enby_f_round" >
<intent-filter>
@@ -153,7 +147,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_fidesz"
android:roundIcon="@mipmap/ic_fidesz_round" >
<intent-filter>
@@ -167,7 +161,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_filc"
android:roundIcon="@mipmap/ic_filc_round" >
<intent-filter>
@@ -181,7 +175,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_filco"
android:roundIcon="@mipmap/ic_filco_round" >
<intent-filter>
@@ -195,7 +189,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_galaxy"
android:roundIcon="@mipmap/ic_galaxy_round" >
<intent-filter>
@@ -209,7 +203,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_gay"
android:roundIcon="@mipmap/ic_gay_round" >
<intent-filter>
@@ -223,7 +217,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_gay_f"
android:roundIcon="@mipmap/ic_gay_f_round" >
<intent-filter>
@@ -237,7 +231,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_half_firka_2"
android:roundIcon="@mipmap/ic_half_firka_2_round" >
<intent-filter>
@@ -251,7 +245,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_kreta"
android:roundIcon="@mipmap/ic_kreta_round" >
<intent-filter>
@@ -265,7 +259,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lesb"
android:roundIcon="@mipmap/ic_lesb_round" >
<intent-filter>
@@ -279,7 +273,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lesb_f"
android:roundIcon="@mipmap/ic_lesb_f_round" >
<intent-filter>
@@ -293,7 +287,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lgbtq"
android:roundIcon="@mipmap/ic_lgbtq_round" >
<intent-filter>
@@ -307,7 +301,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lgbtq_f"
android:roundIcon="@mipmap/ic_lgbtq_f_round" >
<intent-filter>
@@ -321,7 +315,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lgbtqp"
android:roundIcon="@mipmap/ic_lgbtqp_round" >
<intent-filter>
@@ -335,7 +329,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lgbtqp_f"
android:roundIcon="@mipmap/ic_lgbtqp_f_round" >
<intent-filter>
@@ -349,7 +343,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_lidl"
android:roundIcon="@mipmap/ic_lidl_round" >
<intent-filter>
@@ -363,7 +357,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_mkkp"
android:roundIcon="@mipmap/ic_mkkp_round" >
<intent-filter>
@@ -377,7 +371,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_nuke"
android:roundIcon="@mipmap/ic_nuke_round" >
<intent-filter>
@@ -391,7 +385,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_modern"
android:roundIcon="@mipmap/ic_modern_round" >
<intent-filter>
@@ -405,7 +399,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_o1g"
android:roundIcon="@mipmap/ic_o1g_round" >
<intent-filter>
@@ -419,7 +413,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_old"
android:roundIcon="@mipmap/ic_old_round" >
<intent-filter>
@@ -433,7 +427,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_paper"
android:roundIcon="@mipmap/ic_paper_round" >
<intent-filter>
@@ -447,7 +441,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_pear"
android:roundIcon="@mipmap/ic_pear_round" >
<intent-filter>
@@ -461,7 +455,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_pixel"
android:roundIcon="@mipmap/ic_pixel_round" >
<intent-filter>
@@ -475,7 +469,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_pixelized"
android:roundIcon="@mipmap/ic_pixelized_round" >
<intent-filter>
@@ -489,7 +483,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_pride"
android:roundIcon="@mipmap/ic_pride_round" >
<intent-filter>
@@ -503,7 +497,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_proto"
android:roundIcon="@mipmap/ic_proto_round" >
<intent-filter>
@@ -517,7 +511,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_refilc"
android:roundIcon="@mipmap/ic_refilc_round" >
<intent-filter>
@@ -531,7 +525,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_refulc"
android:roundIcon="@mipmap/ic_refulc_round" >
<intent-filter>
@@ -545,7 +539,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_repont"
android:roundIcon="@mipmap/ic_repont_round" >
<intent-filter>
@@ -559,7 +553,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_szivacs"
android:roundIcon="@mipmap/ic_szivacs_round" >
<intent-filter>
@@ -573,7 +567,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_tisza"
android:roundIcon="@mipmap/ic_tisza_round" >
<intent-filter>
@@ -587,7 +581,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_trans"
android:roundIcon="@mipmap/ic_trans_round" >
<intent-filter>
@@ -601,7 +595,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_trans_f"
android:roundIcon="@mipmap/ic_trans_f_round" >
<intent-filter>
@@ -615,7 +609,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_void_icon"
android:roundIcon="@mipmap/ic_void_icon_round" >
<intent-filter>
@@ -629,7 +623,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_xmas1"
android:roundIcon="@mipmap/ic_xmas1_round" >
<intent-filter>
@@ -643,7 +637,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_xmas2"
android:roundIcon="@mipmap/ic_xmas2_round" >
<intent-filter>
@@ -657,7 +651,7 @@
android:targetActivity=".MainActivity"
android:exported="true"
android:enabled="false"
android:icon="@mipmap/launcher_icon"
android:icon="@mipmap/ic_xmas3"
android:roundIcon="@mipmap/ic_xmas3_round" >
<intent-filter>

View File

@@ -1,5 +1,99 @@
package app.firka.naplo
import android.annotation.SuppressLint
import android.app.Application
import android.os.Build
import android.util.Log
import org.brotli.dec.BrotliInputStream
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.security.MessageDigest
import java.util.zip.ZipFile
class AppMain : Application() {}
class AppMain : Application() {
private fun File.sha256(): String {
if (!exists()) return "0000000000000000000000000000000000000000000000000000000000000000"
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(this.readBytes())
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
@SuppressLint("UnsafeDynamicallyLoadedCode")
override fun onCreate() {
super.onCreate()
var useUncompressedLibs = false
val abi = Build.SUPPORTED_ABIS[0]
val apks = File(applicationInfo.nativeLibraryDir, "../..").absoluteFile
.listFiles()!!
.filter { file -> file.name.endsWith(".apk") }
.toList()
var nativesApkN: ZipFile? = null
for (apk in apks) {
if (nativesApkN != null) break
val zip = ZipFile(apk)
val entries = zip.entries()
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
if (entry.name.endsWith("$abi/index.so")) {
zip.close()
nativesApkN = ZipFile(apk)
break
}
if (entry.name.endsWith("$abi/libflutter.so")) {
useUncompressedLibs = true
break
}
}
zip.close()
}
if (useUncompressedLibs) {
return;
}
if (nativesApkN == null) {
throw Exception("Can't find native libraries")
}
val nativesApk: ZipFile = nativesApkN
val compressedLibsIndex = nativesApk.getInputStream(
nativesApk.getEntry("lib/$abi/index.so")
)
val compressedLibs = JSONObject(compressedLibsIndex.readBytes().toString(Charsets.UTF_8))
for (so in compressedLibs.keys()) {
val soFile = File(cacheDir, so)
if (soFile.sha256() == compressedLibs.getString(so)) {
System.load(soFile.absolutePath)
return
}
Log.d("AppMain", "Decompressing: $so")
val brInput = nativesApk.getInputStream(
nativesApk.getEntry("lib/$abi/${so.replace(".so", "-br.so")}")
)
val soOutput = FileOutputStream(soFile)
val brIn = BrotliInputStream(brInput)
brIn.copyTo(soOutput)
brInput.close()
soOutput.close()
System.load(soFile.absolutePath)
}
}
}

View File

@@ -1,28 +1,19 @@
package app.firka.naplo
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.glance.appwidget.updateAll
import app.firka.naplo.glance.TimetableWidget
import app.firka.naplo.glance.TimetableWidgetReceiver
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlin.system.exitProcess
class MainActivity : FlutterActivity() {
private val channel = "firka.app/main"
private val wearSyncChannel = "app.firka/wear_sync"
private fun forceIconUpdate() {
try {
@@ -39,57 +30,6 @@ class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, wearSyncChannel).setMethodCallHandler { call, result ->
when (call.method) {
"startWearSyncService" -> {
val args = call.arguments as? Map<*, *>
val cachePath = args?.get("cachePath") as? String
val appDirPath = args?.get("appDirPath") as? String
if (cachePath != null && appDirPath != null) {
val messenger = flutterEngine.dartExecutor.binaryMessenger
val ch = MethodChannel(messenger, wearSyncChannel)
ch.invokeMethod("getLocalizedString", "wearSyncNotificationTitle", object : MethodChannel.Result {
override fun success(titleResult: Any?) {
val title = titleResult as? String ?: "Syncing with watch"
ch.invokeMethod("getLocalizedString", "wearSyncNotificationText", object : MethodChannel.Result {
override fun success(textResult: Any?) {
val text = textResult as? String ?: ""
val intent = Intent(this@MainActivity, WearSyncForegroundService::class.java).apply {
action = WearSyncForegroundService.ACTION_START
putExtra(WearSyncForegroundService.EXTRA_CACHE_PATH, cachePath)
putExtra(WearSyncForegroundService.EXTRA_APP_DIR_PATH, appDirPath)
putExtra(WearSyncForegroundService.EXTRA_NOTIFICATION_TITLE, title)
putExtra(WearSyncForegroundService.EXTRA_NOTIFICATION_TEXT, text)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
result.success(null)
}
override fun error(code: String, msg: String?, details: Any?) { result.success(null) }
override fun notImplemented() { result.success(null) }
})
}
override fun error(code: String, msg: String?, details: Any?) { result.error(code, msg, details) }
override fun notImplemented() { result.notImplemented() }
})
} else {
result.error("INVALID_ARGS", "cachePath and appDirPath required", null)
}
}
"stopWearSyncService" -> {
val intent = Intent(this, WearSyncForegroundService::class.java).apply {
action = WearSyncForegroundService.ACTION_STOP
}
startService(intent)
result.success(null)
}
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel).setMethodCallHandler {
call, result ->
when (call.method) {
@@ -157,29 +97,7 @@ class MainActivity : FlutterActivity() {
} catch (e: Exception) {
e.printStackTrace()
}
result.success(true)
}
"refreshTimetableWidget" -> {
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
try {
val appContext = context.applicationContext
val appWidgetManager = AppWidgetManager.getInstance(appContext)
val componentName = ComponentName(appContext, TimetableWidgetReceiver::class.java)
val ids = appWidgetManager.getAppWidgetIds(componentName)
if (ids.isNotEmpty()) {
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
}
appContext.sendBroadcast(intent)
}
TimetableWidget().updateAll(appContext)
result.success(true)
} catch (e: Exception) {
result.error("refresh_failed", e.message, null)
}
}
result.success(true)
}
else -> {
result.notImplemented()

View File

@@ -1,221 +0,0 @@
package app.firka.naplo
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import java.io.ByteArrayInputStream
import java.io.ObjectInputStream
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.Wearable
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.embedding.engine.loader.FlutterLoader
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.delay
/**
* Foreground service that keeps the app able to respond to Wear OS sync requests.
* When the watch sends request_sync, starts a Dart background isolate to fetch data,
* then reads the cache file and sends sync_data to the watch.
*/
class WearSyncForegroundService : Service(), MessageClient.OnMessageReceivedListener {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var cachePath: String? = null
private var appDirPath: String? = null
private val channelId = "firka_wear_sync"
private val notificationId = 4001
private var notificationTitle: String = "Syncing with watch"
private var notificationText: String = ""
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> {
cachePath = intent.getStringExtra(EXTRA_CACHE_PATH)
appDirPath = intent.getStringExtra(EXTRA_APP_DIR_PATH)
notificationTitle = intent.getStringExtra(EXTRA_NOTIFICATION_TITLE) ?: "Syncing with watch"
notificationText = intent.getStringExtra(EXTRA_NOTIFICATION_TEXT) ?: ""
startForegroundWithNotification()
Wearable.getMessageClient(this@WearSyncForegroundService)
.addListener(this@WearSyncForegroundService)
}
ACTION_STOP -> {
stopForegroundService()
return START_NOT_STICKY
}
}
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
try {
Wearable.getMessageClient(this@WearSyncForegroundService)
.removeListener(this@WearSyncForegroundService)
.addOnCompleteListener { }
} catch (_: Exception) { }
scope.cancel()
super.onDestroy()
}
override fun onMessageReceived(messageEvent: MessageEvent) {
if (messageEvent.path != PATH_WATCH_CONNECTIVITY ||
!isRequestSyncPayload(messageEvent.data)
) return
val cPath = cachePath
val aPath = appDirPath
if (cPath == null || aPath == null) return
scope.launch {
runSyncInBackground(cPath, aPath)
}
}
/**
* watch_connectivity plugin sends with path "watch_connectivity" and serializes the message
* map with Java ObjectOutputStream. Parse payload and check for id == "request_sync".
*/
private fun isRequestSyncPayload(data: ByteArray?): Boolean {
if (data == null || data.isEmpty()) return false
return try {
ObjectInputStream(ByteArrayInputStream(data)).use { ois ->
val map = ois.readObject()
if (map is Map<*, *>) map["id"] == "request_sync" else false
}
} catch (_: Exception) {
false
}
}
private fun startForegroundWithNotification() {
val notification = buildNotification()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(notificationId, notification, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
@Suppress("DEPRECATION")
startForeground(notificationId, notification)
}
}
private fun buildNotification(): Notification {
val pendingIntent = PendingIntent.getActivity(
this,
0,
packageManager.getLaunchIntentForPackage(packageName),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
return NotificationCompat.Builder(this, channelId)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Wear sync",
NotificationManager.IMPORTANCE_LOW
).apply { setShowBadge(false) }
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
.createNotificationChannel(channel)
}
}
private fun stopForegroundService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@Suppress("DEPRECATION")
stopForeground(true)
}
stopSelf()
}
private suspend fun runSyncInBackground(cPath: String, aPath: String) = withContext(Dispatchers.Default) {
val flutterLoader = FlutterLoader()
if (!flutterLoader.initialized()) {
withContext(Dispatchers.Main) {
flutterLoader.startInitialization(applicationContext)
flutterLoader.ensureInitializationComplete(applicationContext, null)
}
}
val (engine, bgChannel) = withContext(Dispatchers.Main) {
val eng = FlutterEngine(applicationContext)
val entrypoint = DartExecutor.DartEntrypoint(
flutterLoader.findAppBundlePath(),
"package:firka/services/wear_sync_background.dart",
"wearSyncBackgroundEntrypoint"
)
eng.dartExecutor.executeDartEntrypoint(entrypoint)
val ch = MethodChannel(eng.dartExecutor.binaryMessenger, "app.firka/wear_sync_background")
Pair(eng, ch)
}
val completer = CompletableDeferred<Unit>()
delay(500)
withContext(Dispatchers.Main) {
bgChannel.invokeMethod("request_sync", mapOf(
"cachePath" to cPath,
"appDirPath" to aPath
), object : MethodChannel.Result {
override fun success(result: Any?) {
completer.complete(Unit)
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
Log.e(TAG, "request_sync error: $errorCode $errorMessage")
completer.complete(Unit)
}
override fun notImplemented() {
completer.complete(Unit)
}
})
}
try {
withTimeout(30_000) {
completer.await()
}
} catch (_: kotlinx.coroutines.TimeoutCancellationException) {
Log.w(TAG, "Wear sync isolate timed out")
}
withContext(Dispatchers.Main) {
engine.destroy()
}
}
companion object {
private const val TAG = "WearSyncService"
const val ACTION_START = "app.firka.naplo.WearSyncForegroundService.START"
const val ACTION_STOP = "app.firka.naplo.WearSyncForegroundService.STOP"
const val EXTRA_CACHE_PATH = "cachePath"
const val EXTRA_APP_DIR_PATH = "appDirPath"
const val EXTRA_NOTIFICATION_TITLE = "notificationTitle"
const val EXTRA_NOTIFICATION_TEXT = "notificationText"
private const val PATH_WATCH_CONNECTIVITY = "watch_connectivity"
}
}

View File

@@ -18,7 +18,7 @@ import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import app.firka.naplo.model.Colors
import app.firka.naplo.glance.WidgetLesson
import app.firka.naplo.model.Lesson
import java.time.format.DateTimeFormatterBuilder
val hhmm = DateTimeFormatterBuilder()
@@ -26,12 +26,8 @@ val hhmm = DateTimeFormatterBuilder()
.toFormatter()
@Composable
fun LessonCard(
lesson: WidgetLesson,
colors: Colors,
modifier: GlanceModifier = GlanceModifier,
roomBadgeWidthDp: Float = 48f,
) {
fun LessonCard(lesson: Lesson, colors: Colors,
modifier: GlanceModifier = GlanceModifier) {
Box(modifier =
modifier
.fillMaxWidth()
@@ -42,7 +38,7 @@ fun LessonCard(
var bgColor = colors.a15p
var fgColor = colors.textSecondary
if (lesson.substituteTeacher != null) {
if (lesson.substituteTeacher == null) {
bgColor = colors.warning15p
fgColor = colors.warningText
}
@@ -50,21 +46,9 @@ fun LessonCard(
Box(modifier = GlanceModifier.padding(12.dp)) {
Row {
val badgeStyle = TextStyle(
color = ColorProvider(colors.textSecondary, colors.textSecondary),
fontSize = 14.sp,
fontWeight = FontWeight.Bold
)
val badgePadding = GlanceModifier.padding(8.dp, 4.dp)
val lessonNumberBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(24.dp)
val roomBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(roomBadgeWidthDp.dp)
Row(modifier = GlanceModifier.width(226.dp), verticalAlignment = Alignment.CenterVertically) {
if (lesson.lessonNumber != null) {
Box(
modifier = lessonNumberBadgeModifier.background(bgColor),
contentAlignment = Alignment.Center,
) {
Box(modifier = GlanceModifier.cornerRadius(16.dp).background(bgColor)) {
Text(
lesson.lessonNumber.toString(),
style = TextStyle(
@@ -72,7 +56,7 @@ fun LessonCard(
fontSize = 14.sp,
fontWeight = FontWeight.Bold
),
modifier = GlanceModifier.padding(4.dp, 4.dp),
modifier = GlanceModifier.padding(8.dp, 4.dp),
)
}
Spacer(modifier = GlanceModifier.width(4.dp))
@@ -88,6 +72,8 @@ fun LessonCard(
)
}
// Spacer(modifier = GlanceModifier.width(10.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
lesson.start.format(hhmm),
@@ -98,15 +84,24 @@ fun LessonCard(
),
)
Spacer(modifier = GlanceModifier.width(8.dp))
val roomName = (lesson.roomName ?: "N/A").take(5)
Box(
modifier = roomBadgeModifier.background(colors.a15p),
contentAlignment = Alignment.Center,
) {
Box(modifier = GlanceModifier.cornerRadius(16.dp).background(colors.a15p)) {
var roomName = "N/A";
if (lesson.roomName != null) {
roomName = lesson.roomName!!;
}
if (roomName.length < 2) {
roomName = " $roomName"
}
Text(
roomName,
style = badgeStyle,
modifier = GlanceModifier.padding(4.dp, 4.dp),
style = TextStyle(
color = ColorProvider(colors.textSecondary, colors.textSecondary),
fontSize = 14.sp,
fontWeight = FontWeight.Bold
),
modifier = GlanceModifier.padding(8.dp, 4.dp),
)
}
}

View File

@@ -9,10 +9,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.LocalSize
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.provideContent
import androidx.glance.appwidget.SizeMode
import androidx.glance.background
import androidx.glance.color.ColorProvider
import androidx.glance.currentState
@@ -28,9 +26,7 @@ import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import app.firka.naplo.model.Colors
import app.firka.naplo.glance.WidgetLesson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import app.firka.naplo.model.Lesson
import org.json.JSONObject
import java.io.File
import java.time.LocalDate
@@ -41,51 +37,20 @@ class TimetableWidget : GlanceAppWidget() {
override val stateDefinition: GlanceStateDefinition<*>?
get() = HomeWidgetGlanceStateDefinition()
override val sizeMode: SizeMode
get() = SizeMode.Exact
override suspend fun provideGlance(context: Context, id: GlanceId) {
val data = withContext(Dispatchers.IO) {
loadWidgetData(context)
}
provideContent {
GlanceContent(context, currentState(), data)
GlanceContent(context, currentState())
}
}
private fun loadWidgetData(context: Context): WidgetData? {
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
val widgetStateFile = File(appFlutter, "widget_state.json")
if (!widgetStateFile.exists()) return null
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
val colors = Colors(widgetState)
val tt = widgetState.getJSONArray("timetable")
val lessons = mutableListOf<WidgetLesson>()
for (i in 0..<tt.length()) {
lessons.add(WidgetLesson(tt.getJSONObject(i)))
}
val displayDateStr = widgetState.optString("displayDate", "")
val targetDate = if (displayDateStr.isNotEmpty()) {
try {
LocalDate.parse(displayDateStr)
} catch (_: Exception) {
LocalDate.now()
}
} else {
LocalDate.now()
}
val start = LocalDateTime.of(targetDate.year, targetDate.month, targetDate.dayOfMonth, 0, 0)
val end = start.plusHours(23)
val filtered = lessons.filter { it.start.isAfter(start) && it.end.isBefore(end) }
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
return WidgetData(colors, headerText, filtered)
}
@Composable
private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState, data: WidgetData?) {
if (data == null) {
Box(
modifier = GlanceModifier
private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState) {
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
val widgetStateFile = File(appFlutter, "widget_state.json")
if (!widgetStateFile.exists()) {
Box(modifier =
GlanceModifier
.background(Color(0xFFFAFFF0))
.padding(16.dp)
.fillMaxSize(),
@@ -100,67 +65,47 @@ class TimetableWidget : GlanceAppWidget() {
)
)
}
return
}
val size = LocalSize.current
val lessonRowHeightDp = 52f
val scale = lessonRowHeightDp / 52f
val headerHeightDp = 20f * scale
val verticalPaddingDp = 32f * scale
val spacerDp = 4f * scale
val paddingDp = 16f * scale
val availableHeightDp = size.height.value - verticalPaddingDp - headerHeightDp - spacerDp
val maxVisibleLessons = (availableHeightDp / lessonRowHeightDp).toInt().coerceAtLeast(0)
val maxLessons = (maxVisibleLessons.coerceAtMost(16) / 2 * 2).coerceAtLeast(1)
val displayLessons = data.lessons.take(maxLessons)
val lessonChunks = displayLessons.chunked(2)
val showDate = maxLessons > 1
val maxRoomNameLen = displayLessons.maxOfOrNull { (it.roomName ?: "N/A").take(5).length } ?: 0
val roomBadgeWidthDp = if (maxRoomNameLen <= 3) 28f else 48f
val dateSectionHeight = if (showDate) headerHeightDp + spacerDp else 0f
val lessonListHeight = when (val n = displayLessons.size) {
0 -> 0f
else -> n * lessonRowHeightDp + (n - 1) * spacerDp
}
val remainingHeight = (size.height.value - 2 * paddingDp - dateSectionHeight - lessonListHeight).coerceAtLeast(0f)
val verticalPaddingAroundLessons = remainingHeight / 2f
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
val colors = Colors(widgetState)
Box(
modifier = GlanceModifier
.background(data.colors.background)
.padding(paddingDp.dp)
val tt = widgetState.getJSONArray("timetable")
var lessons = mutableListOf<Lesson>()
for (i in 0..<tt.length()) {
lessons.add(Lesson(tt.getJSONObject(i)))
}
val now = LocalDate.now()
val start = LocalDateTime.of(now.year, now.month, now.dayOfMonth, 0, 0)
val end = start.plusHours(23)
lessons = lessons.filter { lesson -> lesson.start.isAfter(start) && lesson.end.isBefore(end) }.toMutableList()
Box(modifier =
GlanceModifier
.background(colors.background)
.padding(16.dp)
.fillMaxSize()
) {
Column {
if (showDate) {
Text(
data.headerText,
style = TextStyle(
color = ColorProvider(data.colors.textSecondary, data.colors.textSecondary),
fontSize = 12.sp,
fontWeight = FontWeight.Medium
)
Text(
"Mai órarend",
style = TextStyle(
color = ColorProvider(colors.textSecondary, colors.textSecondary),
fontSize = 12.sp,
fontWeight = FontWeight.Medium
)
Spacer(modifier = GlanceModifier.height(spacerDp.dp))
)
Spacer(modifier = GlanceModifier.height(4.dp))
for (lesson in lessons) {
LessonCard(lesson, colors)
Spacer(modifier = GlanceModifier.height(4.dp))
}
Spacer(modifier = GlanceModifier.height(verticalPaddingAroundLessons.dp))
for (chunk in lessonChunks) {
Column {
for (lesson in chunk) {
LessonCard(lesson, data.colors, roomBadgeWidthDp = roomBadgeWidthDp)
Spacer(modifier = GlanceModifier.height(spacerDp.dp))
}
}
}
Spacer(modifier = GlanceModifier.height(verticalPaddingAroundLessons.dp))
}
}
}
}
private data class WidgetData(
val colors: Colors,
val headerText: String,
val lessons: List<WidgetLesson>,
)
}

View File

@@ -1,25 +1,7 @@
package app.firka.naplo.glance
import android.appwidget.AppWidgetManager
import android.content.Context
import android.os.Bundle
import HomeWidgetGlanceWidgetReceiver
import androidx.glance.appwidget.GlanceAppWidgetManager
import kotlinx.coroutines.runBlocking
class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>() {
override val glanceAppWidget = TimetableWidget()
override fun onAppWidgetOptionsChanged(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
newOptions: Bundle,
) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
runBlocking {
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
glanceAppWidget.update(context, glanceId)
}
}
}

View File

@@ -1,23 +0,0 @@
package app.firka.naplo.glance
import app.firka.naplo.getIntOrNull
import app.firka.naplo.getStringOrNull
import org.json.JSONObject
import java.time.LocalDateTime
import java.time.format.DateTimeFormatterBuilder
class WidgetLesson(data: JSONObject) {
val formatter = DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
.optionalStart()
.appendLiteral('Z')
.optionalEnd()
.toFormatter()
val name: String = data.getString("Nev")
val start: LocalDateTime = LocalDateTime.parse(data.getString("KezdetIdopont"), formatter)
val end: LocalDateTime = LocalDateTime.parse(data.getString("VegIdopont"), formatter)
val lessonNumber: Int? = data.getIntOrNull("Oraszam")
val roomName: String? = data.getStringOrNull("TeremNeve")
val substituteTeacher: String? = data.getStringOrNull("HelyettesTanarNeve")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@@ -8,7 +8,6 @@
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<item name="android:windowSplashScreenBackground">#7ca120</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
<item name="android:windowSplashScreenIconBackgroundColor">#7ca120</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your

View File

@@ -8,7 +8,6 @@
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<item name="android:windowSplashScreenBackground">#7ca120</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
<item name="android:windowSplashScreenIconBackgroundColor">#7ca120</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your

View File

@@ -1,9 +1,7 @@
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/glance_default_loading_layout"
android:minWidth="250dp"
android:minHeight="93dp"
android:minResizeWidth="180dp"
android:minResizeHeight="93dp"
android:minWidth="300dp"
android:minHeight="100dp"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1800000">
android:updatePeriodMillis="10000">
</appwidget-provider>

View File

@@ -22,8 +22,8 @@ subprojects {
if (plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.library")) {
val androidExtension = extensions.getByName("android") as BaseExtension
androidExtension.apply {
compileSdkVersion(36)
buildToolsVersion = "36.1.0"
compileSdkVersion(35)
buildToolsVersion = "35.0.0"
}
}
if (hasProperty("android")) {
@@ -40,6 +40,9 @@ subprojects {
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)

View File

@@ -1,13 +1,3 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# Disabled for faster config and incremental builds; re-enable if any dependency needs support-library
android.enableJetifier=false
# Build performance (cold and warm)
org.gradle.caching=true
org.gradle.parallel=true
# Configuration cache disabled: Flutter/AGP/Kotlin plugin not fully compatible (KotlinBaseApiPlugin / ProjectServices)
# org.gradle.configuration-cache=true
org.gradle.daemon=true
# Better Kotlin incremental compilation (warm builds)
kotlin.incremental.useClasspathSnapshot=true
android.enableJetifier=true

View File

@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip

View File

@@ -18,9 +18,8 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "8.11.1" apply false
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.1.0" apply false
id("com.android.application") version "8.7.0" apply false
id("org.jetbrains.kotlin.android") version "1.8.22" apply false
}
include(":app")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -1,4 +0,0 @@
<svg width="23" height="18" viewBox="0 0 23 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.8252 0L3.09442 6.29374L2.5175 3.93359C3.26925 3.93359 3.88114 4.15212 4.35317 4.58919C4.8252 5.02625 5.06122 5.6294 5.06122 6.39864C5.06122 7.15039 4.81646 7.76228 4.32695 8.23431C3.85492 8.68886 3.26051 8.91613 2.54372 8.91613C1.80945 8.91613 1.19756 8.68886 0.708046 8.23431C0.236015 7.76228 0 7.15039 0 6.39864C0 6.17136 0.0174826 5.95283 0.0524478 5.74304C0.0874131 5.51576 0.157344 5.25352 0.262239 4.95632C0.367135 4.65912 0.515737 4.26576 0.708046 3.77624L2.22903 0H4.8252ZM11.014 0L9.28327 6.29374L8.70634 3.93359C9.45809 3.93359 10.07 4.15212 10.542 4.58919C11.014 5.02625 11.2501 5.6294 11.2501 6.39864C11.2501 7.15039 11.0053 7.76228 10.5158 8.23431C10.0438 8.68886 9.44935 8.91613 8.73256 8.91613C7.99829 8.91613 7.3864 8.68886 6.89689 8.23431C6.42486 7.76228 6.18884 7.15039 6.18884 6.39864C6.18884 6.17136 6.20633 5.95283 6.24129 5.74304C6.27626 5.51576 6.34619 5.25352 6.45108 4.95632C6.55598 4.65912 6.70458 4.26576 6.89689 3.77624L8.41788 0H11.014Z" fill="#A0D025"/>
<path d="M17.6748 17.832L19.4056 11.5383L19.9825 13.8984C19.2308 13.8984 18.6189 13.6799 18.1468 13.2428C17.6748 12.8058 17.4388 12.2026 17.4388 11.4334C17.4388 10.6816 17.6835 10.0698 18.1731 9.59772C18.6451 9.14317 19.2395 8.9159 19.9563 8.9159C20.6905 8.9159 21.3024 9.14317 21.792 9.59772C22.264 10.0698 22.5 10.6816 22.5 11.4334C22.5 11.6607 22.4825 11.8792 22.4476 12.089C22.4126 12.3163 22.3427 12.5785 22.2378 12.8757C22.1329 13.1729 21.9843 13.5663 21.792 14.0558L20.271 17.832H17.6748ZM11.486 17.832L13.2167 11.5383L13.7937 13.8984C13.0419 13.8984 12.43 13.6799 11.958 13.2428C11.486 12.8058 11.2499 12.2026 11.2499 11.4334C11.2499 10.6816 11.4947 10.0698 11.9842 9.59772C12.4562 9.14317 13.0506 8.9159 13.7674 8.9159C14.5017 8.9159 15.1136 9.14317 15.6031 9.59772C16.0751 10.0698 16.3112 10.6816 16.3112 11.4334C16.3112 11.6607 16.2937 11.8792 16.2587 12.089C16.2237 12.3163 16.1538 12.5785 16.0489 12.8757C15.944 13.1729 15.7954 13.5663 15.6031 14.0558L14.0821 17.832H11.486Z" fill="#A0D025"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -1,4 +0,0 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21.2187 15.3754C21.5637 14.9441 22.1937 14.8741 22.6249 15.2191C23.0562 15.5641 23.1262 16.1941 22.7812 16.6254L18.7812 21.6254C18.6036 21.8474 18.3394 21.9826 18.0556 21.9984C17.7716 22.0142 17.494 21.9086 17.2929 21.7074L15.2929 19.7074C14.9024 19.3169 14.9024 18.6839 15.2929 18.2934C15.6834 17.9028 16.3164 17.9028 16.707 18.2934L17.9159 19.5023L21.2187 15.3754Z" fill="#A0D025"/>
<path d="M10.7998 3.65137C11.146 3.39172 11.5673 3.25098 12 3.25098C12.4327 3.25098 12.854 3.39172 13.2002 3.65137L20.2002 8.90137C20.4484 9.08763 20.6503 9.32886 20.7891 9.60645C20.9279 9.88415 21 10.1905 21 10.501V12.4565C21 12.9796 20.4396 13.3258 19.9346 13.1894C19.4773 13.066 18.9964 13 18.5 13C16.5152 13 14.776 14.0513 13.8089 15.6274C13.6713 15.8515 13.4337 16.001 13.1708 16.001H13H11V19.001C11 19.5314 10.7891 20.04 10.4141 20.415C10.039 20.7901 9.53043 21.001 9 21.001H5C4.46957 21.001 3.96101 20.7901 3.58594 20.415C3.21087 20.04 3 19.5314 3 19.001V10.501C3 10.1905 3.07208 9.88416 3.21094 9.60645C3.34973 9.32885 3.55156 9.08763 3.7998 8.90137L10.7998 3.65137Z" fill="#A0D025"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -1,21 +1,16 @@
flutter_native_splash:
color: "#7ca120"
image: assets/images/logos/splash.png
# Keep image centered instead of fill-scaled (stops icon looking zoomed/cropped)
android_gravity: center
# Dark mode - same color as light mode for consistency
color_dark: "#7ca120"
image_dark: assets/images/logos/splash.png
# Android 12+ uses 960×960 image with logo in 640px circle (generated by codegen) to avoid cropping
android_12:
image: assets/images/logos/splash_android12.png
image: assets/images/logos/splash.png
color: "#7ca120"
color_dark: "#7ca120"
image_dark: assets/images/logos/splash_android12.png
icon_background_color: "#7ca120"
icon_background_color_dark: "#7ca120"
image_dark: assets/images/logos/splash.png
ios: true
web: false

View File

@@ -0,0 +1,42 @@
import 'package:firka/helpers/db/models/generic_cache_model.dart';
import 'package:firka/helpers/db/models/timetable_cache_model.dart';
import 'package:firka/helpers/db/models/token_model.dart';
import 'package:firka/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'test_helpers.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
await resetAppData();
setApiUrls();
group('main', () {
testWidgets('InitializationScreen -> HomeScreen', (tester) async {
final dir = await getApplicationDocumentsDirectory();
var isar = await Isar.open(
[TokenModelSchema, GenericCacheModelSchema, TimetableCacheModelSchema],
inspector: true,
directory: dir.path,
);
isarInit = isar;
await isar.writeTxn(() async {
await isar.tokenModels.put(TokenModel());
});
await tester.pumpWidget(InitializationScreen());
await waitUntil(Duration(minutes: 2), tester, () async {
var ele = find.byKey(const Key('homeScreen'));
return ele.allCandidates.isNotEmpty;
});
});
});
}

View File

@@ -0,0 +1,24 @@
import 'package:firka/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'test_helpers.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
await resetAppData();
setApiUrls();
group('main', () {
testWidgets('InitializationScreen -> LoginScreen', (tester) async {
await tester.pumpWidget(InitializationScreen());
await waitUntil(Duration(minutes: 2), tester, () async {
var ele = find.byKey(const Key('loginScreen'));
return ele.allCandidates.isNotEmpty;
});
});
});
}

View File

@@ -0,0 +1,42 @@
import 'package:firka/helpers/api/consts.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
Future<bool> isWear() async {
const platform = MethodChannel('firka.app/main');
return await platform.invokeMethod("isWear");
}
Future<bool> isPhone() async {
return !(await isWear());
}
Future<void> resetAppData() async {
final isarDir = await getApplicationDocumentsDirectory();
if (await isarDir.exists()) await isarDir.delete(recursive: true);
}
void setApiUrls() {
KretaEndpoints.kretaBase = "localhost:8060";
KretaEndpoints.kretaIdp = "http://localhost:8060";
KretaEndpoints.kretaLoginUrl =
"${KretaEndpoints.kretaIdp}/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fprompt%3Dlogin%26nonce%3DwylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU%26response_type%3Dcode%26code_challenge_method%3DS256%26scope%3Dopenid%2520email%2520offline_access%2520kreta-ellenorzo-webapi.public%2520kreta-eugyintezes-webapi.public%2520kreta-fileservice-webapi.public%2520kreta-mobile-global-webapi.public%2520kreta-dkt-webapi.public%2520kreta-ier-webapi.public%26code_challenge%3DHByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ%26redirect_uri%3Dhttps%253A%252F%252Fmobil.e-kreta.hu%252Fellenorzo-student%252Fprod%252Foauthredirect%26client_id%3Dkreta-ellenorzo-student-mobile-ios%26state%3Dkreta_student_mobile%26suppressed_prompt%3Dlogin";
KretaEndpoints.tokenGrantUrl = "${KretaEndpoints.kretaIdp}/connect/token";
}
Future<void> waitUntil(Duration timeout, WidgetTester tester,
Future<bool> Function() callback) async {
var now = DateTime.now();
while (
now.difference(DateTime.now()).inMilliseconds < timeout.inMilliseconds) {
await tester.pump(Duration(milliseconds: 100));
if (await callback()) {
return;
}
}
throw Exception("waitUntil timed out");
}

View File

@@ -8,23 +8,18 @@ struct CountdownRing: View {
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)
return Double(totalMinutes - remainingMinutes) / Double(totalMinutes)
}
var displayedMinutes: Int {
max(0, remainingMinutes + displayOffset)
remainingMinutes + displayOffset
}
var ringColor: Color {
if clampedRemainingMinutes < 5 { return .red }
if clampedRemainingMinutes < 10 { return .yellow }
if remainingMinutes < 5 { return .red }
if remainingMinutes < 10 { return .yellow }
return .green
}

View File

@@ -3,25 +3,16 @@ import SwiftUI
struct FirkaCard<Content: View>: View {
let content: Content
var isHighlighted: Bool = false
var backgroundColor: Color? = nil
init(
isHighlighted: Bool = false,
backgroundColor: Color? = nil,
@ViewBuilder content: () -> Content
) {
init(isHighlighted: Bool = false, @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))
)
.background(isHighlighted ? Color.green.opacity(0.2) : Color(white: 0.12))
.cornerRadius(12)
}
}

View File

@@ -44,8 +44,6 @@ struct ContentView: View {
}
}
.task {
dataStore.reconcileSharedSessionState()
WatchL10n.shared.reconcileFromSharedState()
dataStore.checkTokenState()
dataStore.loadFromCache()
if dataStore.hasToken {
@@ -56,8 +54,6 @@ struct ContentView: View {
}
.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 {
@@ -69,22 +65,7 @@ struct ContentView: View {
}
}
.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 {
if scenePhase == .active && shouldAutoRefresh && !dataStore.isLoading {
print("[Watch] Data became stale (>10 min), auto-refreshing...")
Task {
await dataStore.refreshAllWithRecovery()
@@ -143,41 +124,22 @@ struct ContentView: View {
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))
VStack(spacing: 16) {
Image(systemName: "iphone.and.arrow.right.inward")
.font(.system(size: 50))
.foregroundColor(.blue)
Text(titleKey.localized)
Text("pair_with_iphone".localized)
.font(.headline)
Text(descriptionKey.localized)
.font(.caption2)
Text("open_firka_on_iphone".localized)
.font(.caption)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal)
if isWatchSystemPaired {
if WCSession.default.isReachable {
Button("sync_button".localized) {
onRequestToken?()
}

View File

@@ -6,10 +6,6 @@
<array>
<string>group.app.firka.firkaa</string>
</array>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)app.firka.shared</string>
</array>
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
<string>$(TeamIdentifierPrefix)app.firka.firkaa</string>
</dict>

View File

@@ -30,7 +30,6 @@ class 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.firka.firkaa"
private var appGroupDefaults: UserDefaults? {
UserDefaults(suiteName: Self.appGroupID)
@@ -46,9 +45,8 @@ class WatchL10n {
var syncWithiPhone: Bool {
didSet {
UserDefaults.standard.set(syncWithiPhone, forKey: syncWithiPhoneKey)
appGroupDefaults?.set(syncWithiPhone, forKey: syncWithiPhoneKey)
if syncWithiPhone {
refreshFromiPhoneAndSharedState()
requestLanguageFromiPhone()
}
}
}
@@ -58,13 +56,7 @@ class WatchL10n {
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)
}
self.syncWithiPhone = UserDefaults.standard.bool(forKey: syncWithiPhoneKey)
appGroupDefaults?.set(currentLanguage.rawValue, forKey: languageKey)
loadStrings()
}
@@ -74,80 +66,18 @@ class WatchL10n {
}
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()
}
}
currentLanguage = language
loadStrings()
WidgetCenter.shared.reloadAllTimelines()
}
func updateFromiPhone(languageCode: String, sharedStateVersion: Int64? = nil) {
func updateFromiPhone(languageCode: String) {
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))
}
setLanguage(language)
}
}
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()
}
@@ -183,20 +113,12 @@ class WatchL10n {
"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",
@@ -276,20 +198,12 @@ class WatchL10n {
"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",
@@ -369,20 +283,12 @@ class WatchL10n {
"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",

View File

@@ -32,8 +32,6 @@ class DataStore {
private let appGroupID = "group.app.firka.firkaa"
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()
@@ -50,73 +48,6 @@ class DataStore {
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() {
@@ -323,31 +254,7 @@ class DataStore {
}
}
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 {
@@ -515,30 +422,24 @@ class DataStore {
let elapsed = Date().timeIntervalSince(lastUpdated)
if elapsed < 60 {
return "time_now".localized
return nil
}
// Minutes
let minutes = Int(elapsed / 60)
if minutes < 60 {
return minutes == 1
? "time_since_minutes_one".localized
: "time_since_minutes_many".localized(minutes)
return minutes == 1 ? "1 perce" : "\(minutes) perce"
}
// Hours
let hours = Int(elapsed / 3600)
if hours < 24 {
return hours == 1
? "time_since_hours_one".localized
: "time_since_hours_many".localized(hours)
return hours == 1 ? "1 órája" : "\(hours) órája"
}
// Days
let days = Int(elapsed / 86400)
return days == 1
? "time_since_days_one".localized
: "time_since_days_many".localized(days)
return days == 1 ? "1 napja" : "\(days) napja"
}
/// Returns true if data is stale (> 1 hour old or never updated)

View File

@@ -4,8 +4,6 @@ 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()
@@ -37,22 +35,6 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
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() {
@@ -110,17 +92,6 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
) {
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
@@ -208,14 +179,6 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
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(
@@ -238,26 +201,14 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
}
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
)
WatchL10n.shared.updateFromiPhone(languageCode: language)
}
}
@@ -271,38 +222,18 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
}
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
)
WatchL10n.shared.updateFromiPhone(languageCode: language)
}
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")
@@ -365,14 +296,8 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
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
)
WatchL10n.shared.updateFromiPhone(languageCode: language)
}
}
},
@@ -404,24 +329,19 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
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!)
}
if incomingSentAtMs > 0,
let currentToken,
!token.isSameAccount(as: currentToken) {
shouldForceAccountSwitch = true
} 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)")
print("[Watch] Ignoring stale token_update without sentAtMs")
return
}
@@ -429,20 +349,14 @@ class WatchConnectivityManager: NSObject, WCSessionDelegate {
try TokenManager.shared.saveToken(
token,
syncToSharedKeychain: false,
syncToICloud: 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 {

View File

@@ -1,5 +1,4 @@
import SwiftUI
import WatchConnectivity
internal import Combine
struct HomeView: View {
@@ -93,10 +92,10 @@ struct HomeView: View {
.disabled(dataStore.isLoading || refreshStatus == .loading)
.padding(.top, 8)
.onChange(of: dataStore.isLoading) { oldValue, newValue in
if newValue && refreshStatus != .loading {
if newValue && refreshStatus == .idle {
wasLoadingFromBackground = true
}
if !newValue && wasLoadingFromBackground && refreshStatus != .loading {
if !newValue && wasLoadingFromBackground && refreshStatus == .idle {
wasLoadingFromBackground = false
if dataStore.error == nil && dataStore.data != nil {
refreshStatus = .success
@@ -111,20 +110,6 @@ struct HomeView: View {
}
}
}
.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 {
@@ -210,20 +195,12 @@ struct HomeView: View {
displayOffset: 1
)
.id("lesson-\(lesson.start.timeIntervalSince1970)")
FirkaCard(
isHighlighted: true,
backgroundColor: lessonCardBackgroundColor(
for: lesson,
isHighlighted: true
)
) {
FirkaCard(isHighlighted: true) {
VStack(alignment: .leading, spacing: 4) {
lessonTitleWithStatus(
lesson,
font: .subheadline,
weight: .semibold,
lineLimit: 2
)
Text(lesson.displayName)
.font(.subheadline)
.fontWeight(.semibold)
.lineLimit(2)
HStack(spacing: 6) {
if let room = lesson.roomName {
@@ -244,15 +221,11 @@ struct HomeView: View {
.font(.caption)
.foregroundColor(.secondary)
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) {
FirkaCard {
HStack {
VStack(alignment: .leading, spacing: 2) {
lessonTitleWithStatus(
next,
font: .subheadline,
weight: .regular,
lineLimit: 2
)
Text(next.displayName)
.font(.subheadline)
if let room = next.roomName {
Text(room)
.font(.caption2)
@@ -278,16 +251,11 @@ struct HomeView: View {
.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)))
}()
let remaining = max(0, Int(next.start.timeIntervalSince(now) / 60))
HStack(spacing: 10) {
CountdownRing(
totalMinutes: totalBreakMinutes,
totalMinutes: 15,
remainingMinutes: remaining,
label: "minutes".localized,
size: 56,
@@ -296,14 +264,12 @@ struct HomeView: View {
)
.id("break-\(next.start.timeIntervalSince1970)")
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) {
FirkaCard {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
Text("next_lesson".localized(next.displayName))
.font(.subheadline)
.fontWeight(.semibold)
.lineLimit(2)
}
Text("next_lesson".localized(next.displayName))
.font(.subheadline)
.fontWeight(.semibold)
.lineLimit(2)
HStack(spacing: 6) {
if let room = next.roomName {
@@ -329,14 +295,10 @@ struct HomeView: View {
.font(.caption)
.foregroundColor(.secondary)
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: first)) {
FirkaCard {
VStack(alignment: .leading, spacing: 8) {
lessonTitleWithStatus(
first,
font: .headline,
weight: .regular,
lineLimit: 2
)
Text(first.displayName)
.font(.headline)
HStack {
if let room = first.roomName {
@@ -379,14 +341,10 @@ struct HomeView: View {
.foregroundColor(.secondary)
.padding(.top, 8)
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: nextLesson)) {
FirkaCard {
HStack {
lessonTitleWithStatus(
nextLesson,
font: .subheadline,
weight: .regular,
lineLimit: 2
)
Text(nextLesson.displayName)
.font(.subheadline)
Spacer()
Text(nextLesson.start, style: .time)
.font(.caption)
@@ -461,46 +419,6 @@ struct HomeView: View {
}
}
@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
@@ -520,36 +438,17 @@ struct HomeView: View {
// 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)
Image(systemName: "iphone.and.arrow.right.inward")
.font(.system(size: 44))
.foregroundColor(.blue)
Text(noTokenTitleKey.localized)
Text("pair_with_iphone".localized)
.font(.headline)
.multilineTextAlignment(.center)
Text(noTokenDescriptionKey.localized)
Text("open_firka_on_iphone".localized)
.font(.caption)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)

View File

@@ -289,7 +289,7 @@ struct ReauthRequiredView: View {
try TokenManager.shared.saveToken(
token,
syncToSharedKeychain: false,
syncToICloud: false,
forceAccountSwitch: shouldForceAccountSwitch
)

View File

@@ -69,10 +69,6 @@ struct SettingsView: View {
private func logout() {
TokenManager.shared.deleteToken()
_ = SharedSessionStateManager.shared.publishState(
hasAnyAccount: false,
activeStudentIdNorm: nil
)
DataStore.shared.clearAll()
}
}

View File

@@ -308,17 +308,17 @@ struct TimetableView: View {
VStack(alignment: .leading, spacing: 4) {
HStack {
HStack(spacing: 4) {
Text(lesson.displayName)
.font(.subheadline)
.fontWeight(.medium)
.lineLimit(1)
Text(lesson.displayName)
.font(.subheadline)
.fontWeight(.medium)
.lineLimit(1)
.strikethrough(lesson.isCancelled)
.opacity(lesson.isCancelled ? 0.5 : 1)
if let statusIcon = lessonStatusIconName(for: lesson) {
Image(systemName: statusIcon)
.font(.caption2)
.foregroundColor(lessonStatusColor(for: lesson))
}
if lesson.isSubstitution {
Image(systemName: "exclamationmark.circle.fill")
.font(.caption2)
.foregroundColor(.orange)
}
Spacer()
@@ -340,23 +340,11 @@ struct TimetableView: View {
}
.font(.caption2)
.foregroundColor(.secondary)
.opacity(lesson.isCancelled ? 0.5 : 1)
}
}
}
}
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
.opacity(lesson.isCancelled ? 0.6 : 1)
}
}

View File

@@ -28,11 +28,6 @@ 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"
@@ -41,49 +36,9 @@ struct TimetableProvider: AppIntentTimelineProvider {
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
return Self.dateFormatter.date(from: dateString)
}
func placeholder(in context: Context) -> TimetableEntry {
@@ -221,8 +176,9 @@ struct TimetableProvider: AppIntentTimelineProvider {
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) {
if let nextSchoolDayDateString = data?.timetable.nextSchoolDayDate,
let nextSchoolDayDate = parseNextSchoolDayDate(nextSchoolDayDateString) {
let nextSchoolDay = calendar.startOfDay(for: nextSchoolDayDate)
let dayBeforeNextSchoolDay = calendar.date(byAdding: .day, value: -1, to: nextSchoolDay)!
if dayBeforeNextSchoolDay > now {
@@ -294,47 +250,93 @@ struct TimetableProvider: AppIntentTimelineProvider {
}
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 lessons = data.timetable.today
var isNextDay = false
var candidates: [LessonCandidate] = []
if let firstTodayLesson = lessons.first {
let todayLessonDay = calendar.startOfDay(for: firstTodayLesson.start)
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 entryDay > todayLessonDay {
lessons = data.timetable.tomorrow
if let firstTomorrowLesson = lessons.first {
let tomorrowLessonDay = calendar.startOfDay(for: firstTomorrowLesson.start)
isNextDay = entryDay < tomorrowLessonDay
}
} else {
let lastLesson = lessons.last
if let last = lastLesson, date > last.end {
lessons = data.timetable.tomorrow
isNextDay = true
}
}
if candidate.day == entryDay, let lastLesson = candidate.lessons.last {
return date <= lastLesson.end
} else {
lessons = data.timetable.tomorrow
if !lessons.isEmpty {
isNextDay = true
}
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
if lessons.isEmpty {
if let nextSchoolDayLessons = data.timetable.nextSchoolDay, !nextSchoolDayLessons.isEmpty {
if let nextSchoolDayDate = parseNextSchoolDayDate(data.timetable.nextSchoolDayDate) {
let nextSchoolDay = calendar.startOfDay(for: nextSchoolDayDate)
let dayBeforeNextSchoolDay = calendar.date(byAdding: .day, value: -1, to: nextSchoolDay)!
if entryDay == nextSchoolDay {
let currentLesson = nextSchoolDayLessons.first { lesson in
return date >= lesson.start && date <= lesson.end
}
let nextLesson = nextSchoolDayLessons.first { $0.start > date }
return TimetableEntry(
date: date,
configuration: configuration,
data: data,
lessons: nextSchoolDayLessons,
currentLesson: currentLesson,
nextLesson: nextLesson,
isNextDay: false,
isNextSchoolDay: false,
nextSchoolDayDateString: nil,
breakInfo: nil,
state: .normal,
debugInfo: WidgetData.lastError
)
}
if entryDay == dayBeforeNextSchoolDay {
return TimetableEntry(
date: date,
configuration: configuration,
data: data,
lessons: nextSchoolDayLessons,
currentLesson: nil,
nextLesson: nextSchoolDayLessons.first,
isNextDay: true,
isNextSchoolDay: false,
nextSchoolDayDateString: nil,
breakInfo: nil,
state: .normal,
debugInfo: WidgetData.lastError
)
}
}
return TimetableEntry(
date: date,
configuration: configuration,
data: data,
lessons: nextSchoolDayLessons,
currentLesson: nil,
nextLesson: nextSchoolDayLessons.first,
isNextDay: false,
isNextSchoolDay: true,
nextSchoolDayDateString: data.timetable.nextSchoolDayDate,
breakInfo: nil,
state: .normal,
debugInfo: WidgetData.lastError
)
}
return TimetableEntry(
@@ -344,23 +346,15 @@ struct TimetableProvider: AppIntentTimelineProvider {
lessons: [],
currentLesson: nil,
nextLesson: nil,
isNextDay: false,
isNextDay: isNextDay,
isNextSchoolDay: false,
nextSchoolDayDateString: nil,
breakInfo: nil,
state: hadLessonsTodayButFinished ? .noMoreLessons : .unavailable,
state: isNextDay ? .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
}
@@ -374,8 +368,8 @@ struct TimetableProvider: AppIntentTimelineProvider {
currentLesson: currentLesson,
nextLesson: nextLesson,
isNextDay: isNextDay,
isNextSchoolDay: isNextSchoolDay,
nextSchoolDayDateString: nextSchoolDayDateString,
isNextSchoolDay: false,
nextSchoolDayDateString: nil,
breakInfo: nil,
state: .normal,
debugInfo: WidgetData.lastError

View File

@@ -117,8 +117,8 @@ struct TimetableMediumView: View {
var hasActiveBreak: Bool {
let checkDate = entry.date
for (currentLesson, nextLesson) in zip(entry.lessons, entry.lessons.dropFirst()) {
if checkDate > currentLesson.end && checkDate < nextLesson.start {
for i in 0..<entry.lessons.count - 1 {
if checkDate > entry.lessons[i].end && checkDate < entry.lessons[i + 1].start {
return true
}
}
@@ -209,8 +209,8 @@ struct TimetableLargeView: View {
var hasActiveBreak: Bool {
let checkDate = entry.date
for (currentLesson, nextLesson) in zip(entry.lessons, entry.lessons.dropFirst()) {
if checkDate > currentLesson.end && checkDate < nextLesson.start {
for i in 0..<entry.lessons.count - 1 {
if checkDate > entry.lessons[i].end && checkDate < entry.lessons[i + 1].start {
return true
}
}

View File

@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 70;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
@@ -12,13 +12,13 @@
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 */; };
4F5824802F35468E00B92EA7 /* iCloudTokenManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F58247F2F35468D00B92EA7 /* iCloudTokenManager.swift */; };
4F5824812F35468E00B92EA7 /* iCloudTokenManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F58247F2F35468D00B92EA7 /* iCloudTokenManager.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 */; };
@@ -177,12 +177,12 @@
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 = "<group>"; };
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 = "<group>"; };
4F25FCBD2EB1790E0060DAAA /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedKeychainManager.swift; sourceTree = "<group>"; };
4F30C7582E8FBF26008BB46C /* LiveActivityMethodChannelManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityMethodChannelManager.swift; sourceTree = "<group>"; };
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 = "<group>"; };
4F58247F2F35468D00B92EA7 /* iCloudTokenManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iCloudTokenManager.swift; sourceTree = "<group>"; };
4F5824822F3548B800B92EA7 /* WatchToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchToken.swift; sourceTree = "<group>"; };
4F5965F72F2F0C1600A3DB03 /* WatchSessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchSessionManager.swift; sourceTree = "<group>"; };
4F5965FD2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = FirkaWatchComplicationsExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -222,35 +222,35 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
4F0EA0512F2BD2A2003CC89E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
4F0EA0512F2BD2A2003CC89E /* Exceptions for "HomeWidgetsExtension" folder in "Runner" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Controls/AppControls.swift,
);
target = 97C146ED1CF9000F007C117D /* Runner */;
};
4F4E70D02EF565FF00C90AD1 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
4F4E70D02EF565FF00C90AD1 /* Exceptions for "LiveActivityWidget" folder in "Runner" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
ActivityAttributes.swift,
);
target = 97C146ED1CF9000F007C117D /* Runner */;
};
4F5966082F2F0EB100A3DB03 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
4F5966082F2F0EB100A3DB03 /* Exceptions for "FirkaWatchComplications" folder in "FirkaWatchComplicationsExtension" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
);
target = 4F5965FC2F2F0EAF00A3DB03 /* FirkaWatchComplicationsExtension */;
};
4F6C1D3E2ECD3FBD00F819D7 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
4F6C1D3E2ECD3FBD00F819D7 /* Exceptions for "LiveActivityWidget" folder in "LiveActivityWidget" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
);
target = 4F30C7642E8FBF9D008BB46C /* LiveActivityWidget */;
};
4FE64E472F27B07B006F9205 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
4FE64E472F27B07B006F9205 /* Exceptions for "HomeWidgetsExtension" folder in "HomeWidgetsExtension" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -260,10 +260,55 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
4F30C76A2E8FBF9D008BB46C /* LiveActivityWidget */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (4F4E70D02EF565FF00C90AD1 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 4F6C1D3E2ECD3FBD00F819D7 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = LiveActivityWidget; sourceTree = "<group>"; };
4F5966002F2F0EAF00A3DB03 /* FirkaWatchComplications */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (4F5966082F2F0EB100A3DB03 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = FirkaWatchComplications; sourceTree = "<group>"; };
4FE64E362F27B07A006F9205 /* HomeWidgetsExtension */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (4F0EA0512F2BD2A2003CC89E /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 4FE64E472F27B07B006F9205 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = HomeWidgetsExtension; sourceTree = "<group>"; };
4FF81B7B2F2EB4C100E95BA0 /* FirkaWatch Watch App */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = "FirkaWatch Watch App"; sourceTree = "<group>"; };
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 = "<group>";
};
4F5966002F2F0EAF00A3DB03 /* FirkaWatchComplications */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
4F5966082F2F0EB100A3DB03 /* Exceptions for "FirkaWatchComplications" folder in "FirkaWatchComplicationsExtension" target */,
);
explicitFileTypes = {
};
explicitFolders = (
);
path = FirkaWatchComplications;
sourceTree = "<group>";
};
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 = "<group>";
};
4FF81B7B2F2EB4C100E95BA0 /* FirkaWatch Watch App */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
explicitFileTypes = {
};
explicitFolders = (
);
path = "FirkaWatch Watch App";
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -342,10 +387,10 @@
4F7701CD2F2EC1AA00B79171 /* API */ = {
isa = PBXGroup;
children = (
4F27D4D12F3F2F7700749B9A /* SharedKeychainManager.swift */,
4F7701ED2F2EC2F500B79171 /* KretaAPIClient.swift */,
4F7701EE2F2EC2F500B79171 /* TokenManager.swift */,
4FCB030C2F330F3B00418E63 /* KretaAPIModels.swift */,
4F58247F2F35468D00B92EA7 /* iCloudTokenManager.swift */,
);
path = API;
sourceTree = "<group>";
@@ -711,14 +756,10 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n";
@@ -807,14 +848,10 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
@@ -879,12 +916,12 @@
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 */,
4F5824802F35468E00B92EA7 /* iCloudTokenManager.swift in Sources */,
4F7701EB2F2EC1AA00B79171 /* Subject.swift in Sources */,
4F7701EC2F2EC1AA00B79171 /* WidgetData.swift in Sources */,
4F7701EF2F2EC2F500B79171 /* TokenManager.swift in Sources */,
@@ -897,12 +934,12 @@
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 */,
4F5824812F35468E00B92EA7 /* iCloudTokenManager.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1030,21 +1067,21 @@
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
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 = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -1071,7 +1108,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.firka.firka.RunnerTests;
@@ -1090,7 +1127,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.firka.firka.RunnerTests;
@@ -1107,7 +1144,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.firka.firka.RunnerTests;
@@ -1134,7 +1171,7 @@
CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1185,7 +1222,7 @@
CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1233,7 +1270,7 @@
CODE_SIGN_ENTITLEMENTS = LiveActivityWidget.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1280,7 +1317,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1333,7 +1370,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1383,7 +1420,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = FirkaWatchComplicationsExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1434,7 +1471,7 @@
CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1485,7 +1522,7 @@
CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1532,7 +1569,7 @@
CODE_SIGN_ENTITLEMENTS = HomeWidgetsExtension.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
@@ -1563,9 +1600,9 @@
};
name = Profile;
};
4FF81B9C2F2EB4C300E95BA0 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
4FF81B9C2F2EB4C300E95BA0 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
@@ -1583,10 +1620,10 @@
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -1615,9 +1652,9 @@
};
name = Debug;
};
4FF81B9D2F2EB4C300E95BA0 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
4FF81B9D2F2EB4C300E95BA0 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
@@ -1635,10 +1672,10 @@
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -1664,9 +1701,9 @@
};
name = Release;
};
4FF81B9E2F2EB4C300E95BA0 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
4FF81B9E2F2EB4C300E95BA0 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
@@ -1684,10 +1721,10 @@
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = FirkaWatch;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = app.firka.firkaa;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -1828,21 +1865,21 @@
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
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 = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -1864,21 +1901,21 @@
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
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 = 1101;
CURRENT_PROJECT_VERSION = 1068;
DEVELOPMENT_TEAM = UT7MSP4GWZ;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Firka Testing";
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.education";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",

View File

@@ -213,12 +213,12 @@ import BackgroundTasks
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)
// The default setting is 30 minutes
request.earliestBeginDate = Date(timeIntervalSinceNow: 30 * 60)
do {
try BGTaskScheduler.shared.submit(request)
print("[AppDelegate] Background refresh scheduled for ~15 minutes from now")
print("[AppDelegate] Background refresh scheduled for ~30 minutes from now")
} catch {
print("[AppDelegate] Could not schedule background refresh: \(error)")
}

View File

@@ -46,7 +46,7 @@
</dict>
</array>
<key>CFBundleVersion</key>
<string>1101</string>
<string>1068</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>

View File

@@ -10,10 +10,6 @@
<array>
<string>group.app.firka.firkaa</string>
</array>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)app.firka.shared</string>
</array>
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
<string>$(TeamIdentifierPrefix)app.firka.firkaa</string>
</dict>

View File

@@ -9,30 +9,11 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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",
@@ -55,30 +36,8 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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)
}
@@ -123,13 +82,6 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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,
@@ -149,16 +101,8 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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")
private func fallbackTokenFromiCloud() -> [String: Any]? {
guard let token = iCloudTokenManager.shared.loadToken() else {
return nil
}
return tokenPayload(from: token)
@@ -172,22 +116,12 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
(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")
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]) {
@@ -211,19 +145,13 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
guard isFlutterWatchSyncReady else {
return
}
let payloadsToFlush: [[String: Any]] = pendingAuthQueue.sync {
let copy = pendingAuthPayloads
pendingAuthPayloads.removeAll()
return copy
if !pendingAuthPayloads.isEmpty {
print("[WatchSessionManager] Flushing \(pendingAuthPayloads.count) queued token event(s) to Flutter")
}
if !payloadsToFlush.isEmpty {
print("[WatchSessionManager] Flushing \(payloadsToFlush.count) queued token event(s) to Flutter")
}
for authData in payloadsToFlush {
for authData in pendingAuthPayloads {
flutterChannel?.invokeMethod("onTokenFromWatch", arguments: authData)
}
pendingAuthPayloads.removeAll()
if pendingICloudRecoveryNotification {
pendingICloudRecoveryNotification = false
@@ -244,43 +172,21 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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)")
}
)
do {
WCSession.default.transferUserInfo([
"id": "token_update",
"auth": authData
])
result(nil)
print("[WatchSessionManager] Token sent to Watch")
} catch {
result(FlutterError(code: "TRANSFER_ERROR", message: error.localizedDescription, details: nil))
}
result(nil)
print("[WatchSessionManager] Token sent to Watch")
}
private func handleSendWidgetDataToWatch(arguments: Any?, result: @escaping FlutterResult) {
@@ -294,9 +200,13 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
return
}
mergeApplicationContext(["widget_data": jsonString])
result(nil)
print("[WatchSessionManager] Widget data sent to Watch")
do {
try WCSession.default.updateApplicationContext(["widget_data": jsonString])
result(nil)
print("[WatchSessionManager] Widget data sent to Watch")
} catch {
result(FlutterError(code: "UPDATE_ERROR", message: error.localizedDescription, details: nil))
}
}
private func handleSendLanguageToWatch(arguments: Any?, result: @escaping FlutterResult) {
@@ -305,29 +215,15 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
return
}
guard WCSession.default.isWatchAppInstalled else {
print("[WatchSessionManager] No paired Watch app, skipping language publish")
result(nil)
guard WCSession.default.activationState == .activated else {
result(FlutterError(code: "SESSION_NOT_ACTIVE", message: "WCSession is not activated", details: 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")
}
WCSession.default.transferUserInfo([
"id": "language_update",
"language": languageCode
])
result(nil)
print("[WatchSessionManager] Language '\(languageCode)' sent to Watch")
}
@@ -379,17 +275,17 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
}
private func handleCheckiCloudToken(result: @escaping FlutterResult) {
print("[WatchSessionManager] Checking shared Keychain for token...")
print("[WatchSessionManager] Checking iCloud for token...")
guard let token = SharedKeychainManager.shared.loadToken() else {
print("[WatchSessionManager] No token in shared Keychain")
guard let token = iCloudTokenManager.shared.loadToken() else {
print("[WatchSessionManager] No token in iCloud")
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))")
print("[WatchSessionManager] Found iCloud token, expiry: \(formatter.string(from: token.expiryDate))")
result(tokenPayload(from: token))
}
@@ -400,12 +296,6 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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,
@@ -433,220 +323,15 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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)")
}
}
iCloudTokenManager.shared.saveToken(token, deviceName: "iPhone")
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
print("[WatchSessionManager] Token saved to shared Keychain, expiry: \(formatter.string(from: expiryDate))")
print("[WatchSessionManager] Token saved to iCloud, 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,
@@ -684,12 +369,6 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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 {
@@ -700,7 +379,7 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
switch action {
case "requestToken":
if !self.isFlutterWatchSyncReady {
if let tokenData = self.fallbackTokenFromSharedKeychain() {
if let tokenData = self.fallbackTokenFromiCloud() {
print("[WatchSessionManager] Flutter not ready, returning iCloud token to Watch")
replyHandler(["auth": tokenData])
} else {
@@ -709,13 +388,11 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
}
return
}
self.flutterChannel?.invokeMethod("getTokenForWatch", arguments: nil) { result in
DispatchQueue.main.async {
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() {
if let fallbackToken = self.fallbackTokenFromiCloud() {
print("[WatchSessionManager] Flutter returned error (\(error)), falling back to iCloud token")
replyHandler(["auth": fallbackToken])
} else {
@@ -723,16 +400,11 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
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() {
if let fallbackToken = self.fallbackTokenFromiCloud() {
print("[WatchSessionManager] No Flutter token available, falling back to iCloud token")
replyHandler(["auth": fallbackToken])
} else {
@@ -741,86 +413,18 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
}
}
}
}
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
DispatchQueue.main.async {
self.flutterChannel?.invokeMethod("getLanguageForWatch", arguments: nil) { result in
if let languageCode = result as? String {
print("[WatchSessionManager] Sending language to Watch: \(languageCode)")
replyHandler(["language": languageCode])
} else {
print("[WatchSessionManager] No language from Flutter, defaulting to hu")
replyHandler(["language": "hu"])
}
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"])
}
}
@@ -832,23 +436,27 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
if !self.isFlutterWatchSyncReady {
print("[WatchSessionManager] Flutter not ready, queueing token from Watch")
self.enqueuePendingAuth(tokenData)
DispatchQueue.main.async {
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"])
DispatchQueue.main.async {
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"])
}
}
}
@@ -857,13 +465,6 @@ class WatchSessionManager: NSObject, WCSessionDelegate {
}
}
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")
}

View File

@@ -90,7 +90,6 @@ class KretaAPIClient {
if let token = TokenManager.shared.loadToken() {
let expiryThreshold = token.expiryDate.addingTimeInterval(-60)
if Date() < expiryThreshold {
TokenManager.shared.clearLastRecoveryFailure()
return token
}
}
@@ -98,15 +97,9 @@ class KretaAPIClient {
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)
}

View File

@@ -1,791 +0,0 @@
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
)
}
}

View File

@@ -43,14 +43,6 @@ class TokenManager {
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"
@@ -60,7 +52,6 @@ class TokenManager {
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
@@ -87,45 +78,6 @@ class TokenManager {
return recoveryInProgress
}
func clearLastRecoveryFailure() {
lastRecoveryFailure = nil
}
#if os(watchOS)
private func withWatchRefreshLease<T>(
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
@@ -168,50 +120,61 @@ class TokenManager {
}
}
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()
}
iCloudTokenManager.shared.observeChanges { [weak self] iCloudToken in
guard let self = self else { return }
private let kvStoreMigrationKey = "firka_kv_store_migrated_v1"
let preferredStudentIdNorm = self.getActiveStudentIdNorm()
let isValidToken = iCloudToken.expiryDate > Date().addingTimeInterval(60)
let preferredLocalToken = self.localTokenFromKeychainAndFile(
preferredStudentIdNorm: preferredStudentIdNorm
)
private func runKVStoreMigrationIfNeeded() {
let alreadyMigrated = UserDefaults.standard.bool(forKey: kvStoreMigrationKey)
if alreadyMigrated {
return
if let preferredStudentIdNorm,
iCloudToken.studentIdNorm != preferredStudentIdNorm,
preferredLocalToken != nil {
print("[TokenManager] Ignoring iCloud token for inactive account (\(iCloudToken.studentIdNorm)), active is \(preferredStudentIdNorm)")
return
}
let localToken = preferredLocalToken ?? self.localTokenFromKeychainAndFile()
if let localToken = localToken {
if iCloudToken.isNewer(than: localToken) {
print("[TokenManager] iCloud token is fresher, updating local cache")
try? self.saveTokenToKeychain(iCloudToken)
try? self.saveTokenToFile(iCloudToken)
self.setActiveStudentIdNorm(iCloudToken.studentIdNorm)
#if os(watchOS)
DataStore.shared.checkTokenState()
#endif
#if os(iOS)
if isValidToken {
self.notifyiOSTokenRecovered()
}
#endif
} else {
print("[TokenManager] Local token is fresher or equal, ignoring iCloud update")
}
} else {
print("[TokenManager] No local token, using iCloud token")
try? self.saveTokenToKeychain(iCloudToken)
try? self.saveTokenToFile(iCloudToken)
self.setActiveStudentIdNorm(iCloudToken.studentIdNorm)
#if os(watchOS)
DataStore.shared.checkTokenState()
#endif
#if os(iOS)
if isValidToken {
self.notifyiOSTokenRecovered()
}
#endif
}
}
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)
@@ -236,12 +199,12 @@ class TokenManager {
// MARK: - Load Token (active-account first)
func loadToken() -> WatchToken? {
let sharedKeychainToken = SharedKeychainManager.shared.loadToken()
let iCloudToken = iCloudTokenManager.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 = iCloudToken { candidates.append((t, "iCloud")) }
if let t = keychainToken { candidates.append((t, "keychain")) }
if let t = fileToken { candidates.append((t, "file")) }
@@ -250,24 +213,7 @@ class TokenManager {
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 preferredStudentIdNorm = getActiveStudentIdNorm()
let freshest: (token: WatchToken, source: String)
if let preferredStudentIdNorm {
let filtered = candidates.filter { $0.token.studentIdNorm == preferredStudentIdNorm }
@@ -277,15 +223,7 @@ class TokenManager {
} {
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
}
print("[TokenManager] Active account token not found locally, falling back to freshest available account")
freshest = candidates.dropFirst().reduce(candidates[0]) { currentBest, candidate in
candidate.token.isNewer(than: currentBest.token) ? candidate : currentBest
}
@@ -295,19 +233,8 @@ class TokenManager {
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
@@ -349,16 +276,8 @@ class TokenManager {
// 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()
iCloudTokenManager.shared.deleteToken()
UserDefaults.standard.removeObject(forKey: activeStudentIdNormKey)
guard let filePath = getTokenFilePath() else { return }
@@ -368,11 +287,10 @@ class TokenManager {
// MARK: - Save Token
func saveToken(
_ token: WatchToken,
syncToSharedKeychain: Bool = false,
syncToICloud: Bool = false,
forceAccountSwitch: Bool = false
) throws {
let currentToken = loadToken()
if let currentToken {
if let currentToken = loadToken() {
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) {
@@ -381,19 +299,13 @@ class TokenManager {
}
}
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)
if syncToICloud {
iCloudTokenManager.shared.saveToken(token, deviceName: deviceName)
}
guard let filePath = getTokenFilePath() else {
@@ -532,25 +444,16 @@ class TokenManager {
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
}
@@ -581,49 +484,18 @@ class TokenManager {
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")
@@ -633,93 +505,72 @@ class TokenManager {
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()
try? saveToken(recoveredToken, syncToICloud: false)
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...")
print("[TokenManager] Step 3: Trying iCloud recovery with retries...")
let retryDelays: [TimeInterval] = [0, 5, 10, 5, 10]
var sharedKeychainHasToken = false
var iCloudHasToken = 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")
if !iCloudHasToken && attempt > 0 {
print("[TokenManager] Step 3: Skipping retries - iCloud 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)...")
print("[TokenManager] Step 3: iCloud attempt \(attempt + 1)/\(retryDelays.count)...")
if let sharedToken = SharedKeychainManager.shared.loadToken() {
if let iCloudToken = iCloudTokenManager.shared.loadToken() {
if let preferredStudentIdNorm = getActiveStudentIdNorm(),
sharedToken.studentIdNorm != preferredStudentIdNorm {
iCloudToken.studentIdNorm != preferredStudentIdNorm {
if localTokenFromKeychainAndFile(
preferredStudentIdNorm: preferredStudentIdNorm
) != nil {
print("[TokenManager] Step 3: Ignoring shared Keychain token for inactive account (\(sharedToken.studentIdNorm)), active is \(preferredStudentIdNorm)")
print("[TokenManager] Step 3: Ignoring iCloud token for inactive account (\(iCloudToken.studentIdNorm)), active is \(preferredStudentIdNorm)")
continue
}
print("[TokenManager] Step 3: Active account token missing locally, considering different-account shared Keychain token")
print("[TokenManager] Step 3: Active account token missing locally, considering different-account iCloud 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
iCloudHasToken = true
if iCloudToken.expiryDate > Date() {
print("[TokenManager] Step 3 SUCCESS: Found valid iCloud token, applying without immediate refresh")
try? saveToken(iCloudToken, syncToICloud: false)
return iCloudToken
} else {
print("[TokenManager] Step 3: Shared Keychain token is expired, trying refresh anyway...")
print("[TokenManager] Step 3: iCloud 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()
let refreshedToken = try await refreshTokenInternal(iCloudToken)
print("[TokenManager] Step 3 SUCCESS: Expired iCloud token refresh succeeded on attempt \(attempt + 1)")
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
}
}
print("[TokenManager] Step 3: Expired iCloud token refresh failed on attempt \(attempt + 1): \(error)")
}
}
} else {
print("[TokenManager] Step 3: No token in shared Keychain on attempt \(attempt + 1)")
print("[TokenManager] Step 3: No token in iCloud on attempt \(attempt + 1)")
if attempt == 0 {
sharedKeychainHasToken = false
iCloudHasToken = false
}
}
}
print("[TokenManager] All recovery attempts failed")
if lastRecoveryFailure == nil {
lastRecoveryFailure = .noToken
}
return nil
}
@@ -847,32 +698,6 @@ class TokenManager {
#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
@@ -892,9 +717,13 @@ class TokenManager {
updatedAtMs: nowMs
)
try saveToken(newToken, syncToSharedKeychain: true)
return newToken
try saveToken(newToken, syncToICloud: true)
#if os(watchOS)
WatchConnectivityManager.shared.sendTokenToiPhoneInBackground()
#endif
return newToken
}
// MARK: - Refresh Token
@@ -903,32 +732,6 @@ class TokenManager {
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
@@ -948,9 +751,13 @@ class TokenManager {
updatedAtMs: nowMs
)
try saveToken(newToken, syncToSharedKeychain: true)
return newToken
try saveToken(newToken, syncToICloud: true)
#if os(watchOS)
WatchConnectivityManager.shared.sendTokenToiPhoneInBackground()
#endif
return newToken
}
// MARK: - Private Helper Methods
@@ -967,7 +774,6 @@ class TokenManager {
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,
@@ -979,11 +785,7 @@ class TokenManager {
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)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw TokenError.networkError

View File

@@ -0,0 +1,210 @@
import Foundation
class iCloudTokenManager {
static let shared = iCloudTokenManager()
private let iCloudStore = NSUbiquitousKeyValueStore.default
private let kAccessToken = "firka_access_token"
private let kRefreshToken = "firka_refresh_token"
private let kIdToken = "firka_id_token"
private let kIss = "firka_iss"
private let kStudentId = "firka_student_id"
private let kStudentIdNorm = "firka_student_id_norm"
private let kExpiryDate = "firka_expiry_date"
private let kTokenVersion = "firka_token_version"
private let kUpdatedAtMs = "firka_updated_at_ms"
private let kLastUpdatedDevice = "firka_last_updated_device"
private let kLastUpdateTimestamp = "firka_last_update_timestamp"
private var changeObserver: ((WatchToken) -> Void)?
private var isAvailable = false
private init() {
NotificationCenter.default.addObserver(
self,
selector: #selector(iCloudStoreDidChange(_:)),
name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: iCloudStore
)
isAvailable = iCloudStore.synchronize()
if isAvailable {
print("[iCloud] iCloud KeyValue Store available and synced")
} else {
print("[iCloud] iCloud not available (not signed in or disabled) - using local storage only")
}
}
func saveToken(_ token: WatchToken, deviceName: String) {
guard isAvailable else {
return
}
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("[iCloud] Ignoring stale token save from \(deviceName), existing expiry: \(formatter.string(from: existingToken.expiryDate)), incoming: \(formatter.string(from: token.expiryDate))")
return
}
} else {
let incomingUpdatedAt = token.effectiveUpdatedAtMs ?? 0
let existingUpdatedAt = existingToken.effectiveUpdatedAtMs ?? 0
if incomingUpdatedAt > 0 &&
existingUpdatedAt > 0 &&
incomingUpdatedAt <= existingUpdatedAt {
print("[iCloud] Ignoring cross-account stale token save from \(deviceName)")
return
}
}
}
print("[iCloud] Saving token to iCloud from \(deviceName)")
let nowMs = Int64(Date().timeIntervalSince1970 * 1000)
let updatedAtMs = token.effectiveUpdatedAtMs ?? nowMs
let tokenVersion = token.effectiveTokenVersion
iCloudStore.set(token.accessToken, forKey: kAccessToken)
iCloudStore.set(token.refreshToken, forKey: kRefreshToken)
iCloudStore.set(token.idToken, forKey: kIdToken)
iCloudStore.set(token.iss, forKey: kIss)
iCloudStore.set(token.studentId, forKey: kStudentId)
iCloudStore.set(token.studentIdNorm, forKey: kStudentIdNorm)
iCloudStore.set(token.expiryDate.timeIntervalSince1970, forKey: kExpiryDate)
if let tokenVersion {
iCloudStore.set(tokenVersion, forKey: kTokenVersion)
} else {
iCloudStore.removeObject(forKey: kTokenVersion)
}
iCloudStore.set(updatedAtMs, forKey: kUpdatedAtMs)
iCloudStore.set(deviceName, forKey: kLastUpdatedDevice)
iCloudStore.set(Double(updatedAtMs) / 1000.0, forKey: kLastUpdateTimestamp)
let success = iCloudStore.synchronize()
if success {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
formatter.timeZone = TimeZone.current
print("[iCloud] Token saved successfully, expiry: \(formatter.string(from: token.expiryDate))")
} else {
print("[iCloud] Failed to synchronize token to iCloud")
}
}
func loadToken() -> WatchToken? {
guard isAvailable else {
return nil
}
iCloudStore.synchronize()
guard let accessToken = iCloudStore.string(forKey: kAccessToken),
let refreshToken = iCloudStore.string(forKey: kRefreshToken),
let idToken = iCloudStore.string(forKey: kIdToken),
let iss = iCloudStore.string(forKey: kIss),
let studentId = iCloudStore.string(forKey: kStudentId) else {
print("[iCloud] No token found in iCloud")
return nil
}
let studentIdNorm = iCloudStore.longLong(forKey: kStudentIdNorm)
let expiryTimestamp = iCloudStore.double(forKey: kExpiryDate)
let tokenVersionRaw = iCloudStore.longLong(forKey: kTokenVersion)
let updatedAtMsRaw = iCloudStore.longLong(forKey: kUpdatedAtMs)
let fallbackUpdatedAt = Int64(iCloudStore.double(forKey: kLastUpdateTimestamp) * 1000.0)
let lastDevice = iCloudStore.string(forKey: kLastUpdatedDevice) ?? "unknown"
guard expiryTimestamp > 0 else {
print("[iCloud] Invalid expiry date in iCloud")
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 : (fallbackUpdatedAt > 0 ? fallbackUpdatedAt : nil)
)
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
formatter.timeZone = TimeZone.current
print("[iCloud] Token loaded from iCloud (last updated by: \(lastDevice)), expiry: \(formatter.string(from: expiryDate))")
return token
}
func deleteToken() {
guard isAvailable else {
return
}
print("[iCloud] Deleting token from iCloud")
iCloudStore.removeObject(forKey: kAccessToken)
iCloudStore.removeObject(forKey: kRefreshToken)
iCloudStore.removeObject(forKey: kIdToken)
iCloudStore.removeObject(forKey: kIss)
iCloudStore.removeObject(forKey: kStudentId)
iCloudStore.removeObject(forKey: kStudentIdNorm)
iCloudStore.removeObject(forKey: kExpiryDate)
iCloudStore.removeObject(forKey: kTokenVersion)
iCloudStore.removeObject(forKey: kUpdatedAtMs)
iCloudStore.removeObject(forKey: kLastUpdatedDevice)
iCloudStore.removeObject(forKey: kLastUpdateTimestamp)
iCloudStore.synchronize()
}
func observeChanges(_ observer: @escaping (WatchToken) -> Void) {
self.changeObserver = observer
}
@objc private func iCloudStoreDidChange(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let changeReason = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int else {
return
}
if changeReason == NSUbiquitousKeyValueStoreServerChange ||
changeReason == NSUbiquitousKeyValueStoreInitialSyncChange {
print("[iCloud] Token changed externally in iCloud")
if let token = loadToken() {
let lastDevice = iCloudStore.string(forKey: kLastUpdatedDevice) ?? "unknown"
print("[iCloud] Received updated token from: \(lastDevice)")
changeObserver?(token)
}
}
}
func getLastUpdatedDevice() -> String? {
guard isAvailable else {
return nil
}
iCloudStore.synchronize()
return iCloudStore.string(forKey: kLastUpdatedDevice)
}
func getLastUpdateTimestamp() -> Date? {
guard isAvailable else {
return nil
}
iCloudStore.synchronize()
let timestamp = iCloudStore.double(forKey: kLastUpdateTimestamp)
guard timestamp > 0 else { return nil }
return Date(timeIntervalSince1970: timestamp)
}
}

View File

@@ -1,77 +0,0 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka/core/bloc/home_refresh_cubit.dart';
import 'package:firka/core/bloc/profile_picture_cubit.dart';
import 'package:firka/core/bloc/reauth_cubit.dart';
import 'package:firka/core/bloc/settings_cubit.dart';
import 'package:firka/core/bloc/theme_cubit.dart';
import 'package:firka/data/models/token_model.dart';
import 'package:firka/core/settings.dart';
import 'package:firka/l10n/app_localizations.dart';
import 'package:logging/logging.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:isar_community/isar.dart';
import 'dart:io';
late final Logger logger;
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
late AppInitialization initData;
bool initDone = false;
/// Set when app router is created; used for deep links and notifications.
GoRouter? appRouter;
final dio = Dio();
final isBeta = true;
class DeviceInfo {
String model;
String versionRelease;
String versionSdkInt;
DeviceInfo(this.model, this.versionRelease, this.versionSdkInt);
@override
String toString() {
return "DeviceInfo(model = \"$model\", versionRelease = \"$versionRelease\""
", versionSdkInt = \"$versionSdkInt\"";
}
}
class AppInitialization {
final Isar isar;
final Directory appDir;
final PackageInfo packageInfo;
final DeviceInfo devInfo;
late KretaClient client;
List<TokenModel> tokens;
bool hasWatchListener = false;
/// Set by the wear pairing modal; called when watch sends init_done or sync_done to dismiss the sheet.
void Function()? dismissWearPairingSheet;
Uint8List? profilePicture;
SettingsStore settings;
ThemeCubit? themeCubit;
SettingsCubit? settingsCubit;
ProfilePictureCubit? profilePictureCubit;
ReauthCubit? reauthCubit;
HomeRefreshCubit? homeRefreshCubit;
AppLocalizations l10n;
final GlobalKey<NavigatorState> navigatorKey;
AppInitialization({
required this.isar,
required this.appDir,
required this.devInfo,
required this.packageInfo,
required this.tokens,
required this.settings,
required this.l10n,
required this.navigatorKey,
});
}

View File

@@ -1,407 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/core/bloc/home_refresh_cubit.dart';
import 'package:firka/core/bloc/profile_picture_cubit.dart';
import 'package:firka/core/bloc/reauth_cubit.dart';
import 'package:firka/core/bloc/settings_cubit.dart';
import 'package:firka/core/bloc/theme_cubit.dart';
import 'package:firka/services/active_account_helper.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka/data/models/app_settings_model.dart';
import 'package:firka/data/models/generic_cache_model.dart';
import 'package:firka/data/models/homework_cache_model.dart';
import 'package:firka/data/models/timetable_cache_model.dart';
import 'package:firka/data/models/token_model.dart';
import 'package:firka/services/live_activity_service.dart';
import 'package:firka/core/settings.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';
import 'package:firka/core/swear_generator.dart';
import 'package:firka/ui/theme/style.dart';
import 'package:intl/intl.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:isar_community/isar.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
Isar? isarInit;
Future<Isar> initDB() async {
if (isarInit != null) return isarInit!;
final dir = await getApplicationDocumentsDirectory();
isarInit = await Isar.open(
[
TokenModelSchema,
GenericCacheModelSchema,
TimetableCacheModelSchema,
HomeworkCacheModelSchema,
AppSettingsModelSchema,
HomeworkDoneModelSchema,
],
inspector: true,
directory: dir.path,
);
return isarInit!;
}
Future<void> initLang(AppInitialization data) async {
String? languageCode;
switch ((data.settings.group("settings").subGroup("application")["language"]
as SettingsItemsRadio)
.activeIndex) {
case 1: // hu
data.l10n = AppLocalizationsHu();
languageCode = 'hu';
break;
case 2: // en
data.l10n = AppLocalizationsEn();
languageCode = 'en';
break;
case 3: // de
data.l10n = AppLocalizationsDe();
languageCode = 'de';
break;
default: // 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');
}
}
}
void initTheme(AppInitialization data) {
final themeCubit = data.themeCubit;
if (themeCubit == null) return;
final brightness =
SchedulerBinding.instance.platformDispatcher.platformBrightness;
switch ((data.settings.group("settings").subGroup("customization")["theme"]
as SettingsItemsRadio)
.activeIndex) {
case 1:
appStyle = lightStyle;
themeCubit.setLightMode(true);
break;
case 2:
appStyle = darkStyle;
themeCubit.setLightMode(false);
break;
default:
if (brightness == Brightness.dark) {
appStyle = darkStyle;
themeCubit.setLightMode(false);
} else {
appStyle = lightStyle;
themeCubit.setLightMode(true);
}
}
}
Future<void> _initData(AppInitialization init) async {
init.themeCubit ??= ThemeCubit();
init.settingsCubit ??= SettingsCubit();
init.profilePictureCubit ??= ProfilePictureCubit();
init.reauthCubit ??= ReauthCubit();
init.homeRefreshCubit ??= HomeRefreshCubit();
await init.settings.load(init.isar.appSettingsModels);
await initLang(init);
initTheme(init);
init.settings = SettingsStore(init.l10n);
await init.settings.load(init.isar.appSettingsModels);
var dispatcher = SchedulerBinding.instance.platformDispatcher;
dispatcher.onPlatformBrightnessChanged = () {
initTheme(init);
};
dispatcher.onLocaleChanged = () {
final languageSetting =
init.settings.group("settings").subGroup("application")["language"]
as SettingsItemsRadio;
final isAutoLanguage = languageSetting.activeIndex == 0;
if (!isAutoLanguage) {
return;
}
final previousLocale = init.l10n.localeName;
unawaited(() async {
await initLang(init);
final nextLocale = init.l10n.localeName;
if (previousLocale != nextLocale) {
logger.info(
"[Init] System locale changed in auto mode: $previousLocale -> $nextLocale",
);
}
init.themeCubit?.refresh();
}());
};
resetOldTimeTableCache(init.isar);
resetOldHomeworkCache(init.isar);
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,
tokens: init.tokens,
);
}
} catch (e) {
logger.warning('[Init] iCloud bootstrap/recovery failed: $e');
}
}
final allTokens = await init.isar.tokenModels.where().findAll();
init.tokens = allTokens;
if (allTokens.isNotEmpty) {
final token = pickActiveToken(tokens: allTokens, settings: init.settings);
if (token == null) {
logger.warning(
"[Init] Tokens disappeared during initialization; skipping client setup",
);
return;
}
logger.fine("Initializing kréta client as: ${token.studentId}");
init.client = KretaClient(token, init.isar, init.reauthCubit!);
if (Platform.isIOS) {
final expiryDate = token.expiryDate;
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
init.reauthCubit?.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"));
if (await pfpFile.exists()) {
init.profilePicture = await pfpFile.readAsBytes();
}
}
Future<AppInitialization> initializeApp() async {
if (initDone) {
await _initData(initData);
return initData;
}
final isar = await initDB();
final tokens = await isar.tokenModels.where().findAll();
logger.finest('Token count: ${tokens.length}');
var devInfoFetched = false;
var devInfo = DeviceInfo("SM-A705FN", "11", "30");
try {
if (Platform.isAndroid) {
const channel = MethodChannel("firka.app/main");
final rawInfo = ((await channel.invokeMethod("get_info")) as String)
.split(";");
devInfo = DeviceInfo(rawInfo[0], rawInfo[1], rawInfo[2]);
devInfoFetched = true;
}
} catch (e) {
if (e is Error) {
logger.shout("Error in initializeApp()", e.toString(), e.stackTrace);
} else {
logger.shout("Error in initializeApp()", e.toString());
}
}
logger.fine("Fetched device info: ${devInfoFetched ? "yes" : "no"}");
logger.fine("Using device info: ${devInfo.toString()}");
var init = AppInitialization(
isar: isar,
appDir: await getApplicationDocumentsDirectory(),
devInfo: devInfo,
packageInfo: await PackageInfo.fromPlatform(),
tokens: tokens,
settings: SettingsStore(AppLocalizationsHu()),
l10n: AppLocalizationsHu(),
navigatorKey: navigatorKey,
);
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);
}
}
await _initData(init);
return init;
}
Future<void> setupLogging() async {
final jwtPattern = RegExp(
r'([A-Za-z0-9-_]+)\.([A-Za-z0-9-_]+)\.([A-Za-z0-9-_]+)',
);
final omPattern = RegExp(r'(\d{3})(\d{6})([A-Za-z0-9]?)');
final refreshTokenPattern = RegExp(
r'"(?=.{21,}$)([A-Z0-9]+-[A-Z0-9_\-.~+]*)"',
);
final docs = await getApplicationDocumentsDirectory();
Future<void> deleteOldLogFiles() async {
final docs = await getApplicationDocumentsDirectory();
final dir = Directory(docs.path);
if (!dir.existsSync()) return;
final now = DateTime.now();
final cutoff = now.subtract(Duration(days: 30));
final logFileRegex = RegExp(r'^(\d{4})_(\d{2})_(\d{2})\.log$');
for (final entity in dir.listSync()) {
if (entity is! File) continue;
final name = entity.uri.pathSegments.last;
final m = logFileRegex.firstMatch(name);
if (m == null) continue;
try {
final y = int.parse(m.group(1)!);
final mo = int.parse(m.group(2)!);
final d = int.parse(m.group(3)!);
final fileDate = DateTime(y, mo, d);
if (fileDate.isBefore(
DateTime(cutoff.year, cutoff.month, cutoff.day),
)) {
logger.info("Removing old log file: $name");
await entity.delete();
}
} catch (_) {
// ignore parse/delete errors
}
}
}
String logFilePathForDate(DateTime dt) {
final fileName = "${DateFormat("yyyy_MM_dd").format(dt)}.log";
return Directory(docs.path).uri.resolve(fileName).toFilePath();
}
File fileForDate(DateTime dt) {
final path = logFilePathForDate(dt);
final file = File(path);
if (!file.existsSync()) file.createSync(recursive: true);
return file;
}
String censorLog(String msg) {
return msg
.replaceAll(jwtPattern, '***')
.replaceAllMapped(omPattern, (match) {
return "${match.group(1)}******${match.group(3)}";
})
.replaceAll(refreshTokenPattern, '"***"');
}
hierarchicalLoggingEnabled = true;
logger.level = Level.ALL;
DateTime currentDate = DateTime.now();
IOSink sink = fileForDate(currentDate).openWrite(mode: FileMode.append);
logger.onRecord.listen((record) {
final now = DateTime.now();
if (now.year != currentDate.year ||
now.month != currentDate.month ||
now.day != currentDate.day) {
sink.flush();
sink.close();
currentDate = now;
sink = fileForDate(currentDate).openWrite(mode: FileMode.append);
}
final censored = censorLog(record.message);
final timestamp = DateFormat('yyyy-MM-dd HH:mm:ss.SSS').format(now);
final level = record.level.name;
final line = '[$timestamp] [$level] [$censored]';
sink.writeln(line);
debugPrint(
"[Firka] [${record.level.name}] ${kDebugMode ? record.message : censored}",
);
});
unawaited(deleteOldLogFiles());
try {
logger.finest('loading dirty words');
await loadDirtyWords();
logger.finest('loaded dirty words');
} catch (e, st) {
logger.severe('Failed to load dirty words: $e', e, st);
}
}

View File

@@ -1,237 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/app/initialization.dart';
import 'package:firka/core/bloc/home_refresh_cubit.dart';
import 'package:firka/core/settings.dart';
import 'package:firka/core/bloc/profile_picture_cubit.dart';
import 'package:firka/core/bloc/reauth_cubit.dart';
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/watch_sync_helper.dart';
import 'package:firka/ui/phone/pages/extras/main_wear_pair.dart';
import 'package:firka/l10n/app_localizations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:go_router/go_router.dart';
class InitializationScreen extends StatefulWidget {
const InitializationScreen({super.key});
@override
State<InitializationScreen> createState() => _InitializationScreenState();
}
class _InitializationScreenState extends State<InitializationScreen> {
GoRouter? _router;
final Future<AppInitialization> _init = initializeApp().timeout(
const Duration(seconds: 20),
);
@override
Widget build(BuildContext context) {
return FutureBuilder<AppInitialization>(
future: _init,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
logger.shout(
"Error in InitializationScreen",
snapshot.error.toString(),
snapshot.stackTrace,
);
FlutterNativeSplash.remove();
return MaterialApp(
key: const ValueKey('errorPage'),
home: DefaultAssetBundle(
bundle: FirkaBundle(),
child: Scaffold(
body: Center(
child: Text(
'Error initializing app: ${snapshot.error}',
style: const TextStyle(color: Colors.red),
),
),
),
),
);
}
assert(snapshot.data != null);
initData = snapshot.data!;
initDone = true;
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;
WatchSyncHelper.onWatchMessage = (msg) {
logger.finest("WatchOS IPC [Watch -> Phone]: ${msg["id"]}");
switch (msg["id"]) {
case "ping":
if (initData.tokens.isNotEmpty) {
logger.finest("WatchOS IPC [Phone -> Watch]: pong");
unawaited(
WatchSyncHelper.sendMessageToWatch({'id': 'pong'}),
);
_router?.go('/home');
WidgetsBinding.instance.addPostFrameCallback((_) {
final ctx = navigatorKey.currentContext;
if (ctx != null && ctx.mounted) {
logger.info('Watch init_data: ${jsonEncode(msg)}');
showWearBottomSheet(
ctx,
initData,
Platform.isAndroid ? msg['model'] : 'Apple Watch',
);
}
});
}
break;
case "init_done":
case "sync_done":
final ctx = navigatorKey.currentContext;
if (ctx != null && ctx.mounted) {
ScaffoldMessenger.of(ctx).hideCurrentSnackBar();
}
initData.dismissWearPairingSheet?.call();
initData.dismissWearPairingSheet = null;
break;
}
};
if (Platform.isAndroid) {
WatchSyncHelper.watchMessageStream.listen((msg) async {
WatchSyncHelper.onWatchMessage?.call(msg);
if (msg['id'] == 'request_sync' &&
initDone &&
isWearOsSupportEnabled()) {
final ctx = navigatorKey.currentContext;
if (ctx != null && ctx.mounted) {
ScaffoldMessenger.of(ctx).showSnackBar(
SnackBar(content: Text(initData.l10n.wear_syncing)),
);
}
await WatchSyncHelper.runWearSyncInForeground(
initData.client,
);
}
});
if (isWearOsSupportEnabled()) {
unawaited(() async {
try {
await WatchSyncHelper.startWearSyncServiceWithFreshCache(
initData.client,
initData.appDir.path,
);
} catch (e) {
logger.warning(
'[Init] Failed to start Wear sync service on launch: $e',
);
}
}());
}
}
}
if (_router == null) {
_router = createAppRouter();
appRouter = _router;
}
final themeCubit = initData.themeCubit!;
final settingsCubit = initData.settingsCubit!;
final profilePictureCubit = initData.profilePictureCubit!;
final reauthCubit = initData.reauthCubit!;
final homeRefreshCubit = initData.homeRefreshCubit!;
return MultiBlocProvider(
providers: [
BlocProvider<ThemeCubit>.value(value: themeCubit),
BlocProvider<SettingsCubit>.value(value: settingsCubit),
BlocProvider<ProfilePictureCubit>.value(
value: profilePictureCubit,
),
BlocProvider<ReauthCubit>.value(value: reauthCubit),
BlocProvider<HomeRefreshCubit>.value(value: homeRefreshCubit),
],
child: MaterialApp.router(
title: 'Firka',
key: const ValueKey('firkaApp'),
routerConfig: _router!,
theme: ThemeData(
primarySwatch: Colors.lightGreen,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) {
return BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, themeState) {
final isLight = themeState.isLightMode;
final overlay = SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: isLight
? Brightness.dark
: Brightness.light,
statusBarBrightness: isLight
? Brightness.light
: Brightness.dark,
systemStatusBarContrastEnforced: false,
);
SystemChrome.setSystemUIOverlayStyle(overlay);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: overlay,
child: child ?? const SizedBox.shrink(),
);
},
);
},
),
);
}
return MaterialApp(
home: DefaultAssetBundle(
bundle: FirkaBundle(),
child: Scaffold(
backgroundColor: const Color(0xFF7CA120),
body: Container(),
),
),
);
},
);
}
}

View File

@@ -1,23 +0,0 @@
import 'package:kreta_api/kreta_api.dart';
double calculateAverage(List<Grade> sortedGrades) {
double totalWeight = 0.0;
double weightedSum = 0.0;
for (final grade in sortedGrades) {
final value = grade.numericValue;
final weight = grade.weightPercentage;
if (value != null && weight != null) {
weightedSum += value * weight;
totalWeight += weight;
}
}
if (totalWeight == 0) {
return double.parse(0.0.toStringAsFixed(2));
}
final avg = weightedSum / totalWeight;
return double.parse(avg.toStringAsFixed(2));
}

View File

@@ -1,19 +0,0 @@
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeRefreshState {
final int refreshTrigger;
const HomeRefreshState({this.refreshTrigger = 0});
}
class HomeRefreshCubit extends Cubit<HomeRefreshState> {
HomeRefreshCubit() : super(const HomeRefreshState());
void requestRefresh() {
emit(HomeRefreshState(refreshTrigger: state.refreshTrigger + 1));
}
void onRefreshComplete() {
emit(HomeRefreshState(refreshTrigger: state.refreshTrigger));
}
}

View File

@@ -1,15 +0,0 @@
import 'package:flutter_bloc/flutter_bloc.dart';
class ProfilePictureState {
final int version;
const ProfilePictureState({this.version = 0});
}
class ProfilePictureCubit extends Cubit<ProfilePictureState> {
ProfilePictureCubit() : super(const ProfilePictureState());
void notifyChanged() {
emit(ProfilePictureState(version: state.version + 1));
}
}

View File

@@ -1,19 +0,0 @@
import 'package:flutter_bloc/flutter_bloc.dart';
class ReauthState {
final bool needsReauth;
const ReauthState({this.needsReauth = false});
}
class ReauthCubit extends Cubit<ReauthState> {
ReauthCubit() : super(const ReauthState());
void setNeedsReauth(bool value) {
emit(ReauthState(needsReauth: value));
}
void clear() {
emit(const ReauthState(needsReauth: false));
}
}

View File

@@ -1,15 +0,0 @@
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingsState {
final int version;
const SettingsState({this.version = 0});
}
class SettingsCubit extends Cubit<SettingsState> {
SettingsCubit() : super(const SettingsState());
void notifyChanged() {
emit(SettingsState(version: state.version + 1));
}
}

View File

@@ -1,20 +0,0 @@
import 'package:flutter_bloc/flutter_bloc.dart';
class ThemeState {
final bool isLightMode;
const ThemeState({required this.isLightMode});
}
class ThemeCubit extends Cubit<ThemeState> {
ThemeCubit({bool initialLightMode = true})
: super(ThemeState(isLightMode: initialLightMode));
void setLightMode(bool isLight) {
emit(ThemeState(isLightMode: isLight));
}
void refresh() {
emit(ThemeState(isLightMode: state.isLightMode));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +0,0 @@
import 'package:flutter/widgets.dart';
abstract class FirkaState<T extends StatefulWidget> extends State<T> {}

View File

@@ -1,68 +0,0 @@
import 'package:isar_community/isar.dart';
import 'package:firka/core/debug_helper.dart';
import 'package:firka/data/util.dart';
part 'homework_cache_model.g.dart';
@collection
class HomeworkCacheModel extends DatedCacheEntry {
HomeworkCacheModel();
}
Future<void> resetOldHomeworkCache(Isar isar) async {
var now = timeNow();
var weeks = await isar.homeworkCacheModels.where().findAll();
var weeksToRemove = List<Id>.empty(growable: true);
for (var week in weeks) {
var date = getDate(week.cacheKey!);
if (date.millisecondsSinceEpoch <
now.subtract(Duration(days: 120)).millisecondsSinceEpoch) {
weeksToRemove.add(week.cacheKey!);
}
}
await isar.writeTxn(() async {
await isar.homeworkCacheModels.deleteAll(weeksToRemove);
});
}
@collection
class HomeworkDoneModel {
Id? id;
late String homeworkId;
late DateTime doneAt;
HomeworkDoneModel();
}
Future<void> markAsDone(Isar isar, String homeWorkUid) async {
await isar.writeTxn(() async {
await isar.homeworkDoneModels.put(
HomeworkDoneModel()
..homeworkId = homeWorkUid
..doneAt = DateTime.now(),
);
});
}
Future<void> markAsNotDone(Isar isar, String homeWorkUid) async {
await isar.writeTxn(() async {
final idsToDelete = await isar.homeworkDoneModels
.filter()
.homeworkIdEqualTo(homeWorkUid)
.idProperty()
.findAll();
await isar.homeworkDoneModels.deleteAll(idsToDelete);
});
}
Future<bool> isHomeworkDone(Isar isar, String homeWorkUid) async {
var existing = await isar.homeworkDoneModels
.filter()
.homeworkIdEqualTo(homeWorkUid)
.findFirst();
return existing != null;
}

View File

@@ -1,4 +1,4 @@
import 'package:firka/data/models/token_model.dart';
import 'db/models/token_model.dart';
int resolveActiveAccountIndex(dynamic settings) {
try {
@@ -8,7 +8,8 @@ int resolveActiveAccountIndex(dynamic settings) {
if (accountIndex is int && accountIndex >= 0) {
return accountIndex;
}
} catch (_) {}
} catch (_) {
}
return 0;
}

View File

@@ -1,22 +1,29 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:firka/data/models/generic_cache_model.dart';
import 'package:firka/data/models/timetable_cache_model.dart';
import 'package:firka/helpers/api/model/all_lessons.dart';
import 'package:firka/helpers/api/model/class_group.dart';
import 'package:firka/helpers/api/model/homework.dart';
import 'package:firka/helpers/api/model/timetable.dart';
import 'package:firka/helpers/db/models/generic_cache_model.dart';
import 'package:firka/helpers/db/models/timetable_cache_model.dart';
import 'package:intl/intl.dart';
import 'package:isar_community/isar.dart';
import 'package:kreta_api/kreta_api.dart' hide KretaEndpoints;
import 'package:isar/isar.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/core/bloc/reauth_cubit.dart';
import 'package:firka/data/models/token_model.dart';
import 'package:firka/data/util.dart';
import 'package:firka/core/debug_helper.dart';
import 'package:firka/services/active_account_helper.dart';
import 'package:firka/services/watch_sync_helper.dart';
import '../../../main.dart';
import '../../db/models/token_model.dart';
import '../../db/util.dart';
import '../../debug_helper.dart';
import '../../active_account_helper.dart';
import '../../watch_sync_helper.dart';
import '../consts.dart';
import '../exceptions/token.dart';
import '../model/grade.dart';
import '../model/notice_board.dart';
import '../model/omission.dart';
import '../model/student.dart';
import '../model/test.dart';
import '../token_grant.dart';
import 'dart:io';
@@ -29,63 +36,53 @@ const backoffCount = 4;
const backoffMin = 100;
const backoffStep = 500;
class ApiResponse<T> {
T? response;
int statusCode;
String? err;
bool cached;
ApiResponse(
this.response,
this.statusCode,
this.err,
this.cached,
);
@override
String toString() {
return "ApiResponse("
"response: $response, "
"statusCode: $statusCode, "
"err: \"$err\", "
"cached: $cached"
")";
}
}
class KretaClient {
Completer<void>? _tokenMutexCompleter;
bool _tokenMutex = false;
TokenModel model;
Isar isar;
final ReauthCubit _reauthCubit;
KretaClient(this.model, this.isar, this._reauthCubit);
static bool needsReauth = false;
bool get needsReauth => _reauthCubit.state.needsReauth;
static final ValueNotifier<bool> reauthStateNotifier = ValueNotifier(false);
void clearReauthFlag() {
_reauthCubit.clear();
static void clearReauthFlag() {
needsReauth = false;
reauthStateNotifier.value = false;
debugPrint('[KretaClient] Reauth flag cleared');
}
Future<void> _setReauthFlag() async {
static Future<void> _setReauthFlag() async {
if (needsReauth) return;
_reauthCubit.setNeedsReauth(true);
needsReauth = true;
reauthStateNotifier.value = true;
debugPrint('[KretaClient] Reauth flag set');
}
Future<TokenModel> _refreshModelWithCrossDeviceLease(
TokenModel sourceToken,
) async {
final studentIdNorm = sourceToken.studentIdNorm;
String? leaseOperationId;
try {
if (Platform.isIOS && studentIdNorm != null) {
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 && studentIdNorm != null && leaseOperationId != null) {
await WatchSyncHelper.releaseIPhoneRefreshLease(
studentIdNorm: studentIdNorm,
operationId: leaseOperationId,
);
}
}
}
KretaClient(this.model, this.isar);
Future<void> _syncTokenToAppleTargets(TokenModel token) async {
if (!Platform.isIOS) return;
@@ -95,14 +92,6 @@ class KretaClient {
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) {
@@ -152,15 +141,15 @@ class KretaClient {
if (localExpiry != null &&
localExpiry.isAfter(now.add(const Duration(seconds: 60)))) {
logger.info(
"[Recovery] Existing token is still valid, skipping recovery steps",
);
"[Recovery] Existing token is still valid, skipping recovery steps");
clearReauthFlag();
return true;
}
logger.info("[Recovery] Step 1: Trying local token refresh...");
try {
var tokenModel = await _refreshModelWithCrossDeviceLease(model);
var extended = await extendToken(model);
var tokenModel = TokenModel.fromResp(extended);
await isar.writeTxn(() async {
await isar.tokenModels.put(tokenModel);
@@ -176,9 +165,8 @@ class KretaClient {
}
if (!Platform.isIOS || !initDone) {
logger.warning(
"[Recovery] Not iOS or not initialized, cannot try iCloud",
);
logger
.warning("[Recovery] Not iOS or not initialized, cannot try iCloud");
return false;
}
@@ -195,45 +183,39 @@ class KretaClient {
break;
}
logger.info(
"[Recovery] Waiting ${delay}s before attempt ${attempt + 1}...",
);
"[Recovery] Waiting ${delay}s before attempt ${attempt + 1}...");
await Future.delayed(Duration(seconds: delay));
}
logger.info(
"[Recovery] iCloud attempt ${attempt + 1}/${retryDelays.length}...",
);
"[Recovery] iCloud attempt ${attempt + 1}/${retryDelays.length}...");
final recovered = await WatchSyncHelper.checkAndRecoverFromiCloud(
isar: isar,
tokens: initData.tokens,
client: this,
allowExpiredAccessToken: true,
);
if (recovered) {
iCloudHasToken = true;
await _reloadActiveTokenModel(
preferredStudentIdNorm: model.studentIdNorm,
);
preferredStudentIdNorm: model.studentIdNorm);
final recoveredExpiry = model.expiryDate;
if (recoveredExpiry != null &&
recoveredExpiry.isAfter(
timeNow().add(const Duration(seconds: 60)),
)) {
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",
);
"[Recovery] Step 2 SUCCESS on attempt ${attempt + 1}: usable iCloud token applied without immediate refresh");
clearReauthFlag();
return true;
}
logger.info(
"[Recovery] Found iCloud token close to expiry, trying refresh...",
);
"[Recovery] Found iCloud token close to expiry, trying refresh...");
try {
var tokenModel = await _refreshModelWithCrossDeviceLease(model);
var extended = await extendToken(model);
var tokenModel = TokenModel.fromResp(extended);
await isar.writeTxn(() async {
await isar.tokenModels.put(tokenModel);
@@ -246,14 +228,12 @@ class KretaClient {
return true;
} catch (e) {
logger.warning(
"[Recovery] iCloud token refresh failed on attempt ${attempt + 1}: $e",
);
"[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}",
);
"[Recovery] No fresh token in iCloud on attempt ${attempt + 1}");
if (attempt == 0) {
iCloudHasToken = false;
}
@@ -271,8 +251,7 @@ class KretaClient {
if (model.expiryDate == null ||
model.expiryDate!.isBefore(fiveMinutesFromNow)) {
logger.info(
"[Proactive] Token expired or expiring soon, starting recovery...",
);
"[Proactive] Token expired or expiring soon, starting recovery...");
final recovered = await recoverToken();
if (recovered) {
@@ -292,40 +271,28 @@ class KretaClient {
}
logger.fine(
"[Proactive] Token still valid until ${model.expiryDate}, no refresh needed",
);
"[Proactive] Token still valid until ${model.expiryDate}, no refresh needed");
return true;
}
Future<T> _mutexCallback<T>(Future<T> Function() callback) async {
const maxWaitTime = Duration(seconds: 30);
final startTime = DateTime.now();
if (_tokenMutexCompleter != null) {
try {
await _tokenMutexCompleter!.future.timeout(
maxWaitTime,
onTimeout: () {
logger.warning(
"[Mutex] Timeout waiting for token mutex, forcing release",
);
if (_tokenMutexCompleter != null &&
!_tokenMutexCompleter!.isCompleted) {
_tokenMutexCompleter!.complete();
}
},
);
} catch (_) {}
while (_tokenMutex) {
if (DateTime.now().difference(startTime) > maxWaitTime) {
logger.warning(
"[Mutex] Timeout waiting for token mutex, forcing release");
_tokenMutex = false;
break;
}
await Future.delayed(const Duration(milliseconds: 50));
}
_tokenMutexCompleter = Completer<void>();
_tokenMutex = true;
try {
return await callback();
} finally {
final completer = _tokenMutexCompleter;
_tokenMutexCompleter = null;
if (completer != null && !completer.isCompleted) {
completer.complete();
}
_tokenMutex = false;
}
}
@@ -336,8 +303,7 @@ class KretaClient {
if (now.millisecondsSinceEpoch >=
model.expiryDate!.millisecondsSinceEpoch) {
logger.info(
"Token expired at ${model.expiryDate}, starting recovery for user: ${model.studentId}",
);
"Token expired at ${model.expiryDate}, starting recovery for user: ${model.studentId}");
final recovered = await recoverToken();
if (!recovered) {
@@ -354,21 +320,15 @@ class KretaClient {
"accept": "*/*",
"user-agent": Constants.userAgent,
"authorization": "Bearer $localToken",
"apiKey": "21ff6c25-d1da-4a68-a811-c881a6057463",
"apiKey": "21ff6c25-d1da-4a68-a811-c881a6057463"
};
return await dio.get(
url,
options: Options(method: method, headers: headers),
data: data,
);
return await dio.get(url,
options: Options(method: method, headers: headers), data: data);
}
Future<(dynamic, int)> _authJson(
String method,
String url, [
Object? data,
]) async {
Future<(dynamic, int)> _authJson(String method, String url,
[Object? data]) async {
Response<dynamic> resp;
try {
@@ -384,17 +344,13 @@ class KretaClient {
(responseData is List && responseData.isEmpty) ||
(responseData is Map && responseData.isEmpty)) {
logger.warning(
"API returned ${resp.statusCode} with empty data for: $url - possible stale session",
);
"API returned ${resp.statusCode} with empty data for: $url - possible stale session");
}
}
} catch (ex) {
if (ex is Error) {
logger.shout(
"Request to url: $url failed",
ex.toString(),
ex.stackTrace,
);
"Request to url: $url failed", ex.toString(), ex.stackTrace);
} else {
logger.shout("Request to url: $url failed", ex.toString());
}
@@ -406,11 +362,7 @@ class KretaClient {
}
Future<(dynamic, int, Object?, bool)> _cachingGet(
CacheId id,
String url,
bool forceCache,
int counter,
) async {
CacheId id, String url, bool forceCache, int counter) async {
// it would be *ideal* to use xor and left shift here, however
// binary operations seem to round the number down to
// 32 bits for some reason???
@@ -422,8 +374,7 @@ class KretaClient {
try {
if (forceCache && cache != null) {
logger.finest(
"_cachingGet(forceCache: $forceCache}): decoding cached response for: $url",
);
"_cachingGet(forceCache: $forceCache}): decoding cached response for: $url");
return (jsonDecode(cache.cacheData!), 200, null, true);
}
@@ -433,18 +384,14 @@ class KretaClient {
if (statusCode >= 400) {
if (cache != null) {
logger.finest(
"_cachingGet(forceCache: $forceCache}): decoding uncached response for: $url",
);
"_cachingGet(forceCache: $forceCache}): decoding uncached response for: $url");
return (jsonDecode(cache.cacheData!), statusCode, null, true);
}
}
} catch (ex) {
if (ex is Error) {
logger.finest(
"Request failed for $url",
ex.toString(),
ex.stackTrace,
);
"Request failed for $url", ex.toString(), ex.stackTrace);
} else {
logger.finest("Request failed for $url", ex.toString());
}
@@ -503,12 +450,8 @@ class KretaClient {
} else if (studentCache != null) {
return studentCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getStudent,
KretaEndpoints.getStudentUrl(model.iss!),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getStudent,
KretaEndpoints.getStudentUrl(model.iss!), forceCache, 0);
Student? student;
String? err;
@@ -529,20 +472,15 @@ class KretaClient {
ApiResponse<List<ClassGroup>>? classGroupCache;
Future<ApiResponse<List<ClassGroup>>> getClassGroups({
bool forceCache = true,
}) async {
Future<ApiResponse<List<ClassGroup>>> getClassGroups(
{bool forceCache = true}) async {
if (!forceCache) {
classGroupCache = null;
} else {
if (classGroupCache != null) return classGroupCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getClassGroup,
KretaEndpoints.getClassGroups(model.iss!),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getClassGroup,
KretaEndpoints.getClassGroups(model.iss!), forceCache, 0);
final classGroups = List<ClassGroup>.empty(growable: true);
String? err;
@@ -566,20 +504,15 @@ class KretaClient {
ApiResponse<List<NoticeBoardItem>>? noticeBoardCache;
Future<ApiResponse<List<NoticeBoardItem>>> getNoticeBoard({
bool forceCache = true,
}) async {
Future<ApiResponse<List<NoticeBoardItem>>> getNoticeBoard(
{bool forceCache = true}) async {
if (!forceCache) {
noticeBoardCache = null;
} else if (noticeBoardCache != null) {
return noticeBoardCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getNoticeBoard,
KretaEndpoints.getNoticeBoard(model.iss!),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getNoticeBoard,
KretaEndpoints.getNoticeBoard(model.iss!), forceCache, 0);
var items = List<NoticeBoardItem>.empty(growable: true);
String? err;
@@ -603,16 +536,11 @@ class KretaClient {
ApiResponse<List<InfoBoardItem>>? infoBoardCache;
Future<ApiResponse<List<InfoBoardItem>>> getInfoBoard({
bool forceCache = true,
}) async {
Future<ApiResponse<List<InfoBoardItem>>> getInfoBoard(
{bool forceCache = true}) async {
if (forceCache && infoBoardCache != null) return infoBoardCache!;
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getInfoBoard,
KretaEndpoints.getInfoBoard(model.iss!),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getInfoBoard,
KretaEndpoints.getInfoBoard(model.iss!), forceCache, 0);
var items = List<InfoBoardItem>.empty(growable: true);
String? err;
@@ -643,11 +571,7 @@ class KretaClient {
return gradeCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getGrades,
KretaEndpoints.getGrades(model.iss!),
forceCache,
0,
);
CacheId.getGrades, KretaEndpoints.getGrades(model.iss!), forceCache, 0);
var items = List<Grade>.empty(growable: true);
String? err;
@@ -674,19 +598,14 @@ class KretaClient {
ApiResponse<List<SubjectAverage>>? subjectAverageCache;
Future<ApiResponse<List<SubjectAverage>>> getSubjectAverage(
ClassGroup classGroup, {
bool forceCache = true,
}) async {
ClassGroup classGroup,
{bool forceCache = true}) async {
String? err;
if (classGroup.studyTask == null) {
err = "classGroup.studyTask is null";
logger.warning(err);
return ApiResponse(
List<SubjectAverage>.empty(growable: true),
0,
err,
false,
);
List<SubjectAverage>.empty(growable: true), 0, err, false);
}
if (!forceCache) {
subjectAverageCache = null;
@@ -694,12 +613,8 @@ class KretaClient {
return subjectAverageCache!;
}
var studyTaskUid = classGroup.studyTask!.uid.toString().split(",").first;
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getSubjectAvg,
KretaEndpoints.getSubjectAvg(model.iss!, studyTaskUid),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getSubjectAvg,
KretaEndpoints.getSubjectAvg(model.iss!, studyTaskUid), forceCache, 0);
var items = List<SubjectAverage>.empty(growable: true);
try {
@@ -720,15 +635,14 @@ class KretaClient {
}
Future<(List<dynamic>, int, Object?, bool)>
_timedCachingGet<T extends DatedCacheEntry>(
IsarCollection<T> cacheModel,
String endpoint,
DateTime from,
DateTime? to,
bool forceCache,
int counter,
Future<void> Function(dynamic, int) storeCache,
) async {
_timedCachingGet<T extends DatedCacheEntry>(
IsarCollection<T> cacheModel,
String endpoint,
DateTime from,
DateTime? to,
bool forceCache,
int counter,
Future<void> Function(dynamic, int) storeCache) async {
var cacheKey = genCacheKey(from, model.studentIdNorm!);
var cache = await cacheModel.get(cacheKey);
var formatter = DateFormat('yyyy-MM-dd');
@@ -754,16 +668,14 @@ class KretaClient {
try {
if (toStr == null) {
(resp, statusCode) = await _authJson(
"GET",
"$endpoint?"
"datumTol=$fromStr",
);
"GET",
"$endpoint?"
"datumTol=$fromStr");
} else {
(resp, statusCode) = await _authJson(
"GET",
"$endpoint?"
"datumTol=$fromStr&datumIg=$toStr",
);
"GET",
"$endpoint?"
"datumTol=$fromStr&datumIg=$toStr");
}
if (statusCode >= 400) {
@@ -783,25 +695,16 @@ class KretaClient {
}
await Future.delayed(
Duration(milliseconds: backoffMin + (counter * backoffStep)),
);
Duration(milliseconds: backoffMin + (counter * backoffStep)));
return _timedCachingGet(
cacheModel,
endpoint,
from,
to,
forceCache,
counter + 1,
storeCache,
);
return _timedCachingGet(cacheModel, endpoint, from, to, forceCache,
counter + 1, storeCache);
}
} catch (ex) {
if (_isTokenExpired(ex)) {
await _setReauthFlag();
logger.warning(
"Token expired in timed request, setting needsReauth flag",
);
"Token expired in timed request, setting needsReauth flag");
}
if (cache != null) {
@@ -832,36 +735,27 @@ class KretaClient {
/// Expects from and to to be 7 days apart
Future<ApiResponse<List<Lesson>>> _getTimeTable(
DateTime from,
DateTime to,
bool forceCache,
) async {
var (
resp,
status,
ex,
cached,
) = await _timedCachingGet<TimetableCacheModel>(
isar.timetableCacheModels,
KretaEndpoints.getTimeTable(model.iss!),
from,
to,
forceCache,
0,
(dynamic resp, int cacheKey) async {
TimetableCacheModel cache = TimetableCacheModel();
var rawClasses = List<String>.empty(growable: true);
DateTime from, DateTime to, bool forceCache) async {
var (resp, status, ex, cached) =
await _timedCachingGet<TimetableCacheModel>(
isar.timetableCacheModels,
KretaEndpoints.getTimeTable(model.iss!),
from,
to,
forceCache,
0, (dynamic resp, int cacheKey) async {
TimetableCacheModel cache = TimetableCacheModel();
var rawClasses = List<String>.empty(growable: true);
for (var obj in resp) {
rawClasses.add(jsonEncode(obj));
}
for (var obj in resp) {
rawClasses.add(jsonEncode(obj));
}
cache.cacheKey = cacheKey;
cache.values = rawClasses;
cache.cacheKey = cacheKey;
cache.values = rawClasses;
await isar.timetableCacheModels.put(cache as dynamic);
},
);
await isar.timetableCacheModels.put(cache as dynamic);
});
var items = List<Lesson>.empty(growable: true);
String? err;
@@ -881,18 +775,16 @@ class KretaClient {
return ApiResponse(items, status, err, cached);
}
Future<ApiResponse<List<Homework>>> getHomework({
bool forceCache = true,
}) async {
Future<ApiResponse<List<Homework>>> getHomework(
{bool forceCache = true}) async {
final now = timeNow().subtract(Duration(days: 365));
var formatter = DateFormat('yyyy-MM-dd');
var start = formatter.format(now);
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getHomework,
"${KretaEndpoints.getHomework(model.iss!)}?datumTol=$start",
forceCache,
0,
);
CacheId.getHomework,
"${KretaEndpoints.getHomework(model.iss!)}?datumTol=$start",
forceCache,
0);
var items = List<Homework>.empty(growable: true);
String? err;
@@ -915,20 +807,15 @@ class KretaClient {
}
/// Automatically aligns requests to start at Monday and end at Sunday
Future<ApiResponse<List<Lesson>>> getTimeTable(
DateTime from,
DateTime to, {
bool forceCache = true,
}) async {
Future<ApiResponse<List<Lesson>>> getTimeTable(DateTime from, DateTime to,
{bool forceCache = true}) async {
var lessons = List<Lesson>.empty(growable: true);
String? err;
bool cached = true;
for (
var i = from.millisecondsSinceEpoch;
i < to.millisecondsSinceEpoch;
i += 604800000
) {
for (var i = from.millisecondsSinceEpoch;
i < to.millisecondsSinceEpoch;
i += 604800000) {
var from = DateTime.fromMillisecondsSinceEpoch(i);
var start = from.subtract(Duration(days: from.weekday - 1));
var end = start.add(Duration(days: 6));
@@ -950,16 +837,14 @@ class KretaClient {
lessons.sort((a, b) => a.start.compareTo(b.start));
lessons = lessons
.where(
(lesson) => lesson.start.isAfter(from) && lesson.end.isBefore(to),
)
(lesson) => lesson.start.isAfter(from) && lesson.end.isBefore(to))
.toList();
return ApiResponse(lessons, 200, err, cached);
}
Future<ApiResponse<List<AllLessons>>> getLessons({
bool forceCache = true,
}) async {
Future<ApiResponse<List<AllLessons>>> getLessons(
{bool forceCache = true}) async {
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getLessons,
KretaEndpoints.getLessons(model.iss!),
@@ -996,11 +881,7 @@ class KretaClient {
Future<ApiResponse<List<Test>>> getTests({bool forceCache = true}) async {
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getTests,
KretaEndpoints.getTests(model.iss!),
forceCache,
0,
);
CacheId.getTests, KretaEndpoints.getTests(model.iss!), forceCache, 0);
var items = List<Test>.empty(growable: true);
String? err;
@@ -1024,20 +905,15 @@ class KretaClient {
ApiResponse<List<Omission>>? omissionsCache;
Future<ApiResponse<List<Omission>>> getOmissions({
bool forceCache = true,
}) async {
Future<ApiResponse<List<Omission>>> getOmissions(
{bool forceCache = true}) async {
if (!forceCache) {
omissionsCache = null;
} else {
if (omissionsCache != null) return omissionsCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getOmissions,
KretaEndpoints.getOmissions(model.iss!),
forceCache,
0,
);
var (resp, status, ex, cached) = await _cachingGet(CacheId.getOmissions,
KretaEndpoints.getOmissions(model.iss!), forceCache, 0);
var items = List<Omission>.empty(growable: true);
String? err;

View File

@@ -1,5 +1,12 @@
import 'package:kreta_api/kreta_api.dart';
import 'package:firka/helpers/api/model/class_group.dart';
import 'package:firka/helpers/api/model/homework.dart';
import 'package:firka/helpers/api/model/notice_board.dart';
import 'package:firka/helpers/api/model/omission.dart';
import 'package:firka/helpers/api/model/test.dart';
import 'package:firka/helpers/api/model/timetable.dart';
import '../model/grade.dart';
import '../model/student.dart';
import 'kreta_client.dart';
bool getStudentFL = false;
@@ -14,9 +21,8 @@ bool getTestsStreamFL = false;
bool getOmissionsStreamFL = false;
extension KretaStream on KretaClient {
Stream<ApiResponse<Student>> getStudentStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<Student>> getStudentStream(
{bool cacheOnly = true}) async* {
while (getStudentFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -29,9 +35,8 @@ extension KretaStream on KretaClient {
getStudentFL = false;
}
Stream<ApiResponse<List<ClassGroup>>> getClassGroupsStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<ClassGroup>>> getClassGroupsStream(
{bool cacheOnly = true}) async* {
while (getClassGroupsFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -44,9 +49,8 @@ extension KretaStream on KretaClient {
getClassGroupsFL = false;
}
Stream<ApiResponse<List<NoticeBoardItem>>> getNoticeBoardStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<NoticeBoardItem>>> getNoticeBoardStream(
{bool cacheOnly = true}) async* {
while (getNoticeBoardStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -59,9 +63,8 @@ extension KretaStream on KretaClient {
getNoticeBoardStreamFL = false;
}
Stream<ApiResponse<List<InfoBoardItem>>> getInfoBoardStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<InfoBoardItem>>> getInfoBoardStream(
{bool cacheOnly = true}) async* {
while (getInfoBoardStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -74,9 +77,8 @@ extension KretaStream on KretaClient {
getInfoBoardStreamFL = false;
}
Stream<ApiResponse<List<Grade>>> getGradesStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<Grade>>> getGradesStream(
{bool cacheOnly = true}) async* {
while (getGradesStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -90,9 +92,8 @@ extension KretaStream on KretaClient {
}
Stream<ApiResponse<List<SubjectAverage>>> getSubjectAverageStream(
ClassGroup classGroup, {
bool cacheOnly = true,
}) async* {
ClassGroup classGroup,
{bool cacheOnly = true}) async* {
while (getSubjectAverageStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -105,9 +106,8 @@ extension KretaStream on KretaClient {
getSubjectAverageStreamFL = false;
}
Stream<ApiResponse<List<Homework>>> getHomeworkStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<Homework>>> getHomeworkStream(
{bool cacheOnly = true}) async* {
while (getHomeworkStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -121,10 +121,8 @@ extension KretaStream on KretaClient {
}
Stream<ApiResponse<List<Lesson>>> getTimeTableStream(
DateTime from,
DateTime to, {
bool cacheOnly = true,
}) async* {
DateTime from, DateTime to,
{bool cacheOnly = true}) async* {
while (getTimeTableStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -137,9 +135,8 @@ extension KretaStream on KretaClient {
getTimeTableStreamFL = false;
}
Stream<ApiResponse<List<Test>>> getTestsStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<Test>>> getTestsStream(
{bool cacheOnly = true}) async* {
while (getTestsStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}
@@ -152,9 +149,8 @@ extension KretaStream on KretaClient {
getTestsStreamFL = false;
}
Stream<ApiResponse<List<Omission>>> getOmissionsStream({
bool cacheOnly = true,
}) async* {
Stream<ApiResponse<List<Omission>>> getOmissionsStream(
{bool cacheOnly = true}) async* {
while (getOmissionsStreamFL) {
await Future.delayed(Duration(milliseconds: 10));
}

View File

@@ -1,5 +1,5 @@
import 'package:dio/dio.dart';
import 'package:kreta_api/kreta_api.dart';
import 'package:firka/helpers/api/model/timetable.dart';
import 'package:logging/logging.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
@@ -55,8 +55,7 @@ class LiveActivityBackendClient {
'roomName': lesson.roomName,
'isSubstitution': lesson.substituteTeacher != null,
'substituteTeacher': lesson.substituteTeacher,
'isCancelled':
lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'isCancelled': lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'lastModified': validLastModified.toIso8601String(),
};
}).toList();
@@ -87,9 +86,7 @@ class LiveActivityBackendClient {
requestData['liveActivityEnabled'] = liveActivityEnabled;
}
_logger.info(
'Registering device with backend. Sending ${lessonsData.length} lessons.',
);
_logger.info('Registering device with backend. Sending ${lessonsData.length} lessons.');
if (_logger.isLoggable(Level.FINE)) {
for (var lesson in lessonsData) {
_logger.fine(' Lesson data: $lesson');
@@ -102,9 +99,7 @@ class LiveActivityBackendClient {
);
if (response.statusCode == 200 || response.statusCode == 201) {
_logger.info(
'Device registered successfully with ${timetable.length} lessons',
);
_logger.info('Device registered successfully with ${timetable.length} lessons');
return true;
}
@@ -141,15 +136,12 @@ class LiveActivityBackendClient {
'roomName': lesson.roomName,
'isSubstitution': lesson.substituteTeacher != null,
'substituteTeacher': lesson.substituteTeacher,
'isCancelled':
lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'isCancelled': lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'lastModified': validLastModified.toIso8601String(),
};
}).toList();
_logger.info(
'Updating timetable with backend. Sending ${lessonsData.length} lessons.',
);
_logger.info('Updating timetable with backend. Sending ${lessonsData.length} lessons.');
if (_logger.isLoggable(Level.FINE)) {
for (var lesson in lessonsData) {
_logger.fine(' Lesson data: $lesson');
@@ -185,11 +177,15 @@ class LiveActivityBackendClient {
}
/// Unregister device (called when user logs out)
Future<bool> unregisterDevice({required String deviceToken}) async {
Future<bool> unregisterDevice({
required String deviceToken,
}) async {
try {
final response = await _dio.delete(
'/live-activity/unregister',
data: {'deviceToken': deviceToken},
data: {
'deviceToken': deviceToken,
},
);
if (response.statusCode == 200) {
@@ -232,11 +228,15 @@ class LiveActivityBackendClient {
}
/// Get current timetable from backend
Future<List<Lesson>?> getTimetable({required String deviceToken}) async {
Future<List<Lesson>?> getTimetable({
required String deviceToken,
}) async {
try {
final response = await _dio.get(
'/live-activity/timetable',
queryParameters: {'deviceToken': deviceToken},
queryParameters: {
'deviceToken': deviceToken,
},
);
if (response.statusCode == 200 && response.data is Map) {
@@ -261,7 +261,10 @@ class LiveActivityBackendClient {
try {
final response = await _dio.post(
'/live-activity/push-token',
data: {'deviceToken': deviceToken, 'pushToken': pushToken},
data: {
'deviceToken': deviceToken,
'pushToken': pushToken,
},
);
if (response.statusCode == 200) {
@@ -285,7 +288,10 @@ class LiveActivityBackendClient {
try {
final response = await _dio.post(
'/live-activity/apns-token',
data: {'deviceToken': deviceToken, 'apnsPushToken': apnsPushToken},
data: {
'deviceToken': deviceToken,
'apnsPushToken': apnsPushToken,
},
);
if (response.statusCode == 200) {
@@ -293,9 +299,7 @@ class LiveActivityBackendClient {
return true;
}
_logger.warning(
'Failed to update APNs push token: ${response.statusCode}',
);
_logger.warning('Failed to update APNs push token: ${response.statusCode}');
return false;
} catch (e) {
_logger.severe('Error updating APNs push token: $e');
@@ -304,11 +308,15 @@ class LiveActivityBackendClient {
}
/// Send a test notification (for debugging)
Future<bool> sendTestNotification({required String deviceToken}) async {
Future<bool> sendTestNotification({
required String deviceToken,
}) async {
try {
final response = await _dio.post(
'/live-activity/test-notification',
data: {'deviceToken': deviceToken},
data: {
'deviceToken': deviceToken,
},
);
if (response.statusCode == 200) {
@@ -316,9 +324,7 @@ class LiveActivityBackendClient {
return true;
}
_logger.warning(
'Failed to send test notification: ${response.statusCode}',
);
_logger.warning('Failed to send test notification: ${response.statusCode}');
return false;
} catch (e) {
_logger.severe('Error sending test notification: $e');
@@ -334,7 +340,10 @@ class LiveActivityBackendClient {
try {
final response = await _dio.put(
'/live-activity/language',
data: {'deviceToken': deviceToken, 'language': language},
data: {
'deviceToken': deviceToken,
'language': language,
},
);
if (response.statusCode == 200) {
@@ -358,7 +367,10 @@ class LiveActivityBackendClient {
try {
final response = await _dio.put(
'/live-activity/bell-delay',
data: {'deviceToken': deviceToken, 'bellDelay': bellDelay},
data: {
'deviceToken': deviceToken,
'bellDelay': bellDelay,
},
);
if (response.statusCode == 200) {
@@ -385,25 +397,17 @@ class LiveActivityBackendClient {
'/live-activity/morning-notification',
data: {
'deviceToken': deviceToken,
...?(morningNotificationTime != null
? {'morningNotificationTime': morningNotificationTime}
: null),
...?(morningNotificationEnabled != null
? {'morningNotificationEnabled': morningNotificationEnabled}
: null),
if (morningNotificationTime != null) 'morningNotificationTime': morningNotificationTime,
if (morningNotificationEnabled != null) 'morningNotificationEnabled': morningNotificationEnabled,
},
);
if (response.statusCode == 200) {
_logger.info(
'Morning notification settings updated successfully: enabled=$morningNotificationEnabled, time=$morningNotificationTime',
);
_logger.info('Morning notification settings updated successfully: enabled=$morningNotificationEnabled, time=$morningNotificationTime');
return true;
}
_logger.warning(
'Failed to update morning notification settings: ${response.statusCode}',
);
_logger.warning('Failed to update morning notification settings: ${response.statusCode}');
return false;
} catch (e) {
_logger.severe('Error updating morning notification settings: $e');
@@ -426,9 +430,7 @@ class LiveActivityBackendClient {
);
if (response.statusCode == 200) {
_logger.info(
'Live Activity ${liveActivityEnabled ? "enabled" : "disabled"} successfully',
);
_logger.info('Live Activity ${liveActivityEnabled ? "enabled" : "disabled"} successfully');
return true;
}
@@ -440,3 +442,4 @@ class LiveActivityBackendClient {
}
}
}

View File

@@ -4,8 +4,7 @@ import 'dart:math';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:firka/app/app_state.dart';
import 'package:kreta_api/kreta_api.dart' as ka;
import 'package:firka/main.dart';
class Constants {
static String get clientId {
@@ -42,6 +41,8 @@ class TimetableConsts {
}
class KretaEndpoints {
static String kretaBase = "e-kreta.hu";
static String _generateCodeVerifier() {
var random = Random.secure();
final bytes = List<int>.generate(32, (i) => random.nextInt(256));
@@ -63,7 +64,13 @@ class KretaEndpoints {
return base64Url.encode(bytes).replaceAll('=', '');
}
static String kreta(String iss) => ka.KretaEndpoints.kreta(iss);
static String kreta(String iss) {
if (iss == "firka-test") {
return kretaBase;
} else {
return "https://$iss.$kretaBase";
}
}
static final String codeVerifier = _generateCodeVerifier();
static final String _codeChallenge = _generateCodeChallenge(codeVerifier);
@@ -79,28 +86,38 @@ class KretaEndpoints {
static String tokenGrantUrl = "$kretaIdp/connect/token";
static String getStudentUrl(String iss) =>
ka.KretaEndpoints.getStudentUrl(iss);
"${kreta(iss)}/ellenorzo/v3/sajat/TanuloAdatlap";
static String getClassGroups(String iss) =>
ka.KretaEndpoints.getClassGroups(iss);
"${kreta(iss)}/ellenorzo/v3/sajat/OsztalyCsoportok";
static String getNoticeBoard(String iss) =>
ka.KretaEndpoints.getNoticeBoard(iss);
"${kreta(iss)}/ellenorzo/v3/sajat/FaliujsagElemek";
static String getInfoBoard(String iss) => ka.KretaEndpoints.getInfoBoard(iss);
// for some reason the [redacted] devs decided to make
// two different apis to get items for the notice board
// that appears on the home screen, like wtf
static String getInfoBoard(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/Feljegyzesek";
static String getGrades(String iss) => ka.KretaEndpoints.getGrades(iss);
static String getGrades(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek";
static String getSubjectAvg(String iss, String studyGroupId) =>
ka.KretaEndpoints.getSubjectAvg(iss, studyGroupId);
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek/Atlagok/TantargyiAtlagok?oktatasiNevelesiFeladatUid=$studyGroupId&oktatasiNevelesiFeladatUid=$studyGroupId";
static String getTimeTable(String iss) => ka.KretaEndpoints.getTimeTable(iss);
static String getTimeTable(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/OrarendElemek";
static String getOmissions(String iss) => ka.KretaEndpoints.getOmissions(iss);
static String getOmissions(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/Mulasztasok";
static String getHomework(String iss) => ka.KretaEndpoints.getHomework(iss);
static String getHomework(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/HaziFeladatok";
static String getTests(String iss) => ka.KretaEndpoints.getTests(iss);
static String getLessons(String iss) => ka.KretaEndpoints.getLessons(iss);
}
static String getTests(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/BejelentettSzamonkeresek";
static String getLessons(String iss) =>
"${kreta(iss)}/dktapi/intezmenyek/munkaterek/tanulok";
}

View File

@@ -0,0 +1,132 @@
import 'dart:convert';
class AllLessons {
final String schoolId;
final String yearId;
final dynamic classId;
final String? className;
final bool classWorkspace;
final dynamic groupId;
final String? groupName;
final bool groupWorkspace;
final String groupWorkspaceName;
final dynamic subjectId;
final String subjectName;
final dynamic teacherId;
final String teacherGuid;
final String teacherName;
final dynamic teacherAnnoId;
final dynamic annoId;
final String? languageId;
final dynamic subjectCategoryId;
final String subjectCategoryName;
final dynamic typeId;
final String typeName;
final dynamic gradeTypeId;
final String gradeTypeName;
final dynamic taskPlaceId;
final String taskPlaceName;
final dynamic teacherAvatarTypeId;
final String teacherAvatarTypePath;
final dynamic taskGroupId;
AllLessons({
required this.schoolId,
required this.yearId,
this.classId,
this.className,
required this.classWorkspace,
this.groupId,
this.groupName,
required this.groupWorkspace,
required this.groupWorkspaceName,
required this.subjectId,
required this.subjectName,
required this.teacherId,
required this.teacherGuid,
required this.teacherName,
this.teacherAnnoId,
this.annoId,
this.languageId,
required this.subjectCategoryId,
required this.subjectCategoryName,
required this.typeId,
required this.typeName,
required this.gradeTypeId,
required this.gradeTypeName,
required this.taskPlaceId,
required this.taskPlaceName,
required this.teacherAvatarTypeId,
required this.teacherAvatarTypePath,
this.taskGroupId,
});
factory AllLessons.fromJson(Map<String, dynamic> json) => AllLessons(
schoolId: json['intezmenyId']?.toString() ?? '',
yearId: json['tanevId']?.toString() ?? '',
classId: json['osztalyId'],
className: json['osztalyNev']?.toString(),
classWorkspace: json['osztalyMunkaTer'] == true,
groupId: json['csoportId'],
groupName: json['csoportNev']?.toString(),
groupWorkspace: json['csoportMunkaTer'] == true,
groupWorkspaceName: json['osztalyCsoportNev']?.toString() ?? '',
subjectId: json['tantargyId'],
subjectName: json['tantargyNev']?.toString() ?? '',
teacherId: json['alkalmazottId'],
teacherGuid: json['alkalmazottGuid']?.toString() ?? '',
teacherName: json['alkalmazottNev']?.toString() ?? '',
teacherAnnoId: json['alkalmazottUzenoFalId'],
annoId: json['uzenoFalId'],
languageId: json['nyelvId']?.toString(),
subjectCategoryId: json['tantargyKategoriaId'],
subjectCategoryName: json['tantargyKategoriaNev']?.toString() ?? '',
typeId: json['tipusId'],
typeName: json['tipusNev']?.toString() ?? '',
gradeTypeId: json['evfolyamTipusId'],
gradeTypeName: json['evfolyamTipusNev']?.toString() ?? '',
taskPlaceId: json['feladatEllatasiHelyId'],
taskPlaceName: json['feladatEllatasiHelyNev']?.toString() ?? '',
teacherAvatarTypeId: json['alkalmazottAvatarTipusId'],
teacherAvatarTypePath:
json['alkalmazottAvatarEleres']?.toString() ?? '',
taskGroupId: json['oraiFeladatGroupId'],
);
Map<String, dynamic> toJson() => {
'intezmenyId': schoolId,
'tanevId': yearId,
'osztalyId': classId,
'osztalyNev': className,
'osztalyMunkaTer': classWorkspace,
'csoportId': groupId,
'csoportNev': groupName,
'csoportMunkaTer': groupWorkspace,
'osztalyCsoportNev': groupWorkspaceName,
'tantargyId': subjectId,
'tantargyNev': subjectName,
'alkalmazottId': teacherId,
'alkalmazottGuid': teacherGuid,
'alkalmazottNev': teacherName,
'alkalmazottUzenoFalId': teacherAnnoId,
'uzenoFalId': annoId,
'nyelvId': languageId,
'tantargyKategoriaId': subjectCategoryId,
'tantargyKategoriaNev': subjectCategoryName,
'tipusId': typeId,
'tipusNev': typeName,
'evfolyamTipusId': gradeTypeId,
'evfolyamTipusNev': gradeTypeName,
'feladatEllatasiHelyId': taskPlaceId,
'feladatEllatasiHelyNev': taskPlaceName,
'alkalmazottAvatarTipusId': teacherAvatarTypeId,
'alkalmazottAvatarEleres': teacherAvatarTypePath,
'oraiFeladatGroupId': taskGroupId,
};
}
List<AllLessons> lessonsFromJson(String str) =>
List<AllLessons>.from(json.decode(str).map((x) => AllLessons.fromJson(x)));
String lessonsToJson(List<AllLessons> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

View File

@@ -1,4 +1,4 @@
import 'generic.dart';
import 'package:firka/helpers/api/model/generic.dart';
class ClassGroup {
final String uid;
@@ -11,36 +11,34 @@ class ClassGroup {
final bool isActive;
final String type;
ClassGroup({
required this.uid,
required this.name,
required this.headTeacher,
required this.substituteHeadTeacher,
required this.studyGroup,
required this.studyGroupSortIndex,
required this.studyTask,
required this.isActive,
required this.type,
});
ClassGroup(
{required this.uid,
required this.name,
required this.headTeacher,
required this.substituteHeadTeacher,
required this.studyGroup,
required this.studyGroupSortIndex,
required this.studyTask,
required this.isActive,
required this.type});
factory ClassGroup.fromJson(Map<String, dynamic> json) {
return ClassGroup(
uid: json['Uid'],
name: json['Nev'],
headTeacher: json['OsztalyFonok'] != null
? UidObj.fromJson(json['OsztalyFonok'])
: null,
substituteHeadTeacher: json['OsztalyFonokHelyettes'] != null
? UidObj.fromJson(json['OsztalyFonokHelyettes'])
: null,
studyGroup: NameUidDesc.fromJson(json['OktatasNevelesiKategoria']),
studyGroupSortIndex: json['OktatasNevelesiKategoriaSortIndex'],
studyTask: json['OktatasNevelesiFeladat'] != null
? NameUidDesc.fromJson(json['OktatasNevelesiFeladat'])
: null,
isActive: json['IsAktiv'],
type: json['Tipus'],
);
uid: json['Uid'],
name: json['Nev'],
headTeacher: json['OsztalyFonok'] != null
? UidObj.fromJson(json['OsztalyFonok'])
: null,
substituteHeadTeacher: json['OsztalyFonokHelyettes'] != null
? UidObj.fromJson(json['OsztalyFonokHelyettes'])
: null,
studyGroup: NameUidDesc.fromJson(json['OktatasNevelesiKategoria']),
studyGroupSortIndex: json['OktatasNevelesiKategoriaSortIndex'],
studyTask: json['OktatasNevelesiFeladat'] != null
? NameUidDesc.fromJson(json['OktatasNevelesiFeladat'])
: null,
isActive: json['IsAktiv'],
type: json['Tipus']);
}
@override

View File

@@ -3,18 +3,12 @@ class NameUidDesc {
final String? name;
final String? description;
NameUidDesc({
required this.uid,
required this.name,
required this.description,
});
NameUidDesc(
{required this.uid, required this.name, required this.description});
factory NameUidDesc.fromJson(Map<String, dynamic> json) {
return NameUidDesc(
uid: json['Uid'],
name: json['Nev'],
description: json['Leiras'],
);
uid: json['Uid'], name: json['Nev'], description: json['Leiras']);
}
Map<String, dynamic> toJson() {
@@ -35,14 +29,23 @@ class NameUid {
final String uid;
final String name;
NameUid({required this.uid, required this.name});
NameUid({
required this.uid,
required this.name,
});
factory NameUid.fromJson(Map<String, dynamic> json) {
return NameUid(uid: json['Uid'], name: json['Nev']);
return NameUid(
uid: json['Uid'],
name: json['Nev'],
);
}
Map<String, dynamic> toJson() {
return {'Uid': uid, 'Nev': name};
return {
'Uid': uid,
'Nev': name,
};
}
}
@@ -52,7 +55,9 @@ class UidObj {
UidObj({required this.uid});
factory UidObj.fromJson(Map<String, dynamic> json) {
return UidObj(uid: json['Uid']);
return UidObj(
uid: json['Uid'],
);
}
@override

View File

@@ -1,5 +1,5 @@
import 'generic.dart';
import 'subject.dart';
import 'package:firka/helpers/api/model/generic.dart';
import 'package:firka/helpers/api/model/subject.dart';
class Grade {
final String uid;
@@ -20,25 +20,24 @@ class Grade {
final UidObj? classGroup;
final int sortIndex;
Grade({
required this.uid,
required this.recordDate,
required this.creationDate,
this.ackDate,
required this.subject,
this.topic,
required this.type,
this.mode,
required this.valueType,
required this.teacher,
this.kind,
this.numericValue,
required this.strValue,
this.weightPercentage,
this.shortStrValue,
this.classGroup,
required this.sortIndex,
});
Grade(
{required this.uid,
required this.recordDate,
required this.creationDate,
this.ackDate,
required this.subject,
this.topic,
required this.type,
this.mode,
required this.valueType,
required this.teacher,
this.kind,
this.numericValue,
required this.strValue,
this.weightPercentage,
this.shortStrValue,
this.classGroup,
required this.sortIndex});
factory Grade.fromJson(Map<String, dynamic> json) {
return Grade(
@@ -66,28 +65,6 @@ class Grade {
);
}
Map<String, dynamic> toJson() {
return {
'Uid': uid,
'RogzitesDatuma': recordDate.toUtc().toIso8601String(),
'KeszitesDatuma': creationDate.toUtc().toIso8601String(),
'LattamozasDatuma': ackDate?.toUtc().toIso8601String(),
'Tantargy': subject.toJson(),
'Tema': topic,
'Tipus': type.toJson(),
'Mod': mode?.toJson(),
'ErtekFajta': valueType.toJson(),
'ErtekeloTanarNeve': teacher,
'Kind': kind,
'SzamErtek': numericValue,
'SzovegesErtek': strValue,
'SulySzazalekErteke': weightPercentage,
'SzovegesErtekelesRovidNev': shortStrValue,
'OsztalyCsoport': classGroup != null ? {'Uid': classGroup!.uid} : null,
'SortIndex': sortIndex,
};
}
@override
String toString() {
return 'Grade('

View File

@@ -5,22 +5,20 @@ class Guardian {
final String? phoneNumber;
final String uid;
Guardian({
required this.email,
required this.isLegalRepresentative,
required this.name,
required this.phoneNumber,
required this.uid,
});
Guardian(
{required this.email,
required this.isLegalRepresentative,
required this.name,
required this.phoneNumber,
required this.uid});
factory Guardian.fromJson(Map<String, dynamic> json) {
return Guardian(
email: json['EmailCim'],
isLegalRepresentative: json['IsTorvenyesKepviselo'],
name: json['Nev'],
phoneNumber: json['Telefonszam'],
uid: json['Uid'],
);
email: json['EmailCim'],
isLegalRepresentative: json['IsTorvenyesKepviselo'],
name: json['Nev'],
phoneNumber: json['Telefonszam'],
uid: json['Uid']);
}
@override

View File

@@ -0,0 +1,70 @@
import 'package:firka/helpers/api/model/subject.dart';
import 'generic.dart';
class Homework {
final String uid;
final Subject subject;
final String subjectName;
final String teacherName;
final String description;
final DateTime startDate;
final DateTime dueDate;
final DateTime creationDate;
final bool isCreatedByTeacher;
final bool isDone;
final bool canBeSubmitted;
final UidObj classGroup;
final bool canAttach;
Homework(
{required this.uid,
required this.subject,
required this.subjectName,
required this.teacherName,
required this.description,
required this.startDate,
required this.dueDate,
required this.creationDate,
required this.isCreatedByTeacher,
required this.isDone,
required this.canBeSubmitted,
required this.classGroup,
required this.canAttach});
factory Homework.fromJson(Map<String, dynamic> json) {
return Homework(
uid: json["Uid"],
subject: Subject.fromJson(json["Tantargy"]),
subjectName: json["TantargyNeve"],
teacherName: json["RogzitoTanarNeve"],
description: json["Szoveg"],
startDate: DateTime.parse(json["FeladasDatuma"]).toLocal(),
dueDate: DateTime.parse(json["HataridoDatuma"]).toLocal(),
creationDate: DateTime.parse(json["RogzitesIdopontja"]).toLocal(),
isCreatedByTeacher: json["IsTanarRogzitette"],
isDone: json["IsMegoldva"],
canBeSubmitted: json["IsBeadhato"],
classGroup: UidObj.fromJson(json["OsztalyCsoport"]),
canAttach: json["IsCsatolasEngedelyezes"]);
}
@override
String toString() {
return 'Homework('
'uid: "$uid", '
'subject: $subject, '
'subjectName: "$subjectName", '
'teacherName: "$teacherName", '
'description: "$description", '
'startDate: $startDate, '
'dueDate: $dueDate, '
'creationDate: $creationDate, '
'isCreatedByTeacher: $isCreatedByTeacher, '
'isDone: $isDone, '
'canBeSubmitted: $canBeSubmitted, '
'classGroup: $classGroup, '
'canAttach: $canAttach'
')';
}
}

View File

@@ -4,12 +4,11 @@ class Institution {
final List<SystemModule> systemModuleList;
final String uid;
Institution({
required this.customizationSettings,
required this.shortName,
required this.systemModuleList,
required this.uid,
});
Institution(
{required this.customizationSettings,
required this.shortName,
required this.systemModuleList,
required this.uid});
factory Institution.fromJson(Map<String, dynamic> json) {
var systemModuleList = List<SystemModule>.empty(growable: true);
@@ -19,9 +18,8 @@ class Institution {
}
return Institution(
customizationSettings: CustomizationSettings.fromJson(
json['TestreszabasBeallitasok'],
),
customizationSettings:
CustomizationSettings.fromJson(json['TestreszabasBeallitasok']),
shortName: json['RovidNev'],
systemModuleList: systemModuleList,
uid: json['Uid'],
@@ -35,21 +33,19 @@ class CustomizationSettings {
final bool isLessonsThemeVisible;
final String nextServerDeployAsString;
CustomizationSettings({
required this.delayForNotifications,
required this.isClassAverageVisible,
required this.isLessonsThemeVisible,
required this.nextServerDeployAsString,
});
CustomizationSettings(
{required this.delayForNotifications,
required this.isClassAverageVisible,
required this.isLessonsThemeVisible,
required this.nextServerDeployAsString});
factory CustomizationSettings.fromJson(Map<String, dynamic> json) {
return CustomizationSettings(
delayForNotifications:
json['ErtekelesekMegjelenitesenekKesleltetesenekMerteke'],
isClassAverageVisible: json['IsOsztalyAtlagMegjeleniteseEllenorzoben'],
isLessonsThemeVisible: json['IsTanorakTemajaMegtekinthetoEllenorzoben'],
nextServerDeployAsString: json['KovetkezoTelepitesDatuma'],
);
delayForNotifications:
json['ErtekelesekMegjelenitesenekKesleltetesenekMerteke'],
isClassAverageVisible: json['IsOsztalyAtlagMegjeleniteseEllenorzoben'],
isLessonsThemeVisible: json['IsTanorakTemajaMegtekinthetoEllenorzoben'],
nextServerDeployAsString: json['KovetkezoTelepitesDatuma']);
}
@override
@@ -72,10 +68,7 @@ class SystemModule {
factory SystemModule.fromJson(Map<String, dynamic> json) {
return SystemModule(
isActive: json['IsAktiv'],
type: json['Tipus'],
url: json['Url'],
);
isActive: json['IsAktiv'], type: json['Tipus'], url: json['Url']);
}
@override

View File

@@ -1,4 +1,4 @@
import 'generic.dart';
import 'package:firka/helpers/api/model/generic.dart';
class NoticeBoardItem {
final String uid;
@@ -9,26 +9,24 @@ class NoticeBoardItem {
final String contentHTML;
final String contentText;
NoticeBoardItem({
required this.uid,
required this.author,
required this.validFrom,
required this.validTo,
required this.title,
required this.contentHTML,
required this.contentText,
});
NoticeBoardItem(
{required this.uid,
required this.author,
required this.validFrom,
required this.validTo,
required this.title,
required this.contentHTML,
required this.contentText});
factory NoticeBoardItem.fromJson(Map<String, dynamic> json) {
return NoticeBoardItem(
uid: json['Uid'],
author: json['RogzitoNeve'],
validFrom: DateTime.parse(json['ErvenyessegKezdete']),
validTo: DateTime.parse(json['ErvenyessegVege']),
title: json['Cim'],
contentHTML: json['Tartalom'],
contentText: json['TartalomText'],
);
uid: json['Uid'],
author: json['RogzitoNeve'],
validFrom: DateTime.parse(json['ErvenyessegKezdete']),
validTo: DateTime.parse(json['ErvenyessegVege']),
title: json['Cim'],
contentHTML: json['Tartalom'],
contentText: json['TartalomText']);
}
@override
@@ -55,28 +53,26 @@ class InfoBoardItem {
final String contentText;
final NameUidDesc type;
InfoBoardItem({
required this.uid,
required this.title,
required this.date,
required this.author,
required this.createdAt,
required this.contentHTML,
required this.contentText,
required this.type,
});
InfoBoardItem(
{required this.uid,
required this.title,
required this.date,
required this.author,
required this.createdAt,
required this.contentHTML,
required this.contentText,
required this.type});
factory InfoBoardItem.fromJson(Map<String, dynamic> json) {
return InfoBoardItem(
uid: json['Uid'],
title: json['Cim'],
date: DateTime.parse(json['Datum']),
author: json['KeszitoTanarNeve'],
createdAt: DateTime.parse(json['KeszitesDatuma']),
contentText: json['Tartalom'],
contentHTML: json['TartalomFormazott'],
type: NameUidDesc.fromJson(json['Tipus']),
);
uid: json['Uid'],
title: json['Cim'],
date: DateTime.parse(json['Datum']),
author: json['KeszitoTanarNeve'],
createdAt: DateTime.parse(json['KeszitesDatuma']),
contentText: json['Tartalom'],
contentHTML: json['TartalomFormazott'],
type: NameUidDesc.fromJson(json['Tipus']));
}
@override

View File

@@ -1,5 +1,5 @@
import 'generic.dart';
import 'subject.dart';
import 'package:firka/helpers/api/model/generic.dart';
import 'package:firka/helpers/api/model/subject.dart';
class Omission {
final String uid;
@@ -75,7 +75,11 @@ class Class {
final DateTime end;
final int classNo;
Class({required this.start, required this.end, required this.classNo});
Class({
required this.start,
required this.end,
required this.classNo,
});
factory Class.fromJson(Map<String, dynamic> json) {
return Class(

View File

@@ -0,0 +1,115 @@
import 'package:firka/helpers/api/model/guardian.dart';
import 'package:firka/helpers/api/model/institution.dart';
import 'package:firka/helpers/json_helper.dart';
import 'package:intl/intl.dart';
class Student {
final List<String> addressDataList;
final BankAccount bankAccount;
// final int yearOfBirth;
// final int monthOfBirth;
// final int dayOfBirth;
final DateTime birthdate;
final String? emailAddress;
final String name;
final String? phoneNumber;
final String schoolYearUID;
final String uid;
final List<Guardian> guardianList;
final String instituteCode;
final String instituteName;
final Institution institution;
Student(
{required this.addressDataList,
required this.bankAccount,
// required this.yearOfBirth,
// required this.monthOfBirth,
// required this.dayOfBirth,
required this.birthdate,
required this.emailAddress,
required this.name,
required this.phoneNumber,
required this.schoolYearUID,
required this.uid,
required this.guardianList,
required this.instituteCode,
required this.instituteName,
required this.institution});
factory Student.fromJson(Map<String, dynamic> json) {
var guardianList = List<Guardian>.empty(growable: true);
for (var item in json['Gondviselok']) {
guardianList.add(Guardian.fromJson(item));
}
return Student(
addressDataList: listToTyped<String>(json['Cimek']),
bankAccount: BankAccount.fromJson(json['Bankszamla']),
birthdate: DateFormat('yyyy-M-d').parse(
"${json['SzuletesiEv']}-${json['SzuletesiHonap']}-${json['SzuletesiNap']}"),
emailAddress: json['EmailCim'],
name: json['Nev'],
phoneNumber: json['Telefonszam'],
schoolYearUID: json['TanevUid'],
uid: json['Uid'],
guardianList: guardianList,
instituteCode: json['IntezmenyAzonosito'],
instituteName: json['IntezmenyNev'],
institution: Institution.fromJson(json['Intezmeny']));
}
@override
String toString() {
return 'Student('
'addressDataList: [$addressDataList], '
'bankAccount: $bankAccount, '
'birthDate: $birthdate, '
'emailAddress: "$emailAddress", '
'name: "$name", '
'phoneNumber: "$phoneNumber", '
'schoolYearUID: "$schoolYearUID", '
'uid: "$uid", '
'guardianList: [$guardianList], '
'instituteCode: "$instituteCode", '
'instituteName: "$instituteName", '
')';
}
}
class BankAccount {
final String? accountNumber;
final bool? isReadOnly;
final String? ownerName;
final int? ownerType;
BankAccount(
{required this.accountNumber,
required this.isReadOnly,
required this.ownerName,
required this.ownerType});
factory BankAccount.fromJson(Map<String, dynamic> json) {
return BankAccount(
accountNumber: json['BankszamlaSzam'],
isReadOnly: json['IsReadOnly'],
ownerName: json['BankszamlaTulajdonosNeve'],
ownerType: json['BankszamlaTulajdonosTipusId']);
}
@override
String toString() {
return 'BankAccount('
'accountNumber: "$accountNumber", '
'isReadOnly: "$isReadOnly", '
'ownerName: "$ownerName", '
'ownerType: "$ownerType"'
')';
}
}

View File

@@ -1,5 +1,6 @@
import 'package:firka/helpers/api/model/subject.dart';
import 'generic.dart';
import 'subject.dart';
class Test {
final String uid;

View File

@@ -1,5 +1,5 @@
import 'generic.dart';
import 'subject.dart';
import 'package:firka/helpers/api/model/generic.dart';
import 'package:firka/helpers/api/model/subject.dart';
class Lesson {
final String uid;
@@ -83,9 +83,8 @@ class Lesson {
? NameUid.fromJson(json['OsztalyCsoport'])
: null,
teacher: json['TanarNeve'],
subject: json['Tantargy'] != null
? Subject.fromJson(json['Tantargy'])
: null,
subject:
json['Tantargy'] != null ? Subject.fromJson(json['Tantargy']) : null,
theme: json['Tema'],
roomName: json['TeremNeve'],
type: NameUidDesc.fromJson(json['Tipus']),
@@ -106,8 +105,8 @@ class Lesson {
digitalPlatformType: json['DigitalisPlatformTipus'],
digitalSupportDeviceTypeList:
json['DigitalisTamogatoEszkozTipusList'] != null
? List<String>.from(json['DigitalisTamogatoEszkozTipusList'])
: List<String>.empty(),
? List<String>.from(json['DigitalisTamogatoEszkozTipusList'])
: List<String>.empty(),
createdAt: DateTime.parse(json['Letrehozas']).toLocal(),
lastModifiedAt: DateTime.parse(json['UtolsoModositas']).toLocal(),
);
@@ -128,7 +127,7 @@ class Lesson {
'Nev': name,
'Oraszam': lessonNumber,
'OraEvesSorszama': lessonSeqNumber,
'OsztalyCsoport': classGroup?.toJson(),
'OsztalyCsoport': classGroup,
'TanarNeve': teacher,
'Tantargy': subject?.toJson(),
'Tema': theme,

View File

@@ -6,24 +6,22 @@ class TokenGrantResponse {
final String refreshToken;
final String scope;
TokenGrantResponse({
required this.idToken,
required this.accessToken,
required this.expiresIn,
required this.tokenType,
required this.refreshToken,
required this.scope,
});
TokenGrantResponse(
{required this.idToken,
required this.accessToken,
required this.expiresIn,
required this.tokenType,
required this.refreshToken,
required this.scope});
factory TokenGrantResponse.fromJson(Map<String, dynamic> json) {
return TokenGrantResponse(
idToken: json['id_token'],
accessToken: json['access_token'],
expiresIn: json['expires_in'],
tokenType: json['token_type'],
refreshToken: json['refresh_token'],
scope: json['scope'],
);
idToken: json['id_token'],
accessToken: json['access_token'],
expiresIn: json['expires_in'],
tokenType: json['token_type'],
refreshToken: json['refresh_token'],
scope: json['scope']);
}
@override

View File

@@ -1,8 +1,9 @@
import 'package:dio/dio.dart';
import 'package:firka/data/models/token_model.dart';
import 'package:kreta_api/kreta_api.dart' hide KretaEndpoints;
import 'package:firka/helpers/api/exceptions/token.dart';
import 'package:firka/helpers/api/resp/token_grant.dart';
import 'package:firka/helpers/db/models/token_model.dart';
import 'package:firka/app/app_state.dart';
import '../../main.dart';
import 'consts.dart';
Future<TokenGrantResponse> getAccessToken(String code) async {
@@ -22,11 +23,8 @@ Future<TokenGrantResponse> getAccessToken(String code) async {
};
try {
final response = await dio.post(
KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers),
data: formData,
);
final response = await dio.post(KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers), data: formData);
switch (response.statusCode) {
case 200:
@@ -35,8 +33,7 @@ Future<TokenGrantResponse> getAccessToken(String code) async {
throw Exception("Invalid grant");
default:
throw Exception(
"Failed to get access token, response code: ${response.statusCode}",
);
"Failed to get access token, response code: ${response.statusCode}");
}
} catch (e) {
rethrow;
@@ -47,8 +44,7 @@ const _tokenRefreshRetryDelays = [1000, 3000, 5000];
Future<TokenGrantResponse> extendToken(TokenModel model) async {
logger.info(
"Extending token for user: ${model.studentId}, institute: ${model.iss}",
);
"Extending token for user: ${model.studentId}, institute: ${model.iss}");
final headers = <String, String>{
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
@@ -70,38 +66,30 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
if (attempt > 0) {
final delay = _tokenRefreshRetryDelays[attempt - 1];
logger.info(
"Token refresh attempt ${attempt + 1}, waiting ${delay}ms...",
);
"Token refresh attempt ${attempt + 1}, waiting ${delay}ms...");
await Future.delayed(Duration(milliseconds: delay));
}
final response = await dio.post(
KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers),
data: formData,
);
final response = await dio.post(KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers), data: formData);
switch (response.statusCode) {
case 200:
logger.info(
"Token extended successfully for user: ${model.studentId}",
);
logger
.info("Token extended successfully for user: ${model.studentId}");
return TokenGrantResponse.fromJson(response.data);
case 400:
case 401:
logger.warning(
"Token refresh failed (${response.statusCode}) - refresh token invalid for user: ${model.studentId}",
);
"Token refresh failed (${response.statusCode}) - refresh token invalid for user: ${model.studentId}");
throw response.statusCode == 400
? TokenExpiredException()
: InvalidGrantException();
default:
logger.warning(
"Token refresh failed (${response.statusCode}) for user: ${model.studentId}, attempt ${attempt + 1}",
);
"Token refresh failed (${response.statusCode}) for user: ${model.studentId}, attempt ${attempt + 1}");
lastError = Exception(
"Failed to get access token, response code: ${response.statusCode}",
);
"Failed to get access token, response code: ${response.statusCode}");
// Continue to retry for network errors
continue;
}
@@ -111,8 +99,7 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
rethrow;
} on DioException catch (e) {
logger.warning(
"Token refresh network error for user: ${model.studentId}, attempt ${attempt + 1}: $e",
);
"Token refresh network error for user: ${model.studentId}, attempt ${attempt + 1}: $e");
lastError = e;
continue;
} catch (e) {
@@ -122,8 +109,7 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
}
}
logger.severe(
"All token refresh attempts failed for user: ${model.studentId}",
);
logger
.severe("All token refresh attempts failed for user: ${model.studentId}");
throw lastError ?? Exception("Token refresh failed after all retries");
}

View File

@@ -1,7 +1,8 @@
import 'dart:convert';
import 'dart:io';
import 'package:kreta_api/kreta_api.dart';
import 'package:firka/helpers/api/model/grade.dart';
import 'package:firka/helpers/api/model/timetable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
@@ -13,9 +14,7 @@ class IOSWidgetHelper {
if (!Platform.isIOS) return null;
try {
final result = await _channel.invokeMethod<String>(
'getAppGroupDirectory',
);
final result = await _channel.invokeMethod<String>('getAppGroupDirectory');
if (result != null) {
return Directory(result);
}
@@ -40,12 +39,8 @@ class IOSWidgetHelper {
if (!Platform.isIOS) return;
debugPrint('[IOSWidget] Starting updateWidgetData...');
debugPrint(
'[IOSWidget] todayLessons: ${todayLessons.length}, tomorrowLessons: ${tomorrowLessons.length}',
);
debugPrint(
'[IOSWidget] grades: ${grades.length}, subjectAverages: ${subjectAverages.length}',
);
debugPrint('[IOSWidget] todayLessons: ${todayLessons.length}, tomorrowLessons: ${tomorrowLessons.length}');
debugPrint('[IOSWidget] grades: ${grades.length}, subjectAverages: ${subjectAverages.length}');
final dir = await _getAppGroupDirectory();
if (dir == null) {
@@ -61,31 +56,23 @@ class IOSWidgetHelper {
'timetable': {
'today': todayLessons.map((l) => _lessonToJson(l)).toList(),
'tomorrow': tomorrowLessons.map((l) => _lessonToJson(l)).toList(),
'nextSchoolDay': nextSchoolDayLessons
.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,
'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(),
'subjects': subjectAverages.entries.map((e) => {
'uid': e.key,
'name': _getSubjectNameFromGrades(e.key, grades),
'average': e.value,
'gradeCount': _getGradeCount(e.key, grades),
}).toList(),
},
};
@@ -131,29 +118,26 @@ class IOSWidgetHelper {
'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': subject.teacherName,
}
: {
'uid': '',
'name': lesson.name,
'category': null,
'sortIndex': 0,
'teacherName': null,
},
'subject': subject != null ? {
'uid': subject.uid,
'name': subject.name,
'category': subject.category != null ? {
'uid': subject.category!.uid,
'name': subject.category!.name,
'description': subject.category!.description,
} : null,
'sortIndex': subject.sortIndex,
'teacherName': subject.teacherName,
} : {
'uid': '',
'name': lesson.name,
'category': null,
'sortIndex': 0,
'teacherName': null,
},
'theme': lesson.theme,
'roomName': lesson.roomName,
'isCancelled':
lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'isCancelled': lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
'isSubstitution': lesson.substituteTeacher != null,
};
}
@@ -165,11 +149,11 @@ class IOSWidgetHelper {
'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,
},
'category': grade.subject.category != null ? {
'uid': grade.subject.category!.uid,
'name': grade.subject.category!.name,
'description': grade.subject.category!.description,
} : null,
'sortIndex': grade.subject.sortIndex,
// Use the grade's teacher field, not subject.teacherName (which is usually null for grades)
'teacherName': grade.teacher,

View File

@@ -1,4 +1,4 @@
import 'package:isar_community/isar.dart';
import 'package:isar/isar.dart';
part 'app_settings_model.g.dart';

Some files were not shown because too many files have changed in this diff Show More