Compare commits
69 Commits
dev
...
backup/ios
| Author | SHA1 | Date | |
|---|---|---|---|
| 6290c27a7e | |||
| a3a036440a | |||
| 062f1afe67 | |||
| 6d30767cb0 | |||
| 0e3c3c421f | |||
| b6d1b221b8 | |||
| e79c489de6 | |||
| c9a034c0f8 | |||
| 4dbe0b71e6 | |||
| eddfe52a51 | |||
| 1f2f7e9d4e | |||
|
|
5766eb6675 | ||
| b28bebcce1 | |||
|
|
8fb5d5c89b | ||
|
|
f22ab629bc | ||
|
|
09ac4b7f61 | ||
|
|
5320625d83 | ||
|
|
eccdf90fd8 | ||
|
|
b4ccd52321 | ||
|
|
4658366fd4 | ||
|
|
aa77e25fe4 | ||
|
|
8984f8a915 | ||
|
|
4c28999d10 | ||
|
|
50274575f6 | ||
|
|
fb8fad142a | ||
|
|
2dccb59f7f | ||
|
|
7c9ade35f0 | ||
|
|
ca9e6c3efa | ||
| a4af924653 | |||
| 8bc52aadcb | |||
| 6101513a43 | |||
| 16e7ca49ca | |||
| dd05320346 | |||
| 1f9512d03a | |||
| d36992c7bc | |||
| fd57184f99 | |||
| fa31c0d7a3 | |||
| 47e9047873 | |||
| 7319878cb8 | |||
| 3dc902b4cf | |||
| 71e1250932 | |||
| 39651c2ab7 | |||
| bffd1d66d9 | |||
| 3480fb2ac0 | |||
| f5a16da72d | |||
| 04a441cd08 | |||
| 80856d1e8d | |||
| 9a74bd5178 | |||
| 05c1cce469 | |||
| 0b1313d0be | |||
| 5a79c48e6d | |||
| 7bf9351b22 | |||
|
|
368ad86f71 | ||
|
|
46a508cc33 | ||
|
|
2923d868e6 | ||
|
|
7f33b50822 | ||
|
|
54d792eb01 | ||
|
|
c8b402118c | ||
|
|
c0f3e61b90 | ||
|
|
9aaf43892f | ||
|
|
a64a7f7509 | ||
|
|
1225e6763f | ||
|
|
b159530de9 | ||
|
|
5fb1f6cc30 | ||
|
|
670968247a | ||
| 5847301e70 | |||
|
|
6342f16d80 | ||
|
|
7167bf8da4 | ||
|
|
7747e5d90b |
1
.gitignore
vendored
@@ -105,3 +105,4 @@ firka/debug-info/
|
||||
tool_logs/build/*.log
|
||||
tool_logs/d8dx_fix/*.log
|
||||
tool_logs/pub_fix/*.log
|
||||
secrets/upload_certificate.pem
|
||||
|
||||
4
.gitmodules
vendored
@@ -1,8 +1,8 @@
|
||||
[submodule "firka/lib/l10n"]
|
||||
path = firka/lib/l10n
|
||||
url = https://git.firka.app/firka/firka-localization
|
||||
branch = main
|
||||
branch = weblate
|
||||
[submodule "firka_wear/lib/l10n"]
|
||||
path = firka_wear/lib/l10n
|
||||
url = https://git.firka.app/firka/firka-localization
|
||||
branch = main
|
||||
branch = weblate
|
||||
|
||||
128
.woodpecker.yml
Normal file
@@ -0,0 +1,128 @@
|
||||
when:
|
||||
- event: [push, pull_request]
|
||||
- event: manual
|
||||
|
||||
steps:
|
||||
- name: submodules
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- git submodule update --init --recursive
|
||||
|
||||
- name: secrets
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
environment:
|
||||
UPLOAD_KEYSTORE_B64:
|
||||
from_secret: upload_keystore_b64
|
||||
KEYSTORE_PROPERTIES_B64:
|
||||
from_secret: keystore_properties_b64
|
||||
commands:
|
||||
- echo "$UPLOAD_KEYSTORE_B64" | base64 -d > secrets/upload-keystore.jks
|
||||
- echo "$KEYSTORE_PROPERTIES_B64" | base64 -d > secrets/keystore.properties
|
||||
|
||||
# Each step runs in a fresh container from the builder image -- only the
|
||||
# workspace volume is shared between them. Pointing PUB_CACHE at a
|
||||
# workspace-local dir (instead of the image's default /root/.pub-cache)
|
||||
# is what lets `flutter pub get`'s downloads survive into later steps.
|
||||
- name: dependencies
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter pub get
|
||||
|
||||
- name: codegen
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- dart run scripts/codegen.dart
|
||||
|
||||
- name: build-release
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch: main
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build appbundle --release
|
||||
|
||||
- name: build-debug
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build apk --debug --split-per-abi
|
||||
|
||||
- name: publish-release
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/bundle/release/app-release.aab
|
||||
file_name: app-release.aab
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-arm64-v8a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-arm64-v8a-debug.apk
|
||||
file_name: app-arm64-v8a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-armeabi-v7a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-armeabi-v7a-debug.apk
|
||||
file_name: app-armeabi-v7a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-x86_64
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-x86_64-debug.apk
|
||||
file_name: app-x86_64-debug.apk
|
||||
update: 'true'
|
||||
66
Jenkinsfile
vendored
@@ -1,66 +0,0 @@
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
FLUTTER_ROOT = "/opt/flutter"
|
||||
FLUTTER = "/opt/flutter/bin/flutter"
|
||||
DART = "/opt/flutter/bin/dart"
|
||||
ANDROID_SDK_ROOT = "/opt/android-sdk"
|
||||
ANDROID_HOME = "/opt/android-sdk"
|
||||
}
|
||||
stages {
|
||||
stage('Clone Submodules') {
|
||||
steps {
|
||||
sh 'git submodule update --init --recursive'
|
||||
}
|
||||
}
|
||||
stage('Dependencies') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
$FLUTTER pub get
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Setup') {
|
||||
steps {
|
||||
sh '''
|
||||
cp -r /opt/secrets ./
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Codegen') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
PATH="/opt/flutter/bin:$PATH" $DART run scripts/codegen.dart
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Build') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
echo "--- Checking secrets path ---"
|
||||
ls android/app/
|
||||
ls android/app/../../../ || echo "no parent"
|
||||
ls android/app/../../../secrets/ || echo "secrets not found at expected path"
|
||||
$FLUTTER config --android-sdk /opt/android-sdk
|
||||
$FLUTTER build apk --release
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Archive') {
|
||||
steps {
|
||||
archiveArtifacts(
|
||||
artifacts: 'firka/build/app/outputs/flutter-apk/app-debug.apk,firka/build/app/outputs/flutter-apk/app-release.apk',
|
||||
fingerprint: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
post {
|
||||
always {
|
||||
deleteDir()
|
||||
}
|
||||
}
|
||||
}
|
||||
50
README_de.md
@@ -1,13 +1,51 @@
|
||||
# Firka
|
||||
# <img src="https://git.firka.app/firka/readme-files/raw/branch/main/dave.png" height="40" /> Firka
|
||||
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) | <sub>DE</sub> [Deutsch](README_de.md) |
|
||||
|-----------------------------------|---------------------------------------|---------------------------------------|
|
||||
|
||||
[](https://crowdin.com/project/firka)
|
||||
<a href="https://translate.firka.app/engage/firka-naplo/"><img src="https://translate.firka.app/widget/firka-naplo/firka-app/en/svg-badge.svg" alt="Translation status"></a>
|
||||
<a href="https://status.firka.app/"><img src="https://status.firka.app/api/badge/1/uptime/24?label=Uptime&suffix=%" alt="Uptime"></a>
|
||||
<a href="https://builds.firka.app/job/Firka%20Beta/"><img src="https://img.shields.io/jenkins/build?jobUrl=https%3A%2F%2Fbuilds.firka.app%2Fjob%2FFirka%2520Beta%2F&label=Build" alt="Build status"></a>
|
||||
|
||||
## Das Projekt
|
||||
### Wir haben diese App entwickelt, weil die offizielle App viel zu wünschen übrig ließ. Firka ist eine vollständig open-source, von der Community gepflegte Alternative, und wir stehen erst am Anfang. Mit jedem Release wird sie schneller, anpassbarer und benutzerfreundlicher.
|
||||
|
||||
Firka ist ein alternativer Client für [eine noch zu benennende Applikation]. Das Ziel der App ist es, eine moderne
|
||||
und benutzerfreundliche App für das [noch zu benennende] System zu sein.
|
||||
|
||||
[Leitfaden für Mitwirkende](CONTRIBUTING_de.md)
|
||||
|
||||
<img src="https://git.firka.app/firka/readme-files/raw/branch/main/firka_features.png" width="100%" />
|
||||
|
||||
<br />
|
||||
|
||||
## Was sind überhaupt die Funktionen der App?
|
||||
### Sieh, was ansteht
|
||||
|
||||
Der Startbildschirm zeigt deine anstehenden Lektionen an, damit du nie unvorbereitet bist. Filtere nach Fach, Prüfungen oder was auch immer dir gerade wichtig ist. Die untere Leiste ist vollständig anpassbar: Zeige an was du nutzt und verstecke was du nicht brauchst.
|
||||
|
||||
|
||||
### Noten, ganz nach deinen Vorstellungen
|
||||
|
||||
Emotional nicht bereit für deine eigenen Noten? Diese Einstellung hält sie verborgen, bis du jede einzelne antippst, damit du deine Misserfolge in einem angenehmen Tempo verarbeiten kannst.
|
||||
|
||||
|
||||
### Wie schlecht bist du eigentlich in Mathe?
|
||||
|
||||
Die Noten-Seite enthält ein Diagramm deines Gesamtdurchschnitts, sodass du beobachten kannst, wie er im Laufe des Semesters langsam sinkt. Jedes Fach hat zudem ein eigenes Diagramm, falls du genau wissen möchtest, welches dafür verantwortlich ist.
|
||||
|
||||
|
||||
### Alles anpassen
|
||||
|
||||
Der Einstellungsbildschirm bietet Optionen, von denen du nicht wusstest, dass du sie brauchst. Passe die Glockenverzögerung an, damit du auf die Sekunde genau weißt, wann der Unterricht endet. Es gibt auch einen Linkshänder-Modus, denn anscheinend benutzen manche Leute ihr Handy falsch.
|
||||
|
||||
|
||||
## Was wird unterstützt?
|
||||
|
||||
Derzeit unterstützen wir **Android** und **iOS**.
|
||||
<br />
|
||||
Wir planen, auch deinen Browser zu unterstützen!
|
||||
|
||||
## Mitwirken
|
||||
Wir würden uns sehr über deine Hilfe freuen.
|
||||
Du kannst im [Leitfaden zum unterstützen](CONTRIBUTING_de.md) loslegen.
|
||||
|
||||
## Community
|
||||
|
||||
[Discord](https://discord.gg/xTspd3zzRZ)
|
||||
48
cache.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Cache
|
||||
|
||||
Entry:
|
||||
|
||||
név|típus|
|
||||
-|-|
|
||||
latestElement|idő|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
|
||||
Legutóbbi = Legutóbbi sikeres adatlekérdezés listájának legfrissebb elemének ideje.
|
||||
|
||||
## Timetable
|
||||
|
||||
TimetableDay entry.
|
||||
|
||||
Frissíteni|Korábbi|Múlt hét|Jelenlegi hét|Jövő hét|Későbbi|
|
||||
-|-|-|-|-|-|
|
||||
belépéskor?|✖️|✖️|✔️|✔️|✖️|
|
||||
kijelzéskor?|✖️|✖️|✖️|✖️|✔️|
|
||||
|
||||
Új mulasztáskor a mulasztás napját MINDIG frissíti.
|
||||
|
||||
## Értékelések/Tesztek/Faliújság/Feljegyzések/Házi feladatok
|
||||
|
||||
Frissíteni|Korábbi|Legutóbbi létrehozástól|
|
||||
-|-|-|
|
||||
belépéskor?|✖️|✔️|
|
||||
kijelzéskor?|✖️|✖️|
|
||||
|
||||
## Mulasztások
|
||||
|
||||
Összes
|
||||
|
||||
## Egyéb
|
||||
|
||||
Belépéskor
|
||||
|
||||
--------
|
||||
# IMPL
|
||||
|
||||
### GenericCache
|
||||
Entry:
|
||||
név|típus|
|
||||
-|-|
|
||||
userId|id|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
@@ -1,27 +1,27 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services")
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.firka.naplo"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
isCoreLibraryDesugaringEnabled = true
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "app.firka.naplo"
|
||||
// You can update the following values to match your application needs.
|
||||
@@ -31,14 +31,11 @@ android {
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (propsFile.exists()) {
|
||||
val props = Properties().apply { FileInputStream(propsFile).use { load(it) } }
|
||||
val store = File(secretsDir, props["storeFile"].toString())
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
storeFile = store
|
||||
@@ -52,7 +49,6 @@ android {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
applicationIdSuffix = ".debug"
|
||||
@@ -60,27 +56,29 @@ android {
|
||||
}
|
||||
release {
|
||||
val config = signingConfigs.findByName("release")
|
||||
|
||||
if (config != null) {
|
||||
signingConfig = config
|
||||
}
|
||||
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
|
||||
compilerOptions {
|
||||
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
configurations.all {
|
||||
resolutionStrategy {
|
||||
force("androidx.test.espresso:espresso-core:3.6.1")
|
||||
force("androidx.test.espresso:espresso-idling-resource:3.6.1")
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.glance:glance-appwidget:1.1.1")
|
||||
implementation("com.google.android.gms:play-services-wearable:18.1.0")
|
||||
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
|
||||
}
|
||||
|
||||
// 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")
|
||||
@@ -95,7 +93,6 @@ tasks.register("ensureEnv") {
|
||||
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
|
||||
dependsOn("ensureEnv")
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
}
|
||||
29
firka/android/app/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<application android:label="Firka Debug"
|
||||
<application android:name="app.firka.naplo.AppMain"
|
||||
android:label="Firka Debug"
|
||||
android:usesCleartextTraffic="true" />
|
||||
</manifest>
|
||||
</manifest>
|
||||
29
firka/android/app/src/debug/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo.debug"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -684,6 +684,13 @@
|
||||
<meta-data
|
||||
android:name="com.google.android.wearable.standalone"
|
||||
android:value="true" />
|
||||
|
||||
<!-- Small status-bar icon for FCM notification-payload messages that
|
||||
Android displays automatically (data-only wakeups instead go
|
||||
through LocalNotificationService, which sets its own icon). -->
|
||||
<meta-data
|
||||
android:name="com.google.firebase.messaging.default_notification_icon"
|
||||
android:resource="@drawable/ic_notification" />
|
||||
</application>
|
||||
|
||||
<!-- Required to query activities that can process text, see:
|
||||
|
||||
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 957 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 8.1 KiB |
@@ -1,5 +1,5 @@
|
||||
import com.android.build.gradle.BaseExtension
|
||||
import org.jetbrains.kotlin.gradle.plugin.extraProperties
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
@@ -14,33 +14,26 @@ rootProject.layout.buildDirectory.value(newBuildDir)
|
||||
subprojects {
|
||||
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
|
||||
|
||||
// fix for verifyReleaseResources
|
||||
|
||||
// note(4831c0): taken from https://github.com/isar/isar/issues/1662
|
||||
// note(4831c0): and adapted to kotlin
|
||||
afterEvaluate {
|
||||
if (plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.library")) {
|
||||
val androidExtension = extensions.getByName("android") as BaseExtension
|
||||
androidExtension.apply {
|
||||
compileSdkVersion(37)
|
||||
buildToolsVersion = "36.1.0"
|
||||
}
|
||||
}
|
||||
if (hasProperty("android")) {
|
||||
val androidExtension = extensions.getByName("android") as BaseExtension
|
||||
androidExtension.apply {
|
||||
// Set namespace if it's not already set
|
||||
if (!extraProperties.has("namespace")) {
|
||||
extraProperties["namespace"] = project.group.toString()
|
||||
if (plugins.hasPlugin("com.android.application")) {
|
||||
extensions.configure<ApplicationExtension> {
|
||||
compileSdk = 37
|
||||
defaultConfig {
|
||||
// buildToolsVersion can be set here if needed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (plugins.hasPlugin("com.android.library")) {
|
||||
extensions.configure<LibraryExtension> {
|
||||
compileSdk = 37
|
||||
}
|
||||
}
|
||||
}
|
||||
// ===============================
|
||||
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
}
|
||||
|
||||
tasks.register<Delete>("clean") {
|
||||
delete(rootProject.layout.buildDirectory)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ pluginManagement {
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "9.2.0" apply false
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services") version("4.4.4") apply false
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.android") version "2.3.10" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.3.10" apply false
|
||||
}
|
||||
|
||||
BIN
firka/assets/fonts/FiraCode-VariableFont_wght.ttf
Normal file
BIN
firka/assets/fonts/JustMeAgainDownHere.ttf
Normal file
BIN
firka/assets/fonts/Monoton-Regular.ttf
Normal file
BIN
firka/assets/fonts/PirataOne-Regular.ttf
Normal file
BIN
firka/assets/fonts/Vollkorn-VariableFont_wght.ttf
Normal file
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 13 KiB |
5
firka/assets/images/surprise_grades/play_card_star.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g id="tabler:play-card-star-filled">
|
||||
<path id="Vector" d="M14.1667 1.66667C14.8297 1.66667 15.4656 1.93006 15.9344 2.3989C16.4033 2.86774 16.6667 3.50363 16.6667 4.16667V15.8333C16.6667 16.4964 16.4033 17.1323 15.9344 17.6011C15.4656 18.0699 14.8297 18.3333 14.1667 18.3333H5.83333C5.17029 18.3333 4.53441 18.0699 4.06557 17.6011C3.59673 17.1323 3.33333 16.4964 3.33333 15.8333V4.16667C3.33333 3.50363 3.59673 2.86774 4.06557 2.3989C4.53441 1.93006 5.17029 1.66667 5.83333 1.66667H14.1667ZM14.175 15H14.1667C13.9543 15.0002 13.75 15.0816 13.5955 15.2274C13.4411 15.3732 13.3481 15.5725 13.3357 15.7845C13.3232 15.9965 13.3922 16.2053 13.5286 16.3682C13.6649 16.5311 13.8583 16.6357 14.0692 16.6608L14.175 16.6667C14.396 16.6667 14.608 16.5789 14.7643 16.4226C14.9205 16.2663 15.0083 16.0543 15.0083 15.8333C15.0083 15.6123 14.9205 15.4004 14.7643 15.2441C14.608 15.0878 14.396 15 14.175 15ZM10.025 7.08333L9.92917 7.0875C9.60917 7.12083 9.32583 7.315 9.18083 7.60667L8.75583 8.4625L7.8075 8.60083C7.455 8.65 7.1575 8.89833 7.04583 9.24083L7.01833 9.345C6.9866 9.50024 6.99456 9.66098 7.04146 9.81233C7.08837 9.96368 7.17271 10.1007 7.28667 10.2108L7.97 10.875L7.80833 11.8142C7.75 12.1742 7.8975 12.5283 8.18667 12.7375L8.27583 12.7942C8.41247 12.8713 8.56621 12.9131 8.7231 12.9157C8.87998 12.9183 9.03503 12.8817 9.17417 12.8092L10.0258 12.3625L10.875 12.8083C11.1892 12.975 11.575 12.9483 11.8667 12.7367L11.95 12.67C12.1842 12.4542 12.2967 12.1325 12.2417 11.8133L12.08 10.875L12.7658 10.2092C13.0242 9.9575 13.1158 9.5825 13.005 9.24167L12.97 9.15C12.9051 9.00436 12.8044 8.87758 12.6771 8.78153C12.5499 8.68548 12.4003 8.6233 12.2425 8.60083L11.2942 8.4625L10.8708 7.6075C10.793 7.44983 10.6727 7.31709 10.5233 7.22431C10.374 7.13152 10.2016 7.0824 10.0258 7.0825M5.84167 3.33333H5.83333C5.62093 3.33357 5.41664 3.4149 5.26219 3.56071C5.10775 3.70651 5.0148 3.90579 5.00236 4.11783C4.98991 4.32986 5.0589 4.53865 5.19522 4.70153C5.33155 4.8644 5.52492 4.96908 5.73583 4.99417L5.84167 5C6.06268 5 6.27464 4.9122 6.43092 4.75592C6.5872 4.59964 6.675 4.38768 6.675 4.16667C6.675 3.94565 6.5872 3.73369 6.43092 3.57741C6.27464 3.42113 6.06268 3.33333 5.84167 3.33333Z" fill="#A7DC22"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
3
firka/assets/images/surprise_grades/star_large.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 9" d="M10.5 0L11.047 7.18922C11.1594 8.66653 12.3335 9.84055 13.8108 9.95296L21 10.5L13.8108 11.047C12.3335 11.1594 11.1594 12.3335 11.047 13.8108L10.5 21L9.95296 13.8108C9.84055 12.3335 8.66653 11.1594 7.18923 11.047L0 10.5L7.18922 9.95296C8.66653 9.84055 9.84055 8.66653 9.95296 7.18923L10.5 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 503 B |
3
firka/assets/images/surprise_grades/star_medium.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 11" d="M12.5 0L13.1885 9.0478C13.3009 10.5251 14.4749 11.6991 15.9522 11.8115L25 12.5L15.9522 13.1885C14.4749 13.3009 13.3009 14.4749 13.1885 15.9522L12.5 25L11.8115 15.9522C11.6991 14.4749 10.5251 13.3009 9.0478 13.1885L0 12.5L9.0478 11.8115C10.5251 11.6991 11.6991 10.5251 11.8115 9.0478L12.5 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 504 B |
3
firka/assets/images/surprise_grades/star_small.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="9.87586" height="9.87586" viewBox="0 0 9.87586 9.87586" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 10" d="M4.93793 0L5.15681 2.87656C5.23175 3.86143 6.01443 4.64411 6.9993 4.71905L9.87586 4.93793L6.9993 5.15681C6.01443 5.23175 5.23175 6.01443 5.15681 6.9993L4.93793 9.87586L4.71905 6.9993C4.64411 6.01443 3.86143 5.23175 2.87656 5.15681L0 4.93793L2.87656 4.71905C3.86143 4.64411 4.64411 3.86143 4.71905 2.87656L4.93793 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 549 B |
3
firka/assets/majesticons/check.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.7069 7.70643C19.8891 7.51783 19.9899 7.26523 19.9876 7.00303C19.9853 6.74083 19.8801 6.49002 19.6947 6.30461C19.5093 6.1192 19.2585 6.01403 18.9963 6.01176C18.7341 6.00948 18.4815 6.11027 18.2929 6.29243L8.99992 15.5854L5.70692 12.2924C5.51832 12.1103 5.26571 12.0095 5.00352 12.0118C4.74132 12.014 4.49051 12.1192 4.3051 12.3046C4.11969 12.49 4.01452 12.7408 4.01224 13.003C4.00997 13.2652 4.11076 13.5178 4.29292 13.7064L8.29292 17.7064C8.48045 17.8939 8.73476 17.9992 8.99992 17.9992C9.26508 17.9992 9.51939 17.8939 9.70692 17.7064L19.7069 7.70643Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 726 B |
10
firka/assets/majesticons/checkSolid.svg
Normal file
@@ -0,0 +1,10 @@
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_2679_4048)">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.5 0.5C1.96957 0.5 1.46086 0.710714 1.08579 1.08579C0.710714 1.46086 0.5 1.96957 0.5 2.5V9.5C0.5 10.0304 0.710714 10.5391 1.08579 10.9142C1.46086 11.2893 1.96957 11.5 2.5 11.5H9.5C10.0304 11.5 10.5391 11.2893 10.9142 10.9142C11.2893 10.5391 11.5 10.0304 11.5 9.5V2.5C11.5 1.96957 11.2893 1.46086 10.9142 1.08579C10.5391 0.710714 10.0304 0.5 9.5 0.5H2.5ZM9.8535 3.8535C9.94458 3.7592 9.99498 3.6329 9.99384 3.5018C9.9927 3.3707 9.94011 3.24529 9.84741 3.15259C9.75471 3.05989 9.6293 3.0073 9.4982 3.00616C9.3671 3.00502 9.2408 3.05542 9.1465 3.1465L4.5 7.793L2.8535 6.1465C2.7592 6.05542 2.6329 6.00502 2.5018 6.00616C2.3707 6.0073 2.24529 6.05989 2.15259 6.15259C2.05989 6.24529 2.0073 6.3707 2.00616 6.5018C2.00502 6.6329 2.05542 6.7592 2.1465 6.8535L4.1465 8.8535C4.24026 8.94724 4.36742 8.99989 4.5 8.99989C4.63258 8.99989 4.75974 8.94724 4.8535 8.8535L9.8535 3.8535Z" fill="#A7DC22"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_2679_4048">
|
||||
<rect width="12" height="12" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -1,21 +1,22 @@
|
||||
icons:
|
||||
"flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1"
|
||||
"pubspec.yaml": "a6ae0bd67a2b6226bec2dfd55437b3db2b7ca4a03f315c1a0a8c2f4b505c7c87"
|
||||
"pubspec.yaml": "5d40f014d654e257bc58e8ebfb2468a5ed7f75d913a67fb89314b9fda1c257a6"
|
||||
"assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983"
|
||||
"assets/images/logos/monochrome_logo.png": "188d2b0a64c70323b09bcee721663d6698fb557066f20ddaec97bba6869c1c6c"
|
||||
"assets/images/logos/colored_logo_without_mustache.png": "d11cff9f38985885873bfdd2d84e61f8fab03803eada94d4caac1545ef3685f3"
|
||||
"assets/images/logos/colored_logo_only_mustache.png": "bad6220c11bdfb1dfe04e5173bd2ebedd3999689d4b3a68fc63dc520c96dd33b"
|
||||
l10n:
|
||||
"l10n.yml": "a57bc304cac4a2b0235593586f17f400a5165d67fc9aadeaa11893cfa36ee082"
|
||||
"lib/l10n/app_de.arb": "ecfbf13bd33be9d27a2b54bfd8fb61e46c1a1dce905869d3f30cd05b4aecf258"
|
||||
"lib/l10n/app_en.arb": "7c43928f67b5b735283da04e3741f1afa2e9d41cdeb2e91c740e77fc84e7f046"
|
||||
"lib/l10n/app_hu.arb": "696a1ea2e86be364e9c815e5f739d3a2f5f3da9c05066084d9d26defe5018e2c"
|
||||
"lib/l10n/app_pl.arb": "a8426455757e587c7635c3a62c650a4aae2a0cac1de1175e8ab7fb0d3b387537"
|
||||
"lib/l10n/app_de.arb": "c498950bbc917e35b1910451ad9fbd4e625db89151f07558e846a7c119a583af"
|
||||
"lib/l10n/app_en.arb": "159405752b5e73eedbe546a59567550091926a37cf9cf6ce78dd58f1a0dd1d4b"
|
||||
"lib/l10n/app_hu.arb": "c7fba2a8f91217433698d766e9451d8fad86ae71021adf714639fc3907a34891"
|
||||
isar:
|
||||
"lib/data/models/app_settings_model.dart": "5eb5af345f1347f104257f0999763650fe2673f9da1754bd12d3f756fe5c9723"
|
||||
"lib/data/models/generic_cache_model.dart": "79151d0467fb5d40c532eaaa08ad7c7e24a34304199280fbf49cf6e5adcce6bc"
|
||||
"lib/data/models/homework_cache_model.dart": "45789970b27d5790cdc54c292ef2f5feaa5f4e293b8a8862fd676d5eb3e25d29"
|
||||
"lib/data/models/timetable_cache_model.dart": "b972bf51e399f8d20d4f9ad660082d4cc4a9798df9ac9d6ec9ef6ac640205572"
|
||||
"lib/data/models/token_model.dart": "8c957cd07e473827d78fd8fd4fb6c1336b636a69c25c93618e1e7f94b7cf0683"
|
||||
"lib/data/models/homework_cache_model.dart": "45789970b27d5790cdc54c292ef2f5feaa5f4e293b8a8862fd676d5eb3e25d29"
|
||||
"lib/data/models/generic_cache_model.dart": "62003ec1fd73a0fa6786d337acdef42b9a6eb9efaa78d17eaf4fe091504b8490"
|
||||
"lib/data/models/timetable_cache_model.dart": "b972bf51e399f8d20d4f9ad660082d4cc4a9798df9ac9d6ec9ef6ac640205572"
|
||||
splash:
|
||||
"flutter_native_splash.yaml": "0fd4a85d6f950d97298e99916927649940ffcfdadfc136ceee126fed0dbaa9f2"
|
||||
"assets/images/logos/splash.png": "88fbebc3d686cb9095bcce362029b69978b1b14270e465e91d962b1425db1152"
|
||||
|
||||
1
firka/firebase.json
Normal file
@@ -0,0 +1 @@
|
||||
{"flutter":{"platforms":{"android":{"default":{"projectId":"firka-4633b","appId":"1:219357380322:android:5b776732799faa5c08a8bb","fileOutput":"android/app/google-services.json"}},"dart":{"lib/firebase_options.dart":{"projectId":"firka-4633b","configurations":{"android":"1:219357380322:android:5b776732799faa5c08a8bb"}}}}}}
|
||||
@@ -1,169 +0,0 @@
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'kreta_client.dart';
|
||||
|
||||
bool getStudentFL = false;
|
||||
bool getClassGroupsFL = false;
|
||||
bool getNoticeBoardStreamFL = false;
|
||||
bool getInfoBoardStreamFL = false;
|
||||
bool getGradesStreamFL = false;
|
||||
bool getSubjectAverageStreamFL = false;
|
||||
bool getHomeworkStreamFL = false;
|
||||
bool getTimeTableStreamFL = false;
|
||||
bool getTestsStreamFL = false;
|
||||
bool getOmissionsStreamFL = false;
|
||||
|
||||
extension KretaStream on KretaClient {
|
||||
Stream<ApiResponse<Student>> getStudentStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getStudentFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getStudentFL = true;
|
||||
yield await getStudent(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getStudent(forceCache: false);
|
||||
}
|
||||
getStudentFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<ClassGroup>>> getClassGroupsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getClassGroupsFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getClassGroupsFL = true;
|
||||
yield await getClassGroups(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getClassGroups(forceCache: false);
|
||||
}
|
||||
getClassGroupsFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<NoticeBoardItem>>> getNoticeBoardStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getNoticeBoardStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getNoticeBoardStreamFL = true;
|
||||
yield await getNoticeBoard(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getNoticeBoard(forceCache: false);
|
||||
}
|
||||
getNoticeBoardStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<InfoBoardItem>>> getInfoBoardStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getInfoBoardStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getInfoBoardStreamFL = true;
|
||||
yield await getInfoBoard(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getInfoBoard(forceCache: false);
|
||||
}
|
||||
getInfoBoardStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Grade>>> getGradesStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getGradesStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getGradesStreamFL = true;
|
||||
yield await getGrades(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getGrades(forceCache: false);
|
||||
}
|
||||
getGradesStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<SubjectAverage>>> getSubjectAverageStream(
|
||||
ClassGroup classGroup, {
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getSubjectAverageStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getSubjectAverageStreamFL = true;
|
||||
yield await getSubjectAverage(classGroup, forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getSubjectAverage(classGroup, forceCache: false);
|
||||
}
|
||||
getSubjectAverageStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Homework>>> getHomeworkStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getHomeworkStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getHomeworkStreamFL = true;
|
||||
yield await getHomework(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getHomework(forceCache: false);
|
||||
}
|
||||
getHomeworkStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Lesson>>> getTimeTableStream(
|
||||
DateTime from,
|
||||
DateTime to, {
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getTimeTableStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getTimeTableStreamFL = true;
|
||||
yield await getTimeTable(from, to, forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getTimeTable(from, to, forceCache: false);
|
||||
}
|
||||
getTimeTableStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Test>>> getTestsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getTestsStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getTestsStreamFL = true;
|
||||
yield await getTests(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getTests(forceCache: false);
|
||||
}
|
||||
getTestsStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Omission>>> getOmissionsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getOmissionsStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getOmissionsStreamFL = true;
|
||||
yield await getOmissions(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getOmissions(forceCache: false);
|
||||
}
|
||||
getOmissionsStreamFL = false;
|
||||
}
|
||||
}
|
||||
@@ -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'),
|
||||
'lastModified': validLastModified.toIso8601String(),
|
||||
};
|
||||
}).toList();
|
||||
@@ -141,8 +140,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'),
|
||||
'lastModified': validLastModified.toIso8601String(),
|
||||
};
|
||||
}).toList();
|
||||
|
||||
138
firka/lib/api/client/notification_backend_client.dart
Normal file
@@ -0,0 +1,138 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
|
||||
/// Client for registering FCM push tokens with firka's backend, mirroring
|
||||
/// LiveActivityBackendClient's conventions (same backend, same auth scheme).
|
||||
/// Requires the backend to expose the `/notifications/*` routes below.
|
||||
class NotificationBackendClient {
|
||||
static final Logger _logger = Logger('NotificationBackendClient');
|
||||
|
||||
final Dio _dio;
|
||||
|
||||
NotificationBackendClient({Dio? dio}) : _dio = dio ?? Dio() {
|
||||
if (!dotenv.isInitialized) {
|
||||
throw StateError(
|
||||
'NotificationBackendClient created before dotenv finished loading',
|
||||
);
|
||||
}
|
||||
|
||||
final baseUrl = dotenv.env['BACKEND_BASE_URL'];
|
||||
final apiKey = dotenv.env['BACKEND_API_KEY'] ?? '';
|
||||
|
||||
_dio.options.baseUrl = baseUrl!;
|
||||
_dio.options.connectTimeout = const Duration(seconds: 10);
|
||||
_dio.options.receiveTimeout = const Duration(seconds: 10);
|
||||
_dio.options.headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'x-api-key': apiKey,
|
||||
};
|
||||
|
||||
_logger.info('Notification backend configured successfully!');
|
||||
}
|
||||
|
||||
/// Register (or refresh) an FCM token for a student, with the current
|
||||
/// notification category preferences.
|
||||
Future<bool> registerToken({
|
||||
required String fcmToken,
|
||||
required String studentId,
|
||||
required bool notifyAll,
|
||||
required bool notifyGrades,
|
||||
required bool notifyHomeworkTests,
|
||||
required bool notifyAbsences,
|
||||
required bool notifyLessons,
|
||||
required bool notifyMessages,
|
||||
String? language,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'/notifications/fcm-token',
|
||||
data: {
|
||||
'fcmToken': fcmToken,
|
||||
'studentId': studentId,
|
||||
'notifyAll': notifyAll,
|
||||
'notifyGrades': notifyGrades,
|
||||
'notifyHomeworkTests': notifyHomeworkTests,
|
||||
'notifyAbsences': notifyAbsences,
|
||||
'notifyLessons': notifyLessons,
|
||||
'notifyMessages': notifyMessages,
|
||||
'language': ?language,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
_logger.info('FCM token registered successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning('Failed to register FCM token: ${response.statusCode}');
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error registering FCM token: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Update notification category preferences for an already-registered token.
|
||||
Future<bool> updatePreferences({
|
||||
required String fcmToken,
|
||||
required bool notifyAll,
|
||||
required bool notifyGrades,
|
||||
required bool notifyHomeworkTests,
|
||||
required bool notifyAbsences,
|
||||
required bool notifyLessons,
|
||||
required bool notifyMessages,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.put(
|
||||
'/notifications/preferences',
|
||||
data: {
|
||||
'fcmToken': fcmToken,
|
||||
'notifyAll': notifyAll,
|
||||
'notifyGrades': notifyGrades,
|
||||
'notifyHomeworkTests': notifyHomeworkTests,
|
||||
'notifyAbsences': notifyAbsences,
|
||||
'notifyLessons': notifyLessons,
|
||||
'notifyMessages': notifyMessages,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
_logger.info('Notification preferences updated successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning(
|
||||
'Failed to update notification preferences: ${response.statusCode}',
|
||||
);
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error updating notification preferences: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Unregister an FCM token (called on logout or when push is disabled).
|
||||
Future<bool> unregisterToken({required String fcmToken}) async {
|
||||
try {
|
||||
final response = await _dio.delete(
|
||||
'/notifications/fcm-token',
|
||||
data: {'fcmToken': fcmToken},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
_logger.info('FCM token unregistered successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning(
|
||||
'Failed to unregister FCM token: ${response.statusCode}',
|
||||
);
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error unregistering FCM token: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
42
firka/lib/api/login_finish.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
import "package:firka_common/data/models/token_model.dart";
|
||||
import "package:kreta_api/kreta_api.dart";
|
||||
|
||||
Future<void> completeLogin(
|
||||
AppInitialization data,
|
||||
TokenGrantResponse resp,
|
||||
) async {
|
||||
var tokenModel = TokenModel.fromResp(resp);
|
||||
|
||||
await data.isar.writeTxn(() async {
|
||||
await data.isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
await data.settings.setSelectedAccountKey(tokenModel.key);
|
||||
await initializeApp();
|
||||
|
||||
if (data.client != null) {
|
||||
await FcmService.onUserLogin(
|
||||
client: data.client!,
|
||||
settingsStore: data.settings,
|
||||
);
|
||||
}
|
||||
|
||||
if (Platform.isIOS) {
|
||||
final watchInstalled = await WatchSyncHelper.isWatchAppInstalled();
|
||||
if (watchInstalled) {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(tokenModel);
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenToWatch();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
38
firka/lib/api/mock_login.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import "package:dio/dio.dart";
|
||||
import "package:firka_common/core/consts.dart";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/core/dev/mock_backend.dart";
|
||||
import "package:kreta_api/kreta_api.dart";
|
||||
|
||||
Future<TokenGrantResponse> mockLogin(String username, String password) async {
|
||||
final headers = <String, String>{
|
||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": initData.userAgent,
|
||||
};
|
||||
|
||||
final formData = <String, String>{
|
||||
"grant_type": "password",
|
||||
"username": username,
|
||||
"password": password,
|
||||
"client_id": Constants.clientId,
|
||||
};
|
||||
|
||||
final response = await dio.post(
|
||||
MockBackend.rewrite(KretaLoginEndpoints.tokenGrantUrl),
|
||||
options: Options(headers: headers),
|
||||
data: formData,
|
||||
);
|
||||
|
||||
switch (response.statusCode) {
|
||||
case 200:
|
||||
return TokenGrantResponse.fromJson(response.data);
|
||||
case 401:
|
||||
throw Exception("Invalid credentials");
|
||||
default:
|
||||
throw Exception(
|
||||
"Failed to get access token, response code: ${response.statusCode}",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/dev/mock_backend.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'consts.dart';
|
||||
|
||||
Future<TokenGrantResponse> getAccessToken(String code) async {
|
||||
final headers = <String, String>{
|
||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": Constants.userAgent,
|
||||
"user-agent": initData.userAgent,
|
||||
};
|
||||
|
||||
final formData = <String, String>{
|
||||
@@ -23,7 +24,7 @@ Future<TokenGrantResponse> getAccessToken(String code) async {
|
||||
|
||||
try {
|
||||
final response = await dio.post(
|
||||
KretaLoginEndpoints.tokenGrantUrl,
|
||||
MockBackend.rewrite(KretaLoginEndpoints.tokenGrantUrl),
|
||||
options: Options(headers: headers),
|
||||
data: formData,
|
||||
);
|
||||
@@ -47,18 +48,18 @@ 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.username}, institute: ${model.iss}",
|
||||
);
|
||||
|
||||
final headers = <String, String>{
|
||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": Constants.userAgent,
|
||||
"user-agent": initData.userAgent,
|
||||
};
|
||||
|
||||
final formData = <String, String>{
|
||||
"institute_code": model.iss!,
|
||||
"refresh_token": model.refreshToken!,
|
||||
"institute_code": model.iss,
|
||||
"refresh_token": model.refreshToken,
|
||||
"grant_type": "refresh_token",
|
||||
"client_id": Constants.clientId,
|
||||
};
|
||||
@@ -76,7 +77,7 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
|
||||
}
|
||||
|
||||
final response = await dio.post(
|
||||
KretaLoginEndpoints.tokenGrantUrl,
|
||||
MockBackend.rewrite(KretaLoginEndpoints.tokenGrantUrl),
|
||||
options: Options(headers: headers),
|
||||
data: formData,
|
||||
);
|
||||
@@ -84,20 +85,20 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
|
||||
switch (response.statusCode) {
|
||||
case 200:
|
||||
logger.info(
|
||||
"Token extended successfully for user: ${model.studentId}",
|
||||
"Token extended successfully for user: ${model.username}",
|
||||
);
|
||||
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.username}",
|
||||
);
|
||||
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.username}, attempt ${attempt + 1}",
|
||||
);
|
||||
lastError = Exception(
|
||||
"Failed to get access token, response code: ${response.statusCode}",
|
||||
@@ -111,19 +112,19 @@ 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.username}, attempt ${attempt + 1}: $e",
|
||||
);
|
||||
lastError = e;
|
||||
continue;
|
||||
} catch (e) {
|
||||
logger.severe("Token refresh exception for user: ${model.studentId}: $e");
|
||||
logger.severe("Token refresh exception for user: ${model.username}: $e");
|
||||
lastError = e is Exception ? e : Exception(e.toString());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
logger.severe(
|
||||
"All token refresh attempts failed for user: ${model.studentId}",
|
||||
"All token refresh attempts failed for user: ${model.username}",
|
||||
);
|
||||
throw lastError ?? Exception("Token refresh failed after all retries");
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:firka_common/core/consts.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/toast_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/core/settings/settings_repository.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
@@ -48,20 +48,20 @@ class AppInitialization {
|
||||
final Directory appDir;
|
||||
final PackageInfo packageInfo;
|
||||
final DeviceInfo devInfo;
|
||||
late KretaClient client;
|
||||
List<TokenModel> tokens;
|
||||
KretaClient? client;
|
||||
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;
|
||||
SettingsRepository settings;
|
||||
final ThemeCubit themeCubit = ThemeCubit();
|
||||
final SettingsCubit settingsCubit = SettingsCubit();
|
||||
final ProfilePictureCubit profilePictureCubit = ProfilePictureCubit();
|
||||
final ToastCubit toastCubit = ToastCubit();
|
||||
final HomeRefreshCubit homeRefreshCubit = HomeRefreshCubit();
|
||||
AppLocalizations l10n;
|
||||
String userAgent;
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
AppInitialization({
|
||||
@@ -69,9 +69,13 @@ class AppInitialization {
|
||||
required this.appDir,
|
||||
required this.devInfo,
|
||||
required this.packageInfo,
|
||||
required this.tokens,
|
||||
required this.settings,
|
||||
required this.l10n,
|
||||
required this.navigatorKey,
|
||||
});
|
||||
}) : userAgent = Platform.isAndroid
|
||||
? "${Constants.applicationId}/${Constants.applicationVersion}"
|
||||
"/${devInfo.model}"
|
||||
"/${devInfo.versionRelease}"
|
||||
"/${devInfo.versionSdkInt}"
|
||||
: "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0";
|
||||
}
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:firka_common/data/database.dart';
|
||||
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_common/data/models/token_model.dart';
|
||||
import 'package:firka/services/fcm_service.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/core/settings/settings_effects.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/core/settings/title_font.dart';
|
||||
import 'package:firka/services/watch_sync_helper.dart';
|
||||
import 'package:firka/l10n/app_localizations_de.dart';
|
||||
import 'package:firka/l10n/app_localizations_en.dart';
|
||||
import 'package:firka/l10n/app_localizations_hu.dart';
|
||||
import 'package:firka/core/swear_generator.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
@@ -32,47 +28,23 @@ 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
|
||||
switch (Settings.language.value) {
|
||||
case AppLanguage.hu:
|
||||
data.l10n = AppLocalizationsHu();
|
||||
languageCode = 'hu';
|
||||
break;
|
||||
case 2: // en
|
||||
case AppLanguage.en:
|
||||
data.l10n = AppLocalizationsEn();
|
||||
languageCode = 'en';
|
||||
break;
|
||||
case 3: // de
|
||||
case AppLanguage.de:
|
||||
data.l10n = AppLocalizationsDe();
|
||||
languageCode = 'de';
|
||||
break;
|
||||
default: // auto
|
||||
case AppLanguage.auto:
|
||||
switch (ui.PlatformDispatcher.instance.locale.languageCode) {
|
||||
case 'hu':
|
||||
data.l10n = AppLocalizationsHu();
|
||||
@@ -107,44 +79,77 @@ Future<void> initLang(AppInitialization data) async {
|
||||
|
||||
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;
|
||||
final titleFont = Settings.titleFont.value;
|
||||
final titleWeight = Settings.titleWeight.value;
|
||||
final fonts = buildAppFonts(
|
||||
headingFamily: titleFont.fontFamily,
|
||||
headingWeight: titleWeight,
|
||||
supportsWeight: titleFont.supportsWeight,
|
||||
);
|
||||
|
||||
appHeadingTextCase = switch (Settings.titleCapitalization.value) {
|
||||
TitleCapitalization.lower => HeadingTextCase.lower,
|
||||
TitleCapitalization.upper => HeadingTextCase.upper,
|
||||
TitleCapitalization.normal => HeadingTextCase.normal,
|
||||
};
|
||||
|
||||
FirkaStyle baseStyle;
|
||||
final coreId = Settings.selectedCoreThemeId.value;
|
||||
final gradeId = Settings.selectedGradeThemeId.value;
|
||||
switch (Settings.themeBrightness.value) {
|
||||
case ThemeBrightness.light:
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: true,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(true);
|
||||
break;
|
||||
case 2:
|
||||
appStyle = darkStyle;
|
||||
case ThemeBrightness.dark:
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: false,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(false);
|
||||
break;
|
||||
default:
|
||||
case ThemeBrightness.auto:
|
||||
if (brightness == Brightness.dark) {
|
||||
appStyle = darkStyle;
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: false,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(false);
|
||||
} else {
|
||||
appStyle = lightStyle;
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: true,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appStyle = baseStyle;
|
||||
}
|
||||
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 init.settings.loadAll();
|
||||
final selectedThemeId = Settings.selectedThemeId.value;
|
||||
final normalized = normalizeSelectedThemeId(selectedThemeId);
|
||||
if (normalized != selectedThemeId) {
|
||||
await Settings.selectedThemeId.set(normalized);
|
||||
}
|
||||
await initLang(init);
|
||||
initTheme(init);
|
||||
init.settings = SettingsStore(init.l10n);
|
||||
await init.settings.load(init.isar.appSettingsModels);
|
||||
|
||||
var dispatcher = SchedulerBinding.instance.platformDispatcher;
|
||||
|
||||
@@ -153,10 +158,7 @@ Future<void> _initData(AppInitialization init) async {
|
||||
};
|
||||
|
||||
dispatcher.onLocaleChanged = () {
|
||||
final languageSetting =
|
||||
init.settings.group("settings").subGroup("application")["language"]
|
||||
as SettingsItemsRadio;
|
||||
final isAutoLanguage = languageSetting.activeIndex == 0;
|
||||
final isAutoLanguage = Settings.language.value == AppLanguage.auto;
|
||||
if (!isAutoLanguage) {
|
||||
return;
|
||||
}
|
||||
@@ -170,13 +172,10 @@ Future<void> _initData(AppInitialization init) async {
|
||||
"[Init] System locale changed in auto mode: $previousLocale -> $nextLocale",
|
||||
);
|
||||
}
|
||||
init.themeCubit?.refresh();
|
||||
init.themeCubit.refresh();
|
||||
}());
|
||||
};
|
||||
|
||||
resetOldTimeTableCache(init.isar);
|
||||
resetOldHomeworkCache(init.isar);
|
||||
|
||||
var didRunFreshInstallCleanup = false;
|
||||
if (Platform.isIOS) {
|
||||
try {
|
||||
@@ -187,50 +186,65 @@ Future<void> _initData(AppInitialization init) async {
|
||||
'[Init] Fresh-install cleanup completed; skipping startup iCloud recovery on this launch',
|
||||
);
|
||||
} else {
|
||||
await WatchSyncHelper.checkAndRecoverFromiCloud(
|
||||
isar: init.isar,
|
||||
tokens: init.tokens,
|
||||
);
|
||||
await WatchSyncHelper.checkAndRecoverFromiCloud(isar: init.isar);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning('[Init] iCloud bootstrap/recovery failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
final allTokens = await init.isar.tokenModels.where().findAll();
|
||||
init.tokens = allTokens;
|
||||
final token = init.settings.getSelectedToken();
|
||||
if (token == null) {
|
||||
logger.warning("[Init] No token available!");
|
||||
init.client = null;
|
||||
return;
|
||||
}
|
||||
logger.fine("Initializing kréta client as: ${token.username}");
|
||||
init.client = KretaClient(token);
|
||||
|
||||
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;
|
||||
// A resumed session (app reopened with an already-logged-in account)
|
||||
// never goes through login_finish.dart's onUserLogin call, so without
|
||||
// this the FCM token would only ever get (re-)registered for a user who
|
||||
// explicitly logs out and back in. Safe to call on every startup:
|
||||
// onUserLogin() itself no-ops if notifyAll is off or permission is denied.
|
||||
unawaited(FcmService.onUserLogin(client: init.client!));
|
||||
|
||||
// Don't block first paint on the network: render whatever is already
|
||||
// cached, then stream in student/timetable/grades/etc. as they arrive.
|
||||
unawaited(() async {
|
||||
try {
|
||||
await init.client!.init();
|
||||
} catch (e) {
|
||||
logger.warning("[Init] Failed to initialize KretaClient: $e");
|
||||
if (!isTokenExpired(e)) {
|
||||
init.toastCubit.setActiveToast(.error, e);
|
||||
}
|
||||
}
|
||||
logger.fine("Initializing kréta client as: ${token.studentId}");
|
||||
init.client = KretaClient(token, init.isar, init.reauthCubit!);
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
|
||||
if (Platform.isIOS) {
|
||||
final expiryDate = token.expiryDate;
|
||||
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
|
||||
init.reauthCubit?.clear();
|
||||
await init.client!.renewCache(reInit: false);
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
}());
|
||||
|
||||
if (Platform.isIOS) {
|
||||
final expiryDate = token.expiryDate;
|
||||
if (expiryDate.isAfter(DateTime.now())) {
|
||||
init.toastCubit.clear();
|
||||
}
|
||||
|
||||
unawaited(() async {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to iCloud: $e');
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
}());
|
||||
}
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenModelToWatch(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to Watch: $e');
|
||||
}
|
||||
}());
|
||||
}
|
||||
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
@@ -239,12 +253,14 @@ Future<void> _initData(AppInitialization init) async {
|
||||
if (await pfpFile.exists()) {
|
||||
init.profilePicture = await pfpFile.readAsBytes();
|
||||
}
|
||||
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
}
|
||||
|
||||
Future<AppInitialization> initializeApp() async {
|
||||
Future<void> initializeApp() async {
|
||||
if (initDone) {
|
||||
await _initData(initData);
|
||||
return initData;
|
||||
return;
|
||||
}
|
||||
final isar = await initDB();
|
||||
final tokens = await isar.tokenModels.where().findAll();
|
||||
@@ -274,16 +290,18 @@ Future<AppInitialization> initializeApp() async {
|
||||
logger.fine("Fetched device info: ${devInfoFetched ? "yes" : "no"}");
|
||||
logger.fine("Using device info: ${devInfo.toString()}");
|
||||
|
||||
var init = AppInitialization(
|
||||
initData = AppInitialization(
|
||||
isar: isar,
|
||||
appDir: await getApplicationDocumentsDirectory(),
|
||||
devInfo: devInfo,
|
||||
packageInfo: await PackageInfo.fromPlatform(),
|
||||
tokens: tokens,
|
||||
settings: SettingsStore(AppLocalizationsHu()),
|
||||
settings: SettingsRepository(isar),
|
||||
l10n: AppLocalizationsHu(),
|
||||
navigatorKey: navigatorKey,
|
||||
);
|
||||
initData.settings.cubit = initData.settingsCubit;
|
||||
Settings = initData.settings;
|
||||
registerSettingsEffects(initData.settings, initData);
|
||||
|
||||
if (Platform.isIOS) {
|
||||
try {
|
||||
@@ -297,9 +315,17 @@ Future<AppInitialization> initializeApp() async {
|
||||
}
|
||||
}
|
||||
|
||||
await _initData(init);
|
||||
try {
|
||||
await FcmService.initialize().timeout(const Duration(seconds: 8));
|
||||
} on TimeoutException catch (e, st) {
|
||||
logger.warning('FcmService init timed out: $e', e, st);
|
||||
} catch (e, st) {
|
||||
logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
}
|
||||
|
||||
return init;
|
||||
await _initData(initData);
|
||||
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
Future<void> setupLogging() async {
|
||||
|
||||
@@ -10,7 +10,7 @@ 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/toast_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';
|
||||
@@ -31,9 +31,7 @@ class InitializationScreen extends StatefulWidget {
|
||||
|
||||
class _InitializationScreenState extends State<InitializationScreen> {
|
||||
GoRouter? _router;
|
||||
final Future<AppInitialization> _init = initializeApp().timeout(
|
||||
const Duration(seconds: 20),
|
||||
);
|
||||
final Future<void> _init = initializeApp();
|
||||
|
||||
ThemeData _buildTheme(FirkaStyle style) {
|
||||
return ThemeData(
|
||||
@@ -45,7 +43,6 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: style.colors.accent,
|
||||
brightness: style.isLight ? Brightness.light : Brightness.dark,
|
||||
background: style.colors.background,
|
||||
surface: style.colors.card,
|
||||
),
|
||||
useMaterial3: false,
|
||||
@@ -54,11 +51,13 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<AppInitialization>(
|
||||
return FutureBuilder<void>(
|
||||
future: _init,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.done) {
|
||||
if (snapshot.hasError) {
|
||||
initDone = false;
|
||||
|
||||
logger.shout(
|
||||
"Error in InitializationScreen",
|
||||
snapshot.error.toString(),
|
||||
@@ -83,10 +82,6 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
assert(snapshot.data != null);
|
||||
initData = snapshot.data!;
|
||||
initDone = true;
|
||||
|
||||
FlutterNativeSplash.remove();
|
||||
|
||||
WatchSyncHelper.initialize();
|
||||
@@ -113,24 +108,20 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
|
||||
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',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
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":
|
||||
@@ -157,7 +148,7 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
);
|
||||
}
|
||||
await WatchSyncHelper.runWearSyncInForeground(
|
||||
initData.client,
|
||||
initData.client!,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -165,7 +156,7 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
unawaited(() async {
|
||||
try {
|
||||
await WatchSyncHelper.startWearSyncServiceWithFreshCache(
|
||||
initData.client,
|
||||
initData.client!,
|
||||
initData.appDir.path,
|
||||
);
|
||||
} catch (e) {
|
||||
@@ -183,11 +174,11 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
appRouter = _router;
|
||||
}
|
||||
|
||||
final themeCubit = initData.themeCubit!;
|
||||
final settingsCubit = initData.settingsCubit!;
|
||||
final profilePictureCubit = initData.profilePictureCubit!;
|
||||
final reauthCubit = initData.reauthCubit!;
|
||||
final homeRefreshCubit = initData.homeRefreshCubit!;
|
||||
final themeCubit = initData.themeCubit;
|
||||
final settingsCubit = initData.settingsCubit;
|
||||
final profilePictureCubit = initData.profilePictureCubit;
|
||||
final reauthCubit = initData.toastCubit;
|
||||
final homeRefreshCubit = initData.homeRefreshCubit;
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<ThemeCubit>.value(value: themeCubit),
|
||||
@@ -195,7 +186,7 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
BlocProvider<ProfilePictureCubit>.value(
|
||||
value: profilePictureCubit,
|
||||
),
|
||||
BlocProvider<ReauthCubit>.value(value: reauthCubit),
|
||||
BlocProvider<ToastCubit>.value(value: reauthCubit),
|
||||
BlocProvider<HomeRefreshCubit>.value(value: homeRefreshCubit),
|
||||
],
|
||||
child: BlocBuilder<ThemeCubit, ThemeState>(
|
||||
@@ -203,15 +194,16 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
final isLight = themeState.isLightMode;
|
||||
final overlay = SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.transparent,
|
||||
statusBarIconBrightness:
|
||||
isLight ? Brightness.dark : Brightness.light,
|
||||
statusBarBrightness:
|
||||
isLight ? Brightness.light : Brightness.dark,
|
||||
statusBarIconBrightness: isLight
|
||||
? Brightness.dark
|
||||
: Brightness.light,
|
||||
statusBarBrightness: isLight
|
||||
? Brightness.light
|
||||
: Brightness.dark,
|
||||
systemStatusBarContrastEnforced: false,
|
||||
);
|
||||
|
||||
final themeMode =
|
||||
isLight ? ThemeMode.light : ThemeMode.dark;
|
||||
final themeMode = isLight ? ThemeMode.light : ThemeMode.dark;
|
||||
|
||||
final fallbackBg = isLight
|
||||
? lightStyle.colors.background
|
||||
|
||||
52
firka/lib/core/bloc/app_icon_picker_cubit.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
import "package:flutter/services.dart";
|
||||
import "package:flutter_bloc/flutter_bloc.dart";
|
||||
import "package:logging/logging.dart";
|
||||
|
||||
import "package:firka/core/settings/settings_repository.dart";
|
||||
import "package:firka/core/settings/settings_schema.dart";
|
||||
|
||||
final Logger _logger = Logger('AppIconPickerCubit');
|
||||
|
||||
class AppIconPickerState {
|
||||
final String activeIcon;
|
||||
final bool saving;
|
||||
|
||||
const AppIconPickerState({required this.activeIcon, this.saving = false});
|
||||
|
||||
AppIconPickerState copyWith({String? activeIcon, bool? saving}) =>
|
||||
AppIconPickerState(
|
||||
activeIcon: activeIcon ?? this.activeIcon,
|
||||
saving: saving ?? this.saving,
|
||||
);
|
||||
}
|
||||
|
||||
class AppIconPickerCubit extends Cubit<AppIconPickerState> {
|
||||
AppIconPickerCubit(String initialIcon)
|
||||
: super(AppIconPickerState(activeIcon: initialIcon));
|
||||
|
||||
void select(String icon) {
|
||||
if (state.saving) return;
|
||||
emit(state.copyWith(activeIcon: icon));
|
||||
}
|
||||
|
||||
/// Persists the selected icon and swaps the platform's launcher icon.
|
||||
Future<void> save(List<String> allIconKeys) async {
|
||||
if (state.saving) return;
|
||||
emit(state.copyWith(saving: true));
|
||||
|
||||
await Settings.appIcon.set(state.activeIcon);
|
||||
|
||||
await Future.delayed(Duration(seconds: 1));
|
||||
|
||||
_logger.info(allIconKeys.join(","));
|
||||
_logger.info(state.activeIcon);
|
||||
|
||||
const channel = MethodChannel('firka.app/main');
|
||||
_logger.info(
|
||||
await channel.invokeMethod('set_icon', {
|
||||
"icon": state.activeIcon == "original" ? null : state.activeIcon,
|
||||
"icons": allIconKeys.join(","),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
37
firka/lib/core/bloc/toast_cubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:firka/ui/phone/pages/extras/firka_toast.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
enum ActiveToastType { fetching, error, reauth, none }
|
||||
|
||||
class ToastState {
|
||||
final ActiveToastType type;
|
||||
final Object? extra;
|
||||
|
||||
const ToastState(this.type, [this.extra]);
|
||||
|
||||
Widget? buildWidget(BuildContext context) {
|
||||
switch (type) {
|
||||
case .fetching:
|
||||
return FirkaToastWidget.fetching(context);
|
||||
case .error:
|
||||
return FirkaToastWidget.error(context, extra!);
|
||||
case .reauth:
|
||||
return FirkaToastWidget.reauth(context);
|
||||
case .none:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ToastCubit extends Cubit<ToastState> {
|
||||
ToastCubit() : super(const ToastState(ActiveToastType.none));
|
||||
|
||||
void setActiveToast(ActiveToastType type, [Object? extra]) {
|
||||
emit(ToastState(type, extra));
|
||||
}
|
||||
|
||||
void clear() {
|
||||
setActiveToast(ActiveToastType.none);
|
||||
}
|
||||
}
|
||||
22
firka/lib/core/dev/mock_backend.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
import "package:firka/core/settings/settings_repository.dart";
|
||||
import "package:firka/core/settings/settings_schema.dart";
|
||||
|
||||
class MockBackend {
|
||||
static String rewrite(String url) {
|
||||
if (!Settings.mockBackendEnabled.value) return url;
|
||||
|
||||
final mockBase = Settings.mockBackendUrl.value;
|
||||
if (mockBase.isEmpty) return url;
|
||||
|
||||
final mockUri = Uri.parse(mockBase);
|
||||
final uri = Uri.parse(url);
|
||||
|
||||
return uri
|
||||
.replace(
|
||||
scheme: mockUri.scheme,
|
||||
host: mockUri.host,
|
||||
port: mockUri.hasPort ? mockUri.port : null,
|
||||
)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -209,16 +209,12 @@ extension DateExtension on DateTime {
|
||||
return subtract(Duration(days: weekday - 1));
|
||||
}
|
||||
|
||||
DateTime getMidnight() {
|
||||
return subtract(
|
||||
Duration(
|
||||
hours: hour,
|
||||
minutes: minute,
|
||||
seconds: second,
|
||||
milliseconds: millisecond,
|
||||
microseconds: microsecond,
|
||||
),
|
||||
);
|
||||
DateTime getMonthFirstDay() {
|
||||
return DateTime(year, month, 1);
|
||||
}
|
||||
|
||||
DateTime getMonthLastDay() {
|
||||
return DateTime(year, month + 1, 1).subtract(Duration(days: 1));
|
||||
}
|
||||
|
||||
Cycle getDayCycle() {
|
||||
@@ -238,6 +234,11 @@ extension DateExtension on DateTime {
|
||||
|
||||
return Cycle.night;
|
||||
}
|
||||
|
||||
DateTime getFirstSchoolDay() {
|
||||
DateTime start = copyWith(month: 9, day: 1);
|
||||
return isBefore(start) ? start.copyWith(year: start.year - 1) : start;
|
||||
}
|
||||
}
|
||||
|
||||
extension DateGrouper<T> on Iterable<T> {
|
||||
@@ -316,4 +317,16 @@ extension StringExtension on String {
|
||||
"${string[0]}.",
|
||||
).shortenName(index - string.length + 2 + 1);
|
||||
}
|
||||
|
||||
/// Removes CSS font-feature-settings. flutter_html passes values like
|
||||
/// `normal` into FontFeature, which requires a 4-character OpenType tag.
|
||||
String withoutFontFeatureSettings() {
|
||||
return replaceAll(
|
||||
RegExp(
|
||||
r'''font-feature-settings\s*:\s*[^;}"']+;?''',
|
||||
caseSensitive: false,
|
||||
),
|
||||
"",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class FirkaBundle extends CachingAssetBundle {
|
||||
@override
|
||||
Future<ByteData> load(String key) async {
|
||||
logger.finest(
|
||||
"Loading asset from root bundle: assets/flutter_assets/$key",
|
||||
);
|
||||
return rootBundle.load(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -99,7 +98,6 @@ class ImagePreloader {
|
||||
AssetBundle bundle,
|
||||
String assetPath,
|
||||
) async {
|
||||
logger.finest("Caching: $assetPath");
|
||||
final ByteData data = await bundle.load(assetPath);
|
||||
final Uint8List bytes = data.buffer.asUint8List();
|
||||
return await _decodeImageFromBytes(bytes);
|
||||
|
||||
73
firka/lib/core/last_seen_helper.dart
Normal file
@@ -0,0 +1,73 @@
|
||||
import "dart:convert";
|
||||
|
||||
import "package:firka/core/settings/settings_repository.dart";
|
||||
import "package:firka/core/settings/settings_schema.dart";
|
||||
import "package:firka_common/data/last_seen.dart";
|
||||
import "package:firka_common/data/models/grade_cache_model.dart";
|
||||
|
||||
class LastSeenHelper {
|
||||
static const grades = "grades";
|
||||
static const homework = "homework";
|
||||
static const tests = "tests";
|
||||
static const omissions = "omissions";
|
||||
static const messages = "messages";
|
||||
|
||||
/// Separate dedup namespace for the FCM wakeup notification pipeline
|
||||
/// (`NotificationDiffService`), distinct from the kinds above: those track
|
||||
/// what the user has manually *opened* in the UI (e.g. for the "surprise
|
||||
/// grades" reveal), which a background push must not silently mark as seen.
|
||||
static const notifGrades = "notif_grades";
|
||||
static const notifHomework = "notif_homework";
|
||||
static const notifTests = "notif_tests";
|
||||
static const notifAbsences = "notif_absences";
|
||||
static const notifLessons = "notif_lessons";
|
||||
static const notifLessonsCancelled = "notif_lessons_cancelled";
|
||||
static const notifLessonsSubstituted = "notif_lessons_substituted";
|
||||
static const notifMessages = "notif_messages";
|
||||
|
||||
static Map<String, dynamic> _read() {
|
||||
try {
|
||||
final decoded = jsonDecode(Settings.lastSeen.value);
|
||||
return decoded is Map<String, dynamic> ? decoded : {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
static LastSeen? get(int accountKey, String kind) {
|
||||
final account = _read()["$accountKey"];
|
||||
if (account is! Map) return null;
|
||||
|
||||
return LastSeen.parse(account[kind] as String?);
|
||||
}
|
||||
|
||||
static List<GradeCacheModel> openedGrades(
|
||||
int accountKey,
|
||||
List<GradeCacheModel> grades,
|
||||
) {
|
||||
if (!Settings.surpriseGrades.value) return grades;
|
||||
|
||||
final seen = get(accountKey, LastSeenHelper.grades);
|
||||
if (seen == null) return grades;
|
||||
|
||||
final hidden = LastSeen.newerThan(
|
||||
grades,
|
||||
seen,
|
||||
).map((g) => g.cacheKey).toSet();
|
||||
|
||||
return grades.where((g) => !hidden.contains(g.cacheKey)).toList();
|
||||
}
|
||||
|
||||
static Future<void> set(int accountKey, String kind, LastSeen seen) async {
|
||||
final all = _read();
|
||||
final account = all["$accountKey"];
|
||||
final entry = account is Map
|
||||
? Map<String, dynamic>.from(account)
|
||||
: <String, dynamic>{};
|
||||
|
||||
entry[kind] = seen.toText();
|
||||
all["$accountKey"] = entry;
|
||||
|
||||
await Settings.lastSeen.set(jsonEncode(all));
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,5 @@ Future<void> pickProfilePicture(
|
||||
await File(p.join(dataDir.path, "profile.webp")).writeAsBytes(bytes);
|
||||
|
||||
data.profilePicture = bytes;
|
||||
data.profilePictureCubit?.notifyChanged();
|
||||
data.profilePictureCubit.notifyChanged();
|
||||
}
|
||||
|
||||
45
firka/lib/core/settings/setting.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import "package:isar_community/isar.dart";
|
||||
|
||||
/// A typed key for one persisted setting. Never constructed by hand outside
|
||||
/// settings_schema.gen.dart; settings_schema.dart defines the full registry.
|
||||
sealed class Setting<T> {
|
||||
final Id id;
|
||||
final T defaultValue;
|
||||
|
||||
const Setting({required this.id, required this.defaultValue});
|
||||
}
|
||||
|
||||
class BoolSetting extends Setting<bool> {
|
||||
const BoolSetting({required super.id, required super.defaultValue});
|
||||
}
|
||||
|
||||
class DoubleSetting extends Setting<double> {
|
||||
final double min;
|
||||
final double max;
|
||||
final int precision;
|
||||
final double? step;
|
||||
|
||||
const DoubleSetting({
|
||||
required super.id,
|
||||
required super.defaultValue,
|
||||
required this.min,
|
||||
required this.max,
|
||||
this.precision = 0,
|
||||
this.step,
|
||||
});
|
||||
}
|
||||
|
||||
/// Persisted as the value's index into [values].
|
||||
class EnumSetting<T extends Enum> extends Setting<T> {
|
||||
final List<T> values;
|
||||
|
||||
const EnumSetting({
|
||||
required super.id,
|
||||
required super.defaultValue,
|
||||
required this.values,
|
||||
});
|
||||
}
|
||||
|
||||
class StringSetting extends Setting<String> {
|
||||
const StringSetting({required super.id, required super.defaultValue});
|
||||
}
|
||||
97
firka/lib/core/settings/settings_effects.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:permission_handler/permission_handler.dart";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/live_activity_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
|
||||
import "settings_repository.dart";
|
||||
import "settings_schema.dart";
|
||||
|
||||
/// Registers the side effects that used to live as `postUpdate` closures on
|
||||
/// each SettingsItem. Called once after the repository is loaded at startup.
|
||||
void registerSettingsEffects(
|
||||
SettingsRepository repo,
|
||||
AppInitialization initData,
|
||||
) {
|
||||
repo.onChange(SettingsRegistry.language, (_) async {
|
||||
await initLang(initData);
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.themeBrightness, (_) async {
|
||||
initTheme(initData);
|
||||
initData.themeCubit.refresh();
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
});
|
||||
|
||||
Future<void> refreshTitleStyle(_) async {
|
||||
initTheme(initData);
|
||||
initData.themeCubit.refresh();
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
}
|
||||
|
||||
repo.onChange(SettingsRegistry.titleFont, refreshTitleStyle);
|
||||
repo.onChange(SettingsRegistry.titleWeight, refreshTitleStyle);
|
||||
repo.onChange(SettingsRegistry.titleCapitalization, refreshTitleStyle);
|
||||
|
||||
repo.onChange(SettingsRegistry.wearOsSupport, (enabled) async {
|
||||
if (!Platform.isAndroid) return;
|
||||
if (enabled && initDone) {
|
||||
final notifStatus = await Permission.notification.status;
|
||||
if (notifStatus.isDenied || notifStatus.isPermanentlyDenied) {
|
||||
await Permission.notification.request();
|
||||
}
|
||||
await WatchSyncHelper.startWearSyncServiceWithFreshCache(
|
||||
initData.client!,
|
||||
initData.appDir.path,
|
||||
);
|
||||
} else {
|
||||
await WatchSyncHelper.stopWearSyncService();
|
||||
}
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.morningNotificationEnabled, (enabled) async {
|
||||
LiveActivityService.onMorningNotificationEnabledChanged(enabled);
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.liveActivityEnabled, (enabled) async {
|
||||
await LiveActivityService.handleEnabledChange(enabled, isManual: true);
|
||||
await LiveActivityService.syncGlobalSettingWithCurrentUser();
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyAll, (enabled) async {
|
||||
await FcmService.handleEnabledChange(enabled);
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
|
||||
await FcmService.handleWakeupIntervalChange();
|
||||
});
|
||||
|
||||
for (final setting in [
|
||||
SettingsRegistry.notifyGrades,
|
||||
SettingsRegistry.notifyHomeworkTests,
|
||||
SettingsRegistry.notifyAbsences,
|
||||
SettingsRegistry.notifyLessons,
|
||||
SettingsRegistry.notifyMessages,
|
||||
]) {
|
||||
repo.onChange(setting, (_) async {
|
||||
await FcmService.updatePreferences();
|
||||
});
|
||||
}
|
||||
|
||||
// These two mirror LiveActivity widgets on iOS only, matching the original
|
||||
// postUpdate wiring that was only attached inside an `if (Platform.isIOS)` block.
|
||||
if (Platform.isIOS) {
|
||||
repo.onChange(SettingsRegistry.bellDelay, (value) async {
|
||||
LiveActivityService.onBellDelayChanged(value);
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.morningNotificationTime, (value) async {
|
||||
LiveActivityService.onMorningNotificationTimeChanged(value);
|
||||
});
|
||||
}
|
||||
}
|
||||
146
firka/lib/core/settings/settings_repository.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
import "package:flutter/widgets.dart";
|
||||
import "package:isar_community/isar.dart";
|
||||
|
||||
import "package:firka/core/bloc/settings_cubit.dart";
|
||||
import "package:firka_common/core/grade_helper.dart" as grade_helper;
|
||||
import "package:firka_common/data/database.dart";
|
||||
import "package:firka_common/data/models/app_settings_model.dart";
|
||||
import "package:firka_common/data/models/token_model.dart";
|
||||
import "package:firka_common/ui/theme/style.dart";
|
||||
|
||||
import "setting.dart";
|
||||
import "settings_schema.dart";
|
||||
|
||||
/// Isar id for the selected Kréta account, kept outside SettingsRegistry since
|
||||
/// it's not a bounded typed value. Distinct from appIcon's id 0 on purpose:
|
||||
/// the original code reused id 0 for both, silently clobbering one another.
|
||||
const _selectedAccountId = 1025;
|
||||
|
||||
/// Live, repository-bound access to every setting, e.g. `Settings.bellDelay.value`.
|
||||
/// Set once at startup once the real SettingsRepository exists. Distinct from
|
||||
/// SettingsRegistry, which only holds the typed key definitions (id, bounds,
|
||||
/// default) and has no notion of a current value.
|
||||
// ignore: non_constant_identifier_names
|
||||
late SettingsRepository Settings;
|
||||
|
||||
/// A single setting bound to its repository. Generated accessors on
|
||||
/// SettingsRepository (see settings_schema.gen.dart) return one of these per
|
||||
/// setting, so callers read `.value` and write via `.set`/`.setSilently`
|
||||
/// instead of the more verbose `repo.get(Settings.x)` / `repo.set(Settings.x, v)`.
|
||||
class SilentlySettable<T> {
|
||||
final SettingsRepository _repo;
|
||||
final Setting<T> _setting;
|
||||
|
||||
const SilentlySettable(this._repo, this._setting);
|
||||
|
||||
T get value => _repo.get(_setting);
|
||||
|
||||
Future<void> set(T value) => _repo.set(_setting, value);
|
||||
|
||||
Future<void> setSilently(T value) => _repo.setSilently(_setting, value);
|
||||
}
|
||||
|
||||
/// Owns every setting's current value and its Isar persistence.
|
||||
/// Replaces the per-item load/save methods that used to live on each SettingsItem subclass.
|
||||
class SettingsRepository {
|
||||
final Isar isar;
|
||||
SettingsCubit? cubit;
|
||||
IsarCollection<AppSettingsModel> get box => isar.appSettingsModels;
|
||||
final _values = <Id, dynamic>{};
|
||||
final _effects = <Id, List<Future<void> Function(dynamic)>>{};
|
||||
|
||||
SettingsRepository(this.isar, [this.cubit]);
|
||||
|
||||
T get<T>(Setting<T> setting) =>
|
||||
(_values[setting.id] ?? setting.defaultValue) as T;
|
||||
|
||||
Future<void> set<T>(Setting<T> setting, T value) async {
|
||||
await setSilently(setting, value);
|
||||
|
||||
for (final effect in _effects[setting.id] ?? const []) {
|
||||
await effect(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists without running registered onChange effects. For code that IS
|
||||
/// itself an effect syncing a setting from an external source (e.g. the
|
||||
/// backend's live activity preferences) and would otherwise recursively
|
||||
/// trigger its own onChange handler.
|
||||
Future<void> setSilently<T>(Setting<T> setting, T value) async {
|
||||
_values[setting.id] = value;
|
||||
|
||||
final row = AppSettingsModel()..id = setting.id;
|
||||
switch (value) {
|
||||
case bool v:
|
||||
row.valueBool = v;
|
||||
case double v:
|
||||
row.valueDouble = v;
|
||||
case Enum v:
|
||||
row.valueIndex = v.index;
|
||||
case String v:
|
||||
row.valueString = v;
|
||||
}
|
||||
await isar.writeTxn(() async {
|
||||
await box.put(row);
|
||||
});
|
||||
|
||||
cubit?.notifyChanged();
|
||||
}
|
||||
|
||||
void onChange<T>(Setting<T> setting, Future<void> Function(T value) effect) {
|
||||
(_effects[setting.id] ??= []).add((value) => effect(value as T));
|
||||
}
|
||||
|
||||
Future<void> loadAll() async {
|
||||
for (final setting in SettingsRegistry.all) {
|
||||
final row = await box.get(setting.id);
|
||||
_values[setting.id] = switch (setting) {
|
||||
BoolSetting() => row?.valueBool ?? setting.defaultValue,
|
||||
DoubleSetting() => row?.valueDouble ?? setting.defaultValue,
|
||||
EnumSetting(:final values) =>
|
||||
row?.valueIndex != null
|
||||
? values[row!.valueIndex!]
|
||||
: setting.defaultValue,
|
||||
StringSetting() => row?.valueString ?? setting.defaultValue,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
int roundGrade(num grade) {
|
||||
return grade_helper.roundGrade(
|
||||
grade,
|
||||
t1: get(SettingsRegistry.rounding1),
|
||||
t2: get(SettingsRegistry.rounding2),
|
||||
t3: get(SettingsRegistry.rounding3),
|
||||
t4: get(SettingsRegistry.rounding4),
|
||||
);
|
||||
}
|
||||
|
||||
Color getGradeColor(num grade) {
|
||||
return switch (roundGrade(grade)) {
|
||||
2 => appStyle.colors.grade2,
|
||||
3 => appStyle.colors.grade3,
|
||||
4 => appStyle.colors.grade4,
|
||||
5 => appStyle.colors.grade5,
|
||||
_ => appStyle.colors.grade1,
|
||||
};
|
||||
}
|
||||
|
||||
int get selectedAccountKey =>
|
||||
box.getSync(_selectedAccountId)?.valueIndex ?? 0;
|
||||
|
||||
Future<void> setSelectedAccountKey(int key) async {
|
||||
await isar.writeTxn(() async {
|
||||
await box.put(
|
||||
AppSettingsModel()
|
||||
..id = _selectedAccountId
|
||||
..valueIndex = key,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
TokenModel? getSelectedToken() {
|
||||
return isarInit.tokenModels.getSync(selectedAccountKey) ??
|
||||
isarInit.tokenModels.where().findFirstSync();
|
||||
}
|
||||
}
|
||||
199
firka/lib/core/settings/settings_schema.dart
Normal file
@@ -0,0 +1,199 @@
|
||||
import "setting.dart";
|
||||
import "settings_repository.dart";
|
||||
|
||||
part "settings_schema.gen.dart";
|
||||
|
||||
enum AppLanguage { auto, hu, en, de }
|
||||
|
||||
enum ThemeBrightness { auto, light, dark }
|
||||
|
||||
enum TitleFont {
|
||||
montserrat,
|
||||
monoton,
|
||||
pirataOne,
|
||||
justMeAgainDownHere,
|
||||
figtree,
|
||||
firaCode,
|
||||
vollkorn,
|
||||
}
|
||||
|
||||
enum TitleCapitalization { lower, normal, upper }
|
||||
|
||||
/// How often the background wakeup push (that triggers a silent data refresh
|
||||
/// + local notification) should fire. Backed by FCM topics `wakeup-hourly`/
|
||||
/// `wakeup-2hourly` sent by the `fcm-notifier` backend service.
|
||||
enum NotifyWakeupInterval { hourly, twoHourly }
|
||||
|
||||
abstract class SettingsSchema {
|
||||
@DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120)
|
||||
double get bellDelay;
|
||||
|
||||
@DoubleSetting(id: 1002, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2)
|
||||
double get rounding1;
|
||||
|
||||
@DoubleSetting(id: 1003, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2)
|
||||
double get rounding2;
|
||||
|
||||
@DoubleSetting(id: 1004, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2)
|
||||
double get rounding3;
|
||||
|
||||
@DoubleSetting(id: 1005, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2)
|
||||
double get rounding4;
|
||||
|
||||
@BoolSetting(id: 1006, defaultValue: true)
|
||||
bool get classAvgOnGraph;
|
||||
|
||||
@BoolSetting(id: 1007, defaultValue: false)
|
||||
bool get leftHandedMode;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1008,
|
||||
defaultValue: AppLanguage.auto,
|
||||
values: AppLanguage.values,
|
||||
)
|
||||
AppLanguage get language;
|
||||
|
||||
// SettingsAppIconPicker has always persisted under a
|
||||
// hardcoded id of 0 instead of the appIcon constant.
|
||||
@StringSetting(id: 0, defaultValue: "original")
|
||||
String get appIcon;
|
||||
|
||||
@BoolSetting(id: 1010, defaultValue: true)
|
||||
bool get childProtection;
|
||||
|
||||
@BoolSetting(id: 1011, defaultValue: false)
|
||||
bool get betaWarning;
|
||||
|
||||
@BoolSetting(id: 1012, defaultValue: true)
|
||||
bool get ttToastLessonNo;
|
||||
|
||||
@BoolSetting(id: 1013, defaultValue: true)
|
||||
bool get ttToastTestsAndHw;
|
||||
|
||||
@BoolSetting(id: 1014, defaultValue: true)
|
||||
bool get ttToastBreaks;
|
||||
|
||||
@BoolSetting(id: 1015, defaultValue: false)
|
||||
bool get statsForNerds;
|
||||
|
||||
@BoolSetting(id: 1016, defaultValue: false)
|
||||
bool get developerOptsEnabled;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1017,
|
||||
defaultValue: ThemeBrightness.auto,
|
||||
values: ThemeBrightness.values,
|
||||
)
|
||||
ThemeBrightness get themeBrightness;
|
||||
|
||||
@BoolSetting(id: 1018, defaultValue: true)
|
||||
bool get ttToastSubstitution;
|
||||
|
||||
@BoolSetting(id: 1019, defaultValue: false)
|
||||
bool get liveActivityEnabled;
|
||||
|
||||
@BoolSetting(id: 1020, defaultValue: false)
|
||||
bool get liveActivityPrivacyEverDeclined;
|
||||
|
||||
@BoolSetting(id: 1021, defaultValue: true)
|
||||
bool get morningNotificationEnabled;
|
||||
|
||||
@DoubleSetting(
|
||||
id: 1022,
|
||||
defaultValue: 120,
|
||||
min: 30,
|
||||
max: 240,
|
||||
precision: 0,
|
||||
step: 15,
|
||||
)
|
||||
double get morningNotificationTime;
|
||||
|
||||
@BoolSetting(id: 1023, defaultValue: true)
|
||||
bool get ttToastABTimetable;
|
||||
|
||||
@BoolSetting(id: 1024, defaultValue: false)
|
||||
bool get wearOsSupport;
|
||||
|
||||
// 1025 is reserved for the selected Kréta account outside SettingsRegistry.
|
||||
@EnumSetting(
|
||||
id: 1026,
|
||||
defaultValue: TitleFont.montserrat,
|
||||
values: TitleFont.values,
|
||||
)
|
||||
TitleFont get titleFont;
|
||||
|
||||
@DoubleSetting(
|
||||
id: 1027,
|
||||
defaultValue: 700,
|
||||
min: 100,
|
||||
max: 900,
|
||||
precision: 0,
|
||||
step: 100,
|
||||
)
|
||||
double get titleWeight;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1028,
|
||||
defaultValue: TitleCapitalization.normal,
|
||||
values: TitleCapitalization.values,
|
||||
)
|
||||
TitleCapitalization get titleCapitalization;
|
||||
|
||||
@StringSetting(id: 1029, defaultValue: "builtin-firka-firka")
|
||||
String get selectedThemeId;
|
||||
|
||||
@StringSetting(id: 1030, defaultValue: "firka")
|
||||
String get selectedCoreThemeId;
|
||||
|
||||
@StringSetting(id: 1031, defaultValue: "firka")
|
||||
String get selectedGradeThemeId;
|
||||
|
||||
@BoolSetting(id: 1032, defaultValue: false)
|
||||
bool get mockBackendEnabled;
|
||||
|
||||
@StringSetting(id: 1033, defaultValue: "http://10.0.0.144:8090")
|
||||
String get mockBackendUrl;
|
||||
|
||||
@StringSetting(id: 1034, defaultValue: "{}")
|
||||
String get lastSeen;
|
||||
|
||||
@BoolSetting(id: 1035, defaultValue: true)
|
||||
bool get surpriseGrades;
|
||||
|
||||
@BoolSetting(id: 1036, defaultValue: true)
|
||||
bool get seasonalAppIcons;
|
||||
|
||||
@BoolSetting(id: 1037, defaultValue: false)
|
||||
bool get uwuMode;
|
||||
|
||||
@BoolSetting(id: 1038, defaultValue: true)
|
||||
bool get notifyAll;
|
||||
|
||||
@BoolSetting(id: 1039, defaultValue: true)
|
||||
bool get notifyGrades;
|
||||
|
||||
@BoolSetting(id: 1040, defaultValue: true)
|
||||
bool get notifyHomeworkTests;
|
||||
|
||||
@BoolSetting(id: 1041, defaultValue: true)
|
||||
bool get notifyAbsences;
|
||||
|
||||
@BoolSetting(id: 1042, defaultValue: true)
|
||||
bool get notifyLessons;
|
||||
|
||||
@BoolSetting(id: 1043, defaultValue: true)
|
||||
bool get notifyMessages;
|
||||
|
||||
@StringSetting(id: 1044, defaultValue: "[]")
|
||||
String get notifyMutedSubjects;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1045,
|
||||
defaultValue: NotifyWakeupInterval.hourly,
|
||||
values: NotifyWakeupInterval.values,
|
||||
)
|
||||
NotifyWakeupInterval get notifyWakeupInterval;
|
||||
|
||||
@BoolSetting(id: 1046, defaultValue: false)
|
||||
bool get fcmDebugNotifyOnMessage;
|
||||
}
|
||||
103
firka/lib/core/settings/settings_schema.gen.dart
Normal file
@@ -0,0 +1,103 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of "settings_schema.dart";
|
||||
|
||||
class SettingsRegistry {
|
||||
static const bellDelay = DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120);
|
||||
static const rounding1 = DoubleSetting(id: 1002, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2);
|
||||
static const rounding2 = DoubleSetting(id: 1003, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2);
|
||||
static const rounding3 = DoubleSetting(id: 1004, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2);
|
||||
static const rounding4 = DoubleSetting(id: 1005, defaultValue: 0.5, min: 0.1, max: 0.99, precision: 2);
|
||||
static const classAvgOnGraph = BoolSetting(id: 1006, defaultValue: true);
|
||||
static const leftHandedMode = BoolSetting(id: 1007, defaultValue: false);
|
||||
static const language = EnumSetting(id: 1008, defaultValue: AppLanguage.auto, values: AppLanguage.values);
|
||||
static const appIcon = StringSetting(id: 0, defaultValue: "original");
|
||||
static const childProtection = BoolSetting(id: 1010, defaultValue: true);
|
||||
static const betaWarning = BoolSetting(id: 1011, defaultValue: false);
|
||||
static const ttToastLessonNo = BoolSetting(id: 1012, defaultValue: true);
|
||||
static const ttToastTestsAndHw = BoolSetting(id: 1013, defaultValue: true);
|
||||
static const ttToastBreaks = BoolSetting(id: 1014, defaultValue: true);
|
||||
static const statsForNerds = BoolSetting(id: 1015, defaultValue: false);
|
||||
static const developerOptsEnabled = BoolSetting(id: 1016, defaultValue: false);
|
||||
static const themeBrightness = EnumSetting(id: 1017, defaultValue: ThemeBrightness.auto, values: ThemeBrightness.values);
|
||||
static const ttToastSubstitution = BoolSetting(id: 1018, defaultValue: true);
|
||||
static const liveActivityEnabled = BoolSetting(id: 1019, defaultValue: false);
|
||||
static const liveActivityPrivacyEverDeclined = BoolSetting(id: 1020, defaultValue: false);
|
||||
static const morningNotificationEnabled = BoolSetting(id: 1021, defaultValue: true);
|
||||
static const morningNotificationTime = DoubleSetting(id: 1022, defaultValue: 120, min: 30, max: 240, precision: 0, step: 15);
|
||||
static const ttToastABTimetable = BoolSetting(id: 1023, defaultValue: true);
|
||||
static const wearOsSupport = BoolSetting(id: 1024, defaultValue: false);
|
||||
static const titleFont = EnumSetting(id: 1026, defaultValue: TitleFont.montserrat, values: TitleFont.values);
|
||||
static const titleWeight = DoubleSetting(id: 1027, defaultValue: 700, min: 100, max: 900, precision: 0, step: 100);
|
||||
static const titleCapitalization = EnumSetting(id: 1028, defaultValue: TitleCapitalization.normal, values: TitleCapitalization.values);
|
||||
static const selectedThemeId = StringSetting(id: 1029, defaultValue: "builtin-firka-firka");
|
||||
static const selectedCoreThemeId = StringSetting(id: 1030, defaultValue: "firka");
|
||||
static const selectedGradeThemeId = StringSetting(id: 1031, defaultValue: "firka");
|
||||
static const mockBackendEnabled = BoolSetting(id: 1032, defaultValue: false);
|
||||
static const mockBackendUrl = StringSetting(id: 1033, defaultValue: "http://10.0.0.144:8090");
|
||||
static const lastSeen = StringSetting(id: 1034, defaultValue: "{}");
|
||||
static const surpriseGrades = BoolSetting(id: 1035, defaultValue: true);
|
||||
static const seasonalAppIcons = BoolSetting(id: 1036, defaultValue: true);
|
||||
static const uwuMode = BoolSetting(id: 1037, defaultValue: false);
|
||||
static const notifyAll = BoolSetting(id: 1038, defaultValue: true);
|
||||
static const notifyGrades = BoolSetting(id: 1039, defaultValue: true);
|
||||
static const notifyHomeworkTests = BoolSetting(id: 1040, defaultValue: true);
|
||||
static const notifyAbsences = BoolSetting(id: 1041, defaultValue: true);
|
||||
static const notifyLessons = BoolSetting(id: 1042, defaultValue: true);
|
||||
static const notifyMessages = BoolSetting(id: 1043, defaultValue: true);
|
||||
static const notifyMutedSubjects = StringSetting(id: 1044, defaultValue: "[]");
|
||||
static const notifyWakeupInterval = EnumSetting(id: 1045, defaultValue: NotifyWakeupInterval.hourly, values: NotifyWakeupInterval.values);
|
||||
static const fcmDebugNotifyOnMessage = BoolSetting(id: 1046, defaultValue: false);
|
||||
|
||||
static const all = <Setting>[
|
||||
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, liveActivityEnabled, liveActivityPrivacyEverDeclined, morningNotificationEnabled, morningNotificationTime, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage,
|
||||
];
|
||||
}
|
||||
|
||||
extension SettingsAccessors on SettingsRepository {
|
||||
SilentlySettable<double> get bellDelay => SilentlySettable(this, SettingsRegistry.bellDelay);
|
||||
SilentlySettable<double> get rounding1 => SilentlySettable(this, SettingsRegistry.rounding1);
|
||||
SilentlySettable<double> get rounding2 => SilentlySettable(this, SettingsRegistry.rounding2);
|
||||
SilentlySettable<double> get rounding3 => SilentlySettable(this, SettingsRegistry.rounding3);
|
||||
SilentlySettable<double> get rounding4 => SilentlySettable(this, SettingsRegistry.rounding4);
|
||||
SilentlySettable<bool> get classAvgOnGraph => SilentlySettable(this, SettingsRegistry.classAvgOnGraph);
|
||||
SilentlySettable<bool> get leftHandedMode => SilentlySettable(this, SettingsRegistry.leftHandedMode);
|
||||
SilentlySettable<AppLanguage> get language => SilentlySettable(this, SettingsRegistry.language);
|
||||
SilentlySettable<String> get appIcon => SilentlySettable(this, SettingsRegistry.appIcon);
|
||||
SilentlySettable<bool> get childProtection => SilentlySettable(this, SettingsRegistry.childProtection);
|
||||
SilentlySettable<bool> get betaWarning => SilentlySettable(this, SettingsRegistry.betaWarning);
|
||||
SilentlySettable<bool> get ttToastLessonNo => SilentlySettable(this, SettingsRegistry.ttToastLessonNo);
|
||||
SilentlySettable<bool> get ttToastTestsAndHw => SilentlySettable(this, SettingsRegistry.ttToastTestsAndHw);
|
||||
SilentlySettable<bool> get ttToastBreaks => SilentlySettable(this, SettingsRegistry.ttToastBreaks);
|
||||
SilentlySettable<bool> get statsForNerds => SilentlySettable(this, SettingsRegistry.statsForNerds);
|
||||
SilentlySettable<bool> get developerOptsEnabled => SilentlySettable(this, SettingsRegistry.developerOptsEnabled);
|
||||
SilentlySettable<ThemeBrightness> get themeBrightness => SilentlySettable(this, SettingsRegistry.themeBrightness);
|
||||
SilentlySettable<bool> get ttToastSubstitution => SilentlySettable(this, SettingsRegistry.ttToastSubstitution);
|
||||
SilentlySettable<bool> get liveActivityEnabled => SilentlySettable(this, SettingsRegistry.liveActivityEnabled);
|
||||
SilentlySettable<bool> get liveActivityPrivacyEverDeclined => SilentlySettable(this, SettingsRegistry.liveActivityPrivacyEverDeclined);
|
||||
SilentlySettable<bool> get morningNotificationEnabled => SilentlySettable(this, SettingsRegistry.morningNotificationEnabled);
|
||||
SilentlySettable<double> get morningNotificationTime => SilentlySettable(this, SettingsRegistry.morningNotificationTime);
|
||||
SilentlySettable<bool> get ttToastABTimetable => SilentlySettable(this, SettingsRegistry.ttToastABTimetable);
|
||||
SilentlySettable<bool> get wearOsSupport => SilentlySettable(this, SettingsRegistry.wearOsSupport);
|
||||
SilentlySettable<TitleFont> get titleFont => SilentlySettable(this, SettingsRegistry.titleFont);
|
||||
SilentlySettable<double> get titleWeight => SilentlySettable(this, SettingsRegistry.titleWeight);
|
||||
SilentlySettable<TitleCapitalization> get titleCapitalization => SilentlySettable(this, SettingsRegistry.titleCapitalization);
|
||||
SilentlySettable<String> get selectedThemeId => SilentlySettable(this, SettingsRegistry.selectedThemeId);
|
||||
SilentlySettable<String> get selectedCoreThemeId => SilentlySettable(this, SettingsRegistry.selectedCoreThemeId);
|
||||
SilentlySettable<String> get selectedGradeThemeId => SilentlySettable(this, SettingsRegistry.selectedGradeThemeId);
|
||||
SilentlySettable<bool> get mockBackendEnabled => SilentlySettable(this, SettingsRegistry.mockBackendEnabled);
|
||||
SilentlySettable<String> get mockBackendUrl => SilentlySettable(this, SettingsRegistry.mockBackendUrl);
|
||||
SilentlySettable<String> get lastSeen => SilentlySettable(this, SettingsRegistry.lastSeen);
|
||||
SilentlySettable<bool> get surpriseGrades => SilentlySettable(this, SettingsRegistry.surpriseGrades);
|
||||
SilentlySettable<bool> get seasonalAppIcons => SilentlySettable(this, SettingsRegistry.seasonalAppIcons);
|
||||
SilentlySettable<bool> get uwuMode => SilentlySettable(this, SettingsRegistry.uwuMode);
|
||||
SilentlySettable<bool> get notifyAll => SilentlySettable(this, SettingsRegistry.notifyAll);
|
||||
SilentlySettable<bool> get notifyGrades => SilentlySettable(this, SettingsRegistry.notifyGrades);
|
||||
SilentlySettable<bool> get notifyHomeworkTests => SilentlySettable(this, SettingsRegistry.notifyHomeworkTests);
|
||||
SilentlySettable<bool> get notifyAbsences => SilentlySettable(this, SettingsRegistry.notifyAbsences);
|
||||
SilentlySettable<bool> get notifyLessons => SilentlySettable(this, SettingsRegistry.notifyLessons);
|
||||
SilentlySettable<bool> get notifyMessages => SilentlySettable(this, SettingsRegistry.notifyMessages);
|
||||
SilentlySettable<String> get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
|
||||
SilentlySettable<NotifyWakeupInterval> get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
|
||||
SilentlySettable<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
|
||||
}
|
||||
170
firka/lib/core/settings/settings_ui.dart
Normal file
@@ -0,0 +1,170 @@
|
||||
import "package:firka/ui/shared/firka_icon.dart";
|
||||
|
||||
import "setting.dart";
|
||||
|
||||
/// UI-only description of a settings screen: icons, titles, grouping, navigation,
|
||||
/// visibility. Holds no values itself, only references to typed [Setting]s whose
|
||||
/// values live in SettingsRepository. Separate from the data schema on purpose:
|
||||
/// see AGENTS.md and the settings redesign plan for why.
|
||||
sealed class SettingsUiNode {
|
||||
final bool Function() visible;
|
||||
|
||||
const SettingsUiNode(this.visible);
|
||||
}
|
||||
|
||||
class SettingsUiGroup extends SettingsUiNode {
|
||||
final List<SettingsUiNode> children;
|
||||
|
||||
const SettingsUiGroup(this.children, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiPadding extends SettingsUiNode {
|
||||
final double padding;
|
||||
|
||||
const SettingsUiPadding(this.padding, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiBackHeader extends SettingsUiNode {
|
||||
final String title;
|
||||
|
||||
const SettingsUiBackHeader(this.title, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiHeader extends SettingsUiNode {
|
||||
final String title;
|
||||
|
||||
const SettingsUiHeader(this.title, bool Function() visible) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiMediumHeader extends SettingsUiNode {
|
||||
final String title;
|
||||
|
||||
const SettingsUiMediumHeader(this.title, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiHeaderSmall extends SettingsUiNode {
|
||||
final String title;
|
||||
|
||||
const SettingsUiHeaderSmall(this.title, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiSubGroup extends SettingsUiNode {
|
||||
final FirkaIconType? iconType;
|
||||
final Object? iconData;
|
||||
final String title;
|
||||
final List<SettingsUiNode> children;
|
||||
final String? redirectTo;
|
||||
final String? subtitle;
|
||||
|
||||
const SettingsUiSubGroup(
|
||||
this.iconType,
|
||||
this.iconData,
|
||||
this.title,
|
||||
this.children,
|
||||
bool Function() visible, [
|
||||
this.redirectTo,
|
||||
this.subtitle,
|
||||
]) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiBoolean extends SettingsUiNode {
|
||||
final FirkaIconType? iconType;
|
||||
final Object? iconData;
|
||||
final String title;
|
||||
final BoolSetting setting;
|
||||
|
||||
const SettingsUiBoolean(
|
||||
this.iconType,
|
||||
this.iconData,
|
||||
this.title,
|
||||
this.setting,
|
||||
bool Function() visible,
|
||||
) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiDouble extends SettingsUiNode {
|
||||
final FirkaIconType? iconType;
|
||||
final Object? iconData;
|
||||
final String title;
|
||||
final DoubleSetting setting;
|
||||
|
||||
const SettingsUiDouble(
|
||||
this.iconType,
|
||||
this.iconData,
|
||||
this.title,
|
||||
this.setting,
|
||||
bool Function() visible,
|
||||
) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiEnum extends SettingsUiNode {
|
||||
final EnumSetting setting;
|
||||
final List<String> optionLabels;
|
||||
|
||||
const SettingsUiEnum(this.setting, this.optionLabels, bool Function() visible)
|
||||
: super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiButton extends SettingsUiNode {
|
||||
final FirkaIconType? iconType;
|
||||
final Object? iconData;
|
||||
final String title;
|
||||
final Future<void> Function() onTap;
|
||||
|
||||
const SettingsUiButton(
|
||||
this.iconType,
|
||||
this.iconData,
|
||||
this.title,
|
||||
bool Function() visible,
|
||||
this.onTap,
|
||||
) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiAppIconPreview extends SettingsUiNode {
|
||||
const SettingsUiAppIconPreview(super.visible);
|
||||
}
|
||||
|
||||
class SettingsUiPersonalization extends SettingsUiNode {
|
||||
final List<SettingsUiNode> appIconPickerChildren;
|
||||
|
||||
const SettingsUiPersonalization(
|
||||
this.appIconPickerChildren,
|
||||
bool Function() visible,
|
||||
) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiAppIconPicker extends SettingsUiNode {
|
||||
final Map<String, List<String>> iconGroups;
|
||||
final SettingsUiBoolean childProtection;
|
||||
|
||||
const SettingsUiAppIconPicker(
|
||||
this.iconGroups,
|
||||
this.childProtection,
|
||||
bool Function() visible,
|
||||
) : super(visible);
|
||||
}
|
||||
|
||||
class SettingsUiKretaAccountPicker extends SettingsUiNode {
|
||||
const SettingsUiKretaAccountPicker(super.visible);
|
||||
}
|
||||
|
||||
class SettingsUiLogs extends SettingsUiNode {
|
||||
const SettingsUiLogs(super.visible);
|
||||
}
|
||||
|
||||
class SettingsUiFcmStatus extends SettingsUiNode {
|
||||
const SettingsUiFcmStatus(super.visible);
|
||||
}
|
||||
|
||||
class SettingsUiLicensePage extends SettingsUiNode {
|
||||
const SettingsUiLicensePage(super.visible);
|
||||
}
|
||||
|
||||
class SettingsUiSubjectNotifications extends SettingsUiNode {
|
||||
const SettingsUiSubjectNotifications(super.visible);
|
||||
}
|
||||
25
firka/lib/core/settings/title_font.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
import "package:firka/core/settings/settings_schema.dart";
|
||||
|
||||
extension TitleFontInfo on TitleFont {
|
||||
String get fontFamily => switch (this) {
|
||||
TitleFont.montserrat => "Montserrat",
|
||||
TitleFont.monoton => "Monoton",
|
||||
TitleFont.pirataOne => "Pirata One",
|
||||
TitleFont.justMeAgainDownHere => "Just Me Again Down Here",
|
||||
TitleFont.figtree => "Figtree",
|
||||
TitleFont.firaCode => "Fira Code",
|
||||
TitleFont.vollkorn => "Vollkorn",
|
||||
};
|
||||
|
||||
String get displayName => fontFamily;
|
||||
|
||||
bool get supportsWeight => switch (this) {
|
||||
TitleFont.montserrat ||
|
||||
TitleFont.figtree ||
|
||||
TitleFont.firaCode ||
|
||||
TitleFont.vollkorn => true,
|
||||
TitleFont.monoton ||
|
||||
TitleFont.pirataOne ||
|
||||
TitleFont.justMeAgainDownHere => false,
|
||||
};
|
||||
}
|
||||
31
firka/lib/core/snowflake.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import "dart:math";
|
||||
|
||||
/// Local Twitter-style snowflake IDs (64-bit, decimal string).
|
||||
class Snowflake {
|
||||
static const int _epochMs = 1704067200000; // 2024-01-01 UTC
|
||||
static final int _workerId = Random().nextInt(1 << 10);
|
||||
static int _sequence = 0;
|
||||
static int _lastTimestamp = -1;
|
||||
|
||||
static String nextId() {
|
||||
var ts = DateTime.now().millisecondsSinceEpoch;
|
||||
if (ts < _lastTimestamp) {
|
||||
ts = _lastTimestamp;
|
||||
}
|
||||
|
||||
if (ts == _lastTimestamp) {
|
||||
_sequence = (_sequence + 1) & 0xFFF;
|
||||
if (_sequence == 0) {
|
||||
while (ts <= _lastTimestamp) {
|
||||
ts = DateTime.now().millisecondsSinceEpoch;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_sequence = 0;
|
||||
}
|
||||
|
||||
_lastTimestamp = ts;
|
||||
final id = ((ts - _epochMs) << 22) | (_workerId << 12) | _sequence;
|
||||
return id.toString();
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ class IOSWidgetHelper {
|
||||
'description': subject.category.description,
|
||||
},
|
||||
'sortIndex': subject.sortIndex,
|
||||
'teacherName': subject.teacherName,
|
||||
'teacherName': null,
|
||||
}
|
||||
: {
|
||||
'uid': '',
|
||||
@@ -152,8 +152,7 @@ class IOSWidgetHelper {
|
||||
},
|
||||
'theme': lesson.theme,
|
||||
'roomName': lesson.roomName,
|
||||
'isCancelled':
|
||||
lesson.state.name?.toLowerCase().contains('elmarad') ?? false,
|
||||
'isCancelled': lesson.state.name.toLowerCase().contains('elmarad'),
|
||||
'isSubstitution': lesson.substituteTeacher != null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
part 'generic_cache_model.g.dart';
|
||||
|
||||
enum CacheId {
|
||||
getStudent,
|
||||
getNoticeBoard,
|
||||
getInfoBoard,
|
||||
getGrades,
|
||||
getOmissions,
|
||||
getTests,
|
||||
getClassGroup,
|
||||
getSubjectAvg,
|
||||
getLessons,
|
||||
getHomework,
|
||||
getClassGroupAvg,
|
||||
}
|
||||
|
||||
@collection
|
||||
class GenericCacheModel {
|
||||
Id? cacheKey;
|
||||
String? cacheData;
|
||||
|
||||
GenericCacheModel();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/util.dart';
|
||||
|
||||
part 'timetable_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class TimetableCacheModel extends DatedCacheEntry {
|
||||
TimetableCacheModel();
|
||||
}
|
||||
|
||||
Future<void> resetOldTimeTableCache(Isar isar) async {
|
||||
var now = timeNow();
|
||||
var weeks = await isar.timetableCacheModels.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.timetableCacheModels.deleteAll(weeksToRemove);
|
||||
});
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
|
||||
class DatedCacheEntry {
|
||||
Id? cacheKey;
|
||||
late List<String> values;
|
||||
}
|
||||
|
||||
int genCacheKey(DateTime date, int studentId) {
|
||||
var md = date.month * pow(10, 2) + date.day;
|
||||
|
||||
return (md * pow(10, 11) + studentId) as int;
|
||||
}
|
||||
|
||||
DateTime getDate(int key) {
|
||||
var md = key ~/ pow(10, 11);
|
||||
var month = md ~/ pow(10, 2);
|
||||
var day = (md - month * pow(10, 2)) as int;
|
||||
|
||||
return DateTime(timeNow().year, month, day);
|
||||
}
|
||||
@@ -3,11 +3,12 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
import 'package:firka/data/ios_widget_helper.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/ios_widget_helper.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -16,13 +17,12 @@ import 'package:path_provider/path_provider.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class WidgetCacheHelper {
|
||||
static Map<String, dynamic> toJson(FirkaStyle style, List<Lesson> timetable) {
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle style,
|
||||
List<LessonCacheModel> timetable,
|
||||
) {
|
||||
List<Map<String, dynamic>> timetableJson = [];
|
||||
|
||||
for (var lesson in timetable) {
|
||||
timetableJson.add(lesson.toJson());
|
||||
}
|
||||
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
@@ -86,20 +86,13 @@ class WidgetCacheHelper {
|
||||
|
||||
final start = now.subtract(Duration(days: 7));
|
||||
final end = now.add(Duration(days: 14));
|
||||
final lessons = await client.getTimeTable(start, end, forceCache: false);
|
||||
final lessons = await client.getLessons(start, end);
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
if (lessons.response != null) {
|
||||
debugPrint(
|
||||
'Android widget cache: ${lessons.response!.length} lessons (cached: ${lessons.cached})',
|
||||
);
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons.response!)),
|
||||
);
|
||||
} else {
|
||||
debugPrint('Android widget cache: No lessons to cache');
|
||||
}
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons)),
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> generateWidgetStateForDate(
|
||||
@@ -108,16 +101,8 @@ class WidgetCacheHelper {
|
||||
KretaClient client,
|
||||
) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final dayStart = DateTime(date.year, date.month, date.day);
|
||||
final dayEnd = dayStart.add(Duration(hours: 23, minutes: 59));
|
||||
final lessons = await client.getTimeTable(
|
||||
dayStart,
|
||||
dayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
final dayLessons = lessons.response ?? [];
|
||||
|
||||
final json = toJson(style, dayLessons);
|
||||
final json = toJson(style, []);
|
||||
json['displayDate'] =
|
||||
'${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
|
||||
|
||||
@@ -125,73 +110,41 @@ class WidgetCacheHelper {
|
||||
await widgetFile.writeAsString(jsonEncode(json));
|
||||
}
|
||||
|
||||
static Future<void> updateIOSWidgets({
|
||||
required String locale,
|
||||
required String theme,
|
||||
required List<Lesson> todayLessons,
|
||||
required List<Lesson> tomorrowLessons,
|
||||
List<Lesson> nextSchoolDayLessons = const [],
|
||||
DateTime? nextSchoolDayDate,
|
||||
required List<Grade> grades,
|
||||
required Map<String, double> subjectAverages,
|
||||
required double? overallAverage,
|
||||
WidgetBreakInfo? currentBreak,
|
||||
}) async {
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: locale,
|
||||
theme: theme,
|
||||
todayLessons: todayLessons,
|
||||
tomorrowLessons: tomorrowLessons,
|
||||
nextSchoolDayLessons: nextSchoolDayLessons,
|
||||
nextSchoolDayDate: nextSchoolDayDate,
|
||||
grades: grades,
|
||||
subjectAverages: subjectAverages,
|
||||
overallAverage: overallAverage,
|
||||
currentBreak: currentBreak,
|
||||
);
|
||||
}
|
||||
|
||||
/// Comprehensive iOS widget refresh that collects all necessary data
|
||||
/// Call this on: app open, user switch, data refresh
|
||||
static Future<void> refreshIOSWidgets(
|
||||
KretaClient client,
|
||||
SettingsStore settings,
|
||||
SettingsRepository settings,
|
||||
) async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
try {
|
||||
final langIndex =
|
||||
(settings.group("settings").subGroup("application")["language"]
|
||||
as SettingsItemsRadio)
|
||||
.activeIndex;
|
||||
final language = settings.get(SettingsRegistry.language);
|
||||
String locale;
|
||||
switch (langIndex) {
|
||||
case 1:
|
||||
switch (language) {
|
||||
case AppLanguage.hu:
|
||||
locale = 'hu';
|
||||
break;
|
||||
case 2:
|
||||
case AppLanguage.en:
|
||||
locale = 'en';
|
||||
break;
|
||||
case 3:
|
||||
case AppLanguage.de:
|
||||
locale = 'de';
|
||||
break;
|
||||
default:
|
||||
case AppLanguage.auto:
|
||||
locale = 'hu';
|
||||
}
|
||||
|
||||
final themeIndex =
|
||||
(settings.group("settings").subGroup("customization")["theme"]
|
||||
as SettingsItemsRadio)
|
||||
.activeIndex;
|
||||
final themeBrightness = settings.get(SettingsRegistry.themeBrightness);
|
||||
String theme;
|
||||
switch (themeIndex) {
|
||||
case 1:
|
||||
switch (themeBrightness) {
|
||||
case ThemeBrightness.light:
|
||||
theme = 'light';
|
||||
break;
|
||||
case 2:
|
||||
case ThemeBrightness.dark:
|
||||
theme = 'dark';
|
||||
break;
|
||||
default:
|
||||
case ThemeBrightness.auto:
|
||||
theme =
|
||||
SchedulerBinding.instance.platformDispatcher.platformBrightness ==
|
||||
Brightness.light
|
||||
@@ -203,19 +156,17 @@ class WidgetCacheHelper {
|
||||
final todayMidnight = DateTime(now.year, now.month, now.day);
|
||||
final tomorrowMidnight = todayMidnight.add(Duration(days: 1));
|
||||
|
||||
final todayResponse = await client.getTimeTable(
|
||||
await client.getLessons(
|
||||
todayMidnight,
|
||||
todayMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
final tomorrowResponse = await client.getTimeTable(
|
||||
await client.getLessons(
|
||||
tomorrowMidnight,
|
||||
tomorrowMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
final todayLessons = todayResponse.response ?? [];
|
||||
final tomorrowLessons = tomorrowResponse.response ?? [];
|
||||
final todayLessons = [];
|
||||
final tomorrowLessons = [];
|
||||
|
||||
debugPrint(
|
||||
'iOS widget refresh: ${todayLessons.length} today lessons, ${tomorrowLessons.length} tomorrow lessons',
|
||||
@@ -226,12 +177,11 @@ class WidgetCacheHelper {
|
||||
if (tomorrowLessons.isEmpty) {
|
||||
for (int i = 2; i <= 7; i++) {
|
||||
final dayMidnight = todayMidnight.add(Duration(days: i));
|
||||
final dayResponse = await client.getTimeTable(
|
||||
await client.getLessons(
|
||||
dayMidnight,
|
||||
dayMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
final dayLessons = dayResponse.response ?? [];
|
||||
final dayLessons = <Lesson>[];
|
||||
if (dayLessons.isNotEmpty) {
|
||||
nextSchoolDayLessons = dayLessons;
|
||||
nextSchoolDayDate = dayMidnight;
|
||||
@@ -243,11 +193,11 @@ class WidgetCacheHelper {
|
||||
}
|
||||
}
|
||||
|
||||
final gradesResponse = await client.getGrades(forceCache: false);
|
||||
final grades = gradesResponse.response ?? [];
|
||||
final gradesResponse = await client.getGrades();
|
||||
final grades = [];
|
||||
|
||||
debugPrint(
|
||||
'iOS widget refresh: ${grades.length} grades fetched (cached: ${gradesResponse.cached})',
|
||||
'iOS widget refresh: ${grades.length} grades fetched (cached: $gradesResponse)',
|
||||
);
|
||||
|
||||
final Map<String, double> subjectAverages = {};
|
||||
@@ -258,25 +208,18 @@ class WidgetCacheHelper {
|
||||
|
||||
subjects.addAll(grades.map((g) => g.subject));
|
||||
|
||||
for (var subject in subjects) {
|
||||
final average = grades.getAverageBySubject(subject);
|
||||
if (average != null) {
|
||||
subjectAverages[subject.uid] = average;
|
||||
}
|
||||
}
|
||||
|
||||
WidgetBreakInfo? currentBreak;
|
||||
|
||||
await updateIOSWidgets(
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: locale,
|
||||
theme: theme,
|
||||
todayLessons: todayLessons,
|
||||
tomorrowLessons: tomorrowLessons,
|
||||
todayLessons: [],
|
||||
tomorrowLessons: [],
|
||||
nextSchoolDayLessons: nextSchoolDayLessons,
|
||||
nextSchoolDayDate: nextSchoolDayDate,
|
||||
grades: grades,
|
||||
grades: [],
|
||||
subjectAverages: subjectAverages,
|
||||
overallAverage: grades.getSubjectAverage(),
|
||||
overallAverage: 0.0,
|
||||
currentBreak: currentBreak,
|
||||
);
|
||||
|
||||
@@ -291,7 +234,7 @@ class WidgetCacheHelper {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
try {
|
||||
await updateIOSWidgets(
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: 'hu',
|
||||
theme: 'light',
|
||||
todayLessons: [],
|
||||
|
||||
62
firka/lib/firebase_options.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
// File generated by FlutterFire CLI.
|
||||
// ignore_for_file: type=lint
|
||||
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
|
||||
import 'package:flutter/foundation.dart'
|
||||
show defaultTargetPlatform, kIsWeb, TargetPlatform;
|
||||
|
||||
/// Default [FirebaseOptions] for use with your Firebase apps.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'firebase_options.dart';
|
||||
/// // ...
|
||||
/// await Firebase.initializeApp(
|
||||
/// options: DefaultFirebaseOptions.currentPlatform,
|
||||
/// );
|
||||
/// ```
|
||||
class DefaultFirebaseOptions {
|
||||
static FirebaseOptions get currentPlatform {
|
||||
if (kIsWeb) {
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for web - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for ios - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.macOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for macos - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.windows:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for windows - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.linux:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for linux - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static const FirebaseOptions android = FirebaseOptions(
|
||||
apiKey: 'AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4',
|
||||
appId: '1:219357380322:android:5b776732799faa5c08a8bb',
|
||||
messagingSenderId: '219357380322',
|
||||
projectId: 'firka-4633b',
|
||||
storageBucket: 'firka-4633b.firebasestorage.app',
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,10 @@ void main() async {
|
||||
dio.options.receiveTimeout = Duration(seconds: 3);
|
||||
dio.options.validateStatus = (status) => status != null && status < 500;
|
||||
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.presentError(details);
|
||||
};
|
||||
|
||||
runZonedGuarded(
|
||||
() async {
|
||||
logger.finest("Initializing app");
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka/ui/phone/pages/home/home_omissions.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/core/settings/settings_ui.dart';
|
||||
import 'package:firka/ui/phone/pages/home/home_grades.dart';
|
||||
import 'package:firka/ui/phone/pages/home/home_grades_subject.dart';
|
||||
import 'package:firka/ui/phone/pages/home/home_main.dart';
|
||||
@@ -16,20 +20,23 @@ import 'package:firka/ui/phone/screens/login/login_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/message/message_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/home/home_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/settings/settings_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/theme_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/themes_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
|
||||
import 'package:firka/routing/chart_interaction_scope.dart';
|
||||
import 'package:firka/routing/shell_with_nav_bar.dart';
|
||||
import 'package:firka/routing/swipable_navigator_container.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
GoRouter createAppRouter() {
|
||||
final subjectRoute = GoRoute(
|
||||
path: 'subject',
|
||||
builder: (context, state) {
|
||||
return DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: HomeGradesSubjectScreen(state.extra as Subject, initData),
|
||||
child: HomeGradesSubjectScreen.subject(
|
||||
state.extra as SubjectCacheModel,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -83,18 +90,35 @@ GoRouter createAppRouter() {
|
||||
path: '/settings',
|
||||
builder: (context, state) {
|
||||
final items = state.extra != null
|
||||
? state.extra! as LinkedHashMap<String, SettingsItem>
|
||||
: initData.settings.items;
|
||||
? state.extra! as List<SettingsUiNode>
|
||||
: buildSettingsTree(initData.l10n).children;
|
||||
return DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: SettingsScreen(initData, items, key: state.pageKey),
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/themes',
|
||||
builder: (context, state) => DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: ThemesScreen(initData, key: state.pageKey),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/theme',
|
||||
builder: (context, state) {
|
||||
final args = state.extra as ThemeScreenArgs;
|
||||
return DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: ThemeScreen(initData, args, key: state.pageKey),
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/message',
|
||||
builder: (context, state) {
|
||||
final info = state.extra as MessageItem?;
|
||||
final info = state.extra as MessageCacheModel?;
|
||||
if (info == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
@@ -167,9 +191,12 @@ GoRouter createAppRouter() {
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: 'monthly',
|
||||
builder: (context, state) => DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: HomeTimetableMonthlyScreen(initData),
|
||||
pageBuilder: (context, state) => _viewSwitchPage(
|
||||
key: state.pageKey,
|
||||
child: DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: HomeTimetableMonthlyScreen(initData),
|
||||
),
|
||||
),
|
||||
),
|
||||
subjectRoute,
|
||||
@@ -177,6 +204,20 @@ GoRouter createAppRouter() {
|
||||
),
|
||||
],
|
||||
),
|
||||
StatefulShellBranch(
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/omissions',
|
||||
pageBuilder: (context, state) => NoTransitionPage(
|
||||
key: state.pageKey,
|
||||
child: DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: HomeOmissionsScreen(initData),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
@@ -185,10 +226,8 @@ GoRouter createAppRouter() {
|
||||
|
||||
String get _initialLocation {
|
||||
if (!initDone) return '/';
|
||||
if (initData.tokens.isEmpty) return '/login';
|
||||
final betaWarning = initData.settings
|
||||
.group('settings')
|
||||
.boolean('beta_warning');
|
||||
if (initData.client == null) return '/login';
|
||||
final betaWarning = Settings.betaWarning.value;
|
||||
if (!betaWarning) return '/beta';
|
||||
return '/home';
|
||||
}
|
||||
@@ -196,10 +235,8 @@ String get _initialLocation {
|
||||
String? _redirect(BuildContext context, GoRouterState state) {
|
||||
if (!initDone) return null;
|
||||
final location = state.matchedLocation;
|
||||
final hasTokens = initData.tokens.isNotEmpty;
|
||||
final betaWarning = initData.settings
|
||||
.group('settings')
|
||||
.boolean('beta_warning');
|
||||
final hasTokens = initData.client != null;
|
||||
final betaWarning = Settings.betaWarning.value;
|
||||
|
||||
if (!hasTokens) {
|
||||
if (location != '/login') return '/login';
|
||||
@@ -224,3 +261,33 @@ String? _redirect(BuildContext context, GoRouterState state) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
CustomTransitionPage<void> _viewSwitchPage({
|
||||
required LocalKey key,
|
||||
required Widget child,
|
||||
}) {
|
||||
return CustomTransitionPage<void>(
|
||||
key: key,
|
||||
opaque: false,
|
||||
transitionDuration: const Duration(milliseconds: 300),
|
||||
reverseTransitionDuration: const Duration(milliseconds: 250),
|
||||
child: child,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) {
|
||||
final curved = CurvedAnimation(
|
||||
parent: animation,
|
||||
curve: Curves.easeOut,
|
||||
reverseCurve: Curves.easeIn,
|
||||
);
|
||||
return FadeTransition(
|
||||
opacity: curved,
|
||||
child: SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: const Offset(0, 0.04),
|
||||
end: Offset.zero,
|
||||
).animate(curved),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class ShellWithNavBar extends StatelessWidget {
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(55, 16, 55, 12),
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
@@ -57,6 +57,11 @@ class ShellWithNavBar extends StatelessWidget {
|
||||
Majesticon.calendarSolid,
|
||||
Majesticon.calendarLine,
|
||||
),
|
||||
(
|
||||
initData.l10n.omissions,
|
||||
Majesticon.timerSolid,
|
||||
Majesticon.timerLine,
|
||||
),
|
||||
].indexed.map(
|
||||
(nav) => BottomNavIconWidget(
|
||||
() {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
|
||||
int resolveActiveAccountIndex(dynamic settings) {
|
||||
try {
|
||||
final dynamic profileSettings = settings.group("profile_settings");
|
||||
final dynamic accountPicker = profileSettings["e_kreta_account_picker"];
|
||||
final dynamic accountIndex = accountPicker.accountIndex;
|
||||
if (accountIndex is int && accountIndex >= 0) {
|
||||
return accountIndex;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
TokenModel? pickActiveToken({
|
||||
required List<TokenModel> tokens,
|
||||
required dynamic settings,
|
||||
int? preferredStudentIdNorm,
|
||||
}) {
|
||||
if (tokens.isEmpty) return null;
|
||||
|
||||
if (preferredStudentIdNorm != null) {
|
||||
for (final token in tokens) {
|
||||
if (token.studentIdNorm == preferredStudentIdNorm) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final accountIndex = resolveActiveAccountIndex(settings);
|
||||
if (accountIndex < tokens.length) {
|
||||
return tokens[accountIndex];
|
||||
}
|
||||
|
||||
return tokens.first;
|
||||
}
|
||||
43
firka/lib/services/fcm_headless_bootstrap.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/l10n/app_localizations_hu.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
|
||||
/// Minimal, isolate-local stand-in for `initializeApp()` (see
|
||||
/// `lib/app/initialization.dart`), used only by the FCM background message
|
||||
/// isolate. That isolate has none of the running app's in-memory state (it's
|
||||
/// a fresh Dart isolate, possibly a fresh process) — but `KretaClient` reads
|
||||
/// the global `initData` (for `userAgent`/`toastCubit`) unconditionally, so
|
||||
/// something has to populate it before a background wakeup can fetch data.
|
||||
///
|
||||
/// Deliberately skips everything UI/theming/watch-sync/live-activity
|
||||
/// related: those either don't apply headlessly or actively assume a
|
||||
/// running app (native platform channels registered on the main
|
||||
/// FlutterEngine, iCloud sync, etc). Idempotent per isolate — a warm
|
||||
/// background isolate handling multiple wakeups only bootstraps once.
|
||||
Future<void> bootstrapHeadless() async {
|
||||
if (initDone) return;
|
||||
|
||||
final isar = await initDB();
|
||||
final settings = SettingsRepository(isar);
|
||||
await settings.loadAll();
|
||||
|
||||
initData = AppInitialization(
|
||||
isar: isar,
|
||||
appDir: await getApplicationDocumentsDirectory(),
|
||||
// Real device info requires a MethodChannel handler that's only
|
||||
// registered on the main FlutterEngine; a placeholder is fine here,
|
||||
// it only affects the User-Agent header string.
|
||||
devInfo: DeviceInfo('background', '0', '0'),
|
||||
packageInfo: await PackageInfo.fromPlatform(),
|
||||
settings: settings,
|
||||
l10n: AppLocalizationsHu(),
|
||||
navigatorKey: GlobalKey<NavigatorState>(),
|
||||
);
|
||||
Settings = settings;
|
||||
initDone = true;
|
||||
}
|
||||
329
firka/lib/services/fcm_service.dart
Normal file
@@ -0,0 +1,329 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/api/client/notification_backend_client.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/firebase_options.dart';
|
||||
import 'package:firka/services/fcm_headless_bootstrap.dart';
|
||||
import 'package:firka/services/local_notification_service.dart';
|
||||
import 'package:firka/services/notification_diff_service.dart';
|
||||
|
||||
const _wakeupDataType = 'wakeup';
|
||||
const _hourlyTopic = 'wakeup-hourly';
|
||||
const _twoHourlyTopic = 'wakeup-2hourly';
|
||||
const _topicPrefix = '/topics/';
|
||||
|
||||
// Fixed id (outside the hash-derived range used by NotificationDiffService)
|
||||
// so the debug "message received" notification always updates in place.
|
||||
const _debugMessageNotificationId = 900001;
|
||||
|
||||
/// Must be a top-level function: FirebaseMessaging invokes it in its own
|
||||
/// background isolate, where none of firka's normal app state is set up.
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
|
||||
if (message.data['type'] == _wakeupDataType) {
|
||||
await NotificationDiffService.checkAll();
|
||||
} else {
|
||||
// checkAll() bootstraps Settings itself; other message types need it
|
||||
// bootstrapped explicitly before FcmService can read the debug toggle.
|
||||
await bootstrapHeadless();
|
||||
}
|
||||
|
||||
await FcmService._maybeShowDebugMessageNotification(message);
|
||||
}
|
||||
|
||||
/// Coordinates FCM push notification registration with firka's backend.
|
||||
/// Android-only for now: `flutterfire configure` has only been run for
|
||||
/// Android, so `DefaultFirebaseOptions.currentPlatform` throws on iOS. Once
|
||||
/// iOS is configured (re-run `flutterfire configure` with both platforms
|
||||
/// selected), drop the `Platform.isAndroid` guard in [initialize] to make
|
||||
/// this cross-platform like the rest of the service already assumes.
|
||||
/// Push is enabled by default; the master switch is SettingsRegistry.notifyAll,
|
||||
/// toggleable from the notifications settings page.
|
||||
class FcmService {
|
||||
static final Logger _logger = Logger('FcmService');
|
||||
static final NotificationBackendClient _backendClient =
|
||||
NotificationBackendClient();
|
||||
|
||||
static bool _isInitialized = false;
|
||||
static String? _cachedToken;
|
||||
static DateTime? _lastTokenRefreshAt;
|
||||
|
||||
/// Debug/status accessors for the developer settings screen.
|
||||
static bool get isInitialized => _isInitialized;
|
||||
static String? get cachedToken => _cachedToken;
|
||||
static DateTime? get lastTokenRefreshAt => _lastTokenRefreshAt;
|
||||
static String get subscribedTopic =>
|
||||
_topicFor(Settings.notifyWakeupInterval.value);
|
||||
|
||||
/// Current notification permission status, without prompting for it.
|
||||
/// Returns null if Firebase hasn't been initialized yet.
|
||||
static Future<AuthorizationStatus?> permissionStatus() async {
|
||||
if (!_isInitialized) return null;
|
||||
try {
|
||||
final settings = await FirebaseMessaging.instance.getNotificationSettings();
|
||||
return settings.authorizationStatus;
|
||||
} catch (e) {
|
||||
_logger.warning('Error reading notification permission status: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets up Firebase + the background handler and starts listening for
|
||||
/// token refreshes. Safe to call once at app startup, before login.
|
||||
static Future<void> initialize() async {
|
||||
if (_isInitialized) return;
|
||||
if (!Platform.isAndroid) return;
|
||||
|
||||
try {
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
|
||||
FirebaseMessaging.onBackgroundMessage(
|
||||
firebaseMessagingBackgroundHandler,
|
||||
);
|
||||
|
||||
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
|
||||
_cachedToken = token;
|
||||
_lastTokenRefreshAt = DateTime.now();
|
||||
_logger.info('FCM token refreshed');
|
||||
unawaited(_registerIfLoggedIn());
|
||||
});
|
||||
|
||||
// Data-only wakeups don't display anything on their own; if the app
|
||||
// happens to be foregrounded when one arrives, run the same
|
||||
// fetch+diff+notify pipeline as the background isolate does.
|
||||
FirebaseMessaging.onMessage.listen((message) {
|
||||
if (message.data['type'] == _wakeupDataType) {
|
||||
unawaited(NotificationDiffService.checkAll());
|
||||
}
|
||||
unawaited(_maybeShowDebugMessageNotification(message));
|
||||
});
|
||||
|
||||
_isInitialized = true;
|
||||
_logger.info('FcmService initialized');
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort label for which channel a message arrived on: the topic
|
||||
/// name for topic-targeted messages (FCM sets `from` to
|
||||
/// `/topics/<name>`), the `type` data field otherwise, or the raw
|
||||
/// sender id as a last resort.
|
||||
static String _channelLabel(RemoteMessage message) {
|
||||
final from = message.from;
|
||||
if (from != null && from.startsWith(_topicPrefix)) {
|
||||
return from.substring(_topicPrefix.length);
|
||||
}
|
||||
final type = message.data['type'];
|
||||
if (type != null) return type.toString();
|
||||
return from ?? 'unknown';
|
||||
}
|
||||
|
||||
static Future<void> _maybeShowDebugMessageNotification(
|
||||
RemoteMessage message,
|
||||
) async {
|
||||
if (!Settings.fcmDebugNotifyOnMessage.value) return;
|
||||
try {
|
||||
await LocalNotificationService.show(
|
||||
id: _debugMessageNotificationId,
|
||||
title: 'FCM message received',
|
||||
body: '${DateTime.now().toIso8601String()} - ${_channelLabel(message)}',
|
||||
);
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to show debug FCM message notification: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> _requestPermission() async {
|
||||
if (Platform.isIOS) {
|
||||
final settings = await FirebaseMessaging.instance.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
return settings.authorizationStatus == AuthorizationStatus.authorized ||
|
||||
settings.authorizationStatus == AuthorizationStatus.provisional;
|
||||
}
|
||||
|
||||
final status = await Permission.notification.status;
|
||||
if (status.isGranted) return true;
|
||||
final result = await Permission.notification.request();
|
||||
return result.isGranted;
|
||||
}
|
||||
|
||||
static String? _currentStudentId(KretaClient? client) {
|
||||
try {
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
return effectiveClient?.cache.token.username;
|
||||
} catch (e) {
|
||||
_logger.warning('Error reading current studentId: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _registerIfLoggedIn() async {
|
||||
final studentId = _currentStudentId(null);
|
||||
if (studentId == null) return;
|
||||
await _register(studentId: studentId);
|
||||
}
|
||||
|
||||
static String _topicFor(NotifyWakeupInterval interval) =>
|
||||
interval == NotifyWakeupInterval.hourly ? _hourlyTopic : _twoHourlyTopic;
|
||||
|
||||
/// Subscribes to the wakeup topic matching the user's chosen interval and
|
||||
/// unsubscribes from the other one, so only one cadence of pushes arrives.
|
||||
static Future<void> _subscribeToWakeupTopic() async {
|
||||
final topic = _topicFor(Settings.notifyWakeupInterval.value);
|
||||
final other = topic == _hourlyTopic ? _twoHourlyTopic : _hourlyTopic;
|
||||
await FirebaseMessaging.instance.subscribeToTopic(topic);
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(other);
|
||||
}
|
||||
|
||||
static Future<void> _unsubscribeFromWakeupTopics() async {
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(_hourlyTopic);
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(_twoHourlyTopic);
|
||||
}
|
||||
|
||||
/// Called from the notifyWakeupInterval settings effect when the user
|
||||
/// switches between hourly/2-hourly.
|
||||
static Future<void> handleWakeupIntervalChange() async {
|
||||
if (!_isInitialized || !Settings.notifyAll.value) return;
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
static Future<void> _register({required String studentId}) async {
|
||||
try {
|
||||
final token = _cachedToken ??= await FirebaseMessaging.instance.getToken();
|
||||
if (token == null) {
|
||||
_logger.warning('No FCM token available to register');
|
||||
return;
|
||||
}
|
||||
|
||||
await _backendClient.registerToken(
|
||||
fcmToken: token,
|
||||
studentId: studentId,
|
||||
notifyAll: Settings.notifyAll.value,
|
||||
notifyGrades: Settings.notifyGrades.value,
|
||||
notifyHomeworkTests: Settings.notifyHomeworkTests.value,
|
||||
notifyAbsences: Settings.notifyAbsences.value,
|
||||
notifyLessons: Settings.notifyLessons.value,
|
||||
notifyMessages: Settings.notifyMessages.value,
|
||||
);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to register FCM token: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// Called after a successful login (push is on by default, per
|
||||
/// SettingsRegistry.notifyAll's default value of true).
|
||||
static Future<void> onUserLogin({
|
||||
required KretaClient client,
|
||||
SettingsRepository? settingsStore,
|
||||
}) async {
|
||||
if (!_isInitialized) return;
|
||||
if (!Settings.notifyAll.value) {
|
||||
_logger.info('onUserLogin: push notifications disabled, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
final studentId = _currentStudentId(client);
|
||||
if (studentId == null) {
|
||||
_logger.warning('onUserLogin: no current user, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
final granted = await _requestPermission();
|
||||
if (!granted) {
|
||||
_logger.info('onUserLogin: notification permission not granted');
|
||||
return;
|
||||
}
|
||||
|
||||
await _register(studentId: studentId);
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
/// Called on logout: unregisters the current token from the backend.
|
||||
static Future<void> onUserLogout() async {
|
||||
await _unsubscribeFromWakeupTopics();
|
||||
|
||||
final token = _cachedToken;
|
||||
if (token == null) return;
|
||||
|
||||
try {
|
||||
await _backendClient.unregisterToken(fcmToken: token);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to unregister FCM token: $e', e, st);
|
||||
}
|
||||
_cachedToken = null;
|
||||
}
|
||||
|
||||
/// Called from the notifyAll settings effect when the master toggle changes.
|
||||
static Future<void> handleEnabledChange(bool enabled) async {
|
||||
if (!_isInitialized) return;
|
||||
|
||||
if (!enabled) {
|
||||
await _unsubscribeFromWakeupTopics();
|
||||
final token = _cachedToken;
|
||||
if (token != null) {
|
||||
try {
|
||||
await _backendClient.unregisterToken(fcmToken: token);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to unregister FCM token: $e', e, st);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final granted = await _requestPermission();
|
||||
if (!granted) {
|
||||
_logger.info('handleEnabledChange: notification permission not granted');
|
||||
return;
|
||||
}
|
||||
|
||||
final studentId = _currentStudentId(null);
|
||||
if (studentId == null) return;
|
||||
await _register(studentId: studentId);
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
/// Called when a category toggle (grades/homework/etc.) changes, to push
|
||||
/// the updated preferences to the backend for the already-registered token.
|
||||
static Future<void> updatePreferences() async {
|
||||
if (!_isInitialized || !Settings.notifyAll.value) return;
|
||||
final token = _cachedToken;
|
||||
if (token == null) return;
|
||||
|
||||
try {
|
||||
await _backendClient.updatePreferences(
|
||||
fcmToken: token,
|
||||
notifyAll: Settings.notifyAll.value,
|
||||
notifyGrades: Settings.notifyGrades.value,
|
||||
notifyHomeworkTests: Settings.notifyHomeworkTests.value,
|
||||
notifyAbsences: Settings.notifyAbsences.value,
|
||||
notifyLessons: Settings.notifyLessons.value,
|
||||
notifyMessages: Settings.notifyMessages.value,
|
||||
);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to update FCM notification preferences: $e', e, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,8 +242,7 @@ class LiveActivityManager {
|
||||
'nextRoomName': isBeforeSchool ? null : nextLesson?.roomName,
|
||||
'nextStartTime': nextStartTimeForActivity?.toUtc().toIso8601String(),
|
||||
'isSubstitution': currentLesson.substituteTeacher != null,
|
||||
'isCancelled':
|
||||
currentLesson.state.name?.toLowerCase().contains('elmarad') ?? false,
|
||||
'isCancelled': currentLesson.state.name.toLowerCase().contains('elmarad'),
|
||||
'substituteTeacher': currentLesson.substituteTeacher,
|
||||
'currentTime': now.toUtc().toIso8601String(),
|
||||
'mode': mode,
|
||||
|
||||
@@ -2,12 +2,11 @@ import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/api/client/live_activity_backend_client.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/services/live_activity_manager.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/ui/phone/screens/live_activity/live_activity_consent_screen.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -61,12 +60,12 @@ class LiveActivityService {
|
||||
static String? _getCurrentStudentId({KretaClient? client}) {
|
||||
try {
|
||||
if (client != null) {
|
||||
return client.model.studentId;
|
||||
return client.cache.token.username;
|
||||
}
|
||||
if (!initDone) {
|
||||
return null;
|
||||
}
|
||||
return initData.client.model.studentId;
|
||||
return initData.client!.cache.token.username;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting current studentId: $e');
|
||||
return null;
|
||||
@@ -216,17 +215,8 @@ class LiveActivityService {
|
||||
final userLiveActivityEnabled = await _getUserLiveActivityEnabled(
|
||||
client: client,
|
||||
);
|
||||
final globalLiveActivitySetting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("notifications")["live_activity_enabled"]
|
||||
as SettingsBoolean;
|
||||
|
||||
if (globalLiveActivitySetting.value != userLiveActivityEnabled) {
|
||||
globalLiveActivitySetting.value = userLiveActivityEnabled;
|
||||
await initData.isar.writeTxn(() async {
|
||||
await globalLiveActivitySetting.save(initData.isar.appSettingsModels);
|
||||
});
|
||||
if (Settings.liveActivityEnabled.value != userLiveActivityEnabled) {
|
||||
await Settings.liveActivityEnabled.setSilently(userLiveActivityEnabled);
|
||||
_logger.info(
|
||||
'Global LiveActivity setting synced: $userLiveActivityEnabled for user $studentId',
|
||||
);
|
||||
@@ -235,19 +225,10 @@ class LiveActivityService {
|
||||
final userMorningEnabled = await _getUserMorningNotificationEnabled(
|
||||
client: client,
|
||||
);
|
||||
final globalMorningEnabledSetting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("notifications")["morning_notification_enabled"]
|
||||
as SettingsBoolean;
|
||||
|
||||
if (globalMorningEnabledSetting.value != userMorningEnabled) {
|
||||
globalMorningEnabledSetting.value = userMorningEnabled;
|
||||
await initData.isar.writeTxn(() async {
|
||||
await globalMorningEnabledSetting.save(
|
||||
initData.isar.appSettingsModels,
|
||||
);
|
||||
});
|
||||
if (Settings.morningNotificationEnabled.value != userMorningEnabled) {
|
||||
await Settings.morningNotificationEnabled.setSilently(
|
||||
userMorningEnabled,
|
||||
);
|
||||
_logger.info(
|
||||
'Global morning notification enabled synced: $userMorningEnabled for user $studentId',
|
||||
);
|
||||
@@ -256,40 +237,24 @@ class LiveActivityService {
|
||||
final userMorningTime = await _getUserMorningNotificationTime(
|
||||
client: client,
|
||||
);
|
||||
final globalMorningTimeSetting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("notifications")["morning_notification_time"]
|
||||
as SettingsDouble;
|
||||
|
||||
if (globalMorningTimeSetting.value.toInt() != userMorningTime) {
|
||||
globalMorningTimeSetting.value = userMorningTime.toDouble();
|
||||
await initData.isar.writeTxn(() async {
|
||||
await globalMorningTimeSetting.save(initData.isar.appSettingsModels);
|
||||
});
|
||||
if (Settings.morningNotificationTime.value.toInt() != userMorningTime) {
|
||||
await Settings.morningNotificationTime.setSilently(
|
||||
userMorningTime.toDouble(),
|
||||
);
|
||||
_logger.info(
|
||||
'Global morning notification time synced: $userMorningTime for user $studentId',
|
||||
);
|
||||
}
|
||||
|
||||
final userBellDelay = await _getUserBellDelay(client: client);
|
||||
final globalBellDelaySetting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("application")["bell_delay"]
|
||||
as SettingsDouble;
|
||||
|
||||
if (globalBellDelaySetting.value != userBellDelay) {
|
||||
globalBellDelaySetting.value = userBellDelay;
|
||||
await initData.isar.writeTxn(() async {
|
||||
await globalBellDelaySetting.save(initData.isar.appSettingsModels);
|
||||
});
|
||||
if (Settings.bellDelay.value != userBellDelay) {
|
||||
await Settings.bellDelay.setSilently(userBellDelay);
|
||||
_logger.info(
|
||||
'Global bell delay synced: $userBellDelay for user $studentId',
|
||||
);
|
||||
}
|
||||
|
||||
initData.themeCubit?.refresh();
|
||||
initData.themeCubit.refresh();
|
||||
} catch (e) {
|
||||
_logger.warning('Error syncing global settings: $e');
|
||||
}
|
||||
@@ -302,22 +267,14 @@ class LiveActivityService {
|
||||
return 'hu';
|
||||
}
|
||||
|
||||
final languageSetting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("application")["language"]
|
||||
as SettingsItemsRadio?;
|
||||
|
||||
if (languageSetting == null) return 'hu';
|
||||
|
||||
switch (languageSetting.activeIndex) {
|
||||
case 1:
|
||||
switch (Settings.language.value) {
|
||||
case AppLanguage.hu:
|
||||
return 'hu';
|
||||
case 2:
|
||||
case AppLanguage.en:
|
||||
return 'en';
|
||||
case 3:
|
||||
case AppLanguage.de:
|
||||
return 'de';
|
||||
default: // auto
|
||||
case AppLanguage.auto:
|
||||
final systemLang = Platform.localeName.split('_').first;
|
||||
if (['hu', 'en', 'de'].contains(systemLang)) {
|
||||
return systemLang;
|
||||
@@ -444,7 +401,7 @@ class LiveActivityService {
|
||||
}
|
||||
|
||||
try {
|
||||
final client = initData.client;
|
||||
final client = initData.client!;
|
||||
|
||||
final enabled = await isEnabled(initData.settings, client);
|
||||
if (!enabled) {
|
||||
@@ -465,39 +422,23 @@ class LiveActivityService {
|
||||
_logger.info(
|
||||
'Background fetch: attempting to fetch fresh data from KRÉTA API',
|
||||
);
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
_logger.info(
|
||||
'Background fetch: successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
} else {
|
||||
throw Exception('KRÉTA API returned null response');
|
||||
}
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'Background fetch: successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.warning(
|
||||
'Background fetch: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'Background fetch: successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
_logger.info(
|
||||
'Background fetch: successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
} else {
|
||||
_logger.severe('Background fetch: both API and cache failed');
|
||||
return false;
|
||||
}
|
||||
} catch (cacheError) {
|
||||
_logger.severe(
|
||||
'Background fetch: cache fallback also failed: $cacheError',
|
||||
@@ -525,14 +466,10 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(candidateDay, candidateDayEnd);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -639,7 +576,7 @@ class LiveActivityService {
|
||||
|
||||
/// Check if LiveActivity is enabled in settings
|
||||
static Future<bool> isEnabled([
|
||||
SettingsStore? settingsStore,
|
||||
SettingsRepository? settingsStore,
|
||||
KretaClient? client,
|
||||
]) async {
|
||||
try {
|
||||
@@ -660,7 +597,7 @@ class LiveActivityService {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
try {
|
||||
final effectiveClient = client ?? initData.client;
|
||||
final effectiveClient = initData.client!;
|
||||
final studentId = _getCurrentStudentId(client: effectiveClient);
|
||||
if (studentId == null) {
|
||||
_logger.warning('Cannot change LiveActivity state: no current user');
|
||||
@@ -714,14 +651,9 @@ class LiveActivityService {
|
||||
);
|
||||
}
|
||||
|
||||
final studentResp = await effectiveClient.getStudent();
|
||||
final activeToken = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: effectiveClient.model.studentIdNorm,
|
||||
);
|
||||
final studentName =
|
||||
studentResp.response?.name ?? activeToken?.studentId ?? "Student";
|
||||
await effectiveClient.getStudent();
|
||||
final activeToken = initData.client!.cache.token;
|
||||
final studentName = activeToken.username;
|
||||
|
||||
await onUserLogin(
|
||||
client: effectiveClient,
|
||||
@@ -851,7 +783,7 @@ class LiveActivityService {
|
||||
static Future<void> onUserLogin({
|
||||
required KretaClient client,
|
||||
required String studentName,
|
||||
SettingsStore? settingsStore,
|
||||
SettingsRepository? settingsStore,
|
||||
}) async {
|
||||
_logger.info('onUserLogin: Function called for $studentName');
|
||||
|
||||
@@ -889,39 +821,23 @@ class LiveActivityService {
|
||||
_logger.info(
|
||||
'onUserLogin: Attempting to fetch fresh timetable from KRÉTA API',
|
||||
);
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
} else {
|
||||
throw Exception('KRÉTA API returned null response');
|
||||
}
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.warning(
|
||||
'onUserLogin: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
} else {
|
||||
_logger.severe('onUserLogin: Both API and cache failed');
|
||||
return;
|
||||
}
|
||||
} catch (cacheError) {
|
||||
_logger.severe(
|
||||
'onUserLogin: Cache fallback also failed: $cacheError',
|
||||
@@ -944,14 +860,10 @@ class LiveActivityService {
|
||||
|
||||
List<Lesson> nextWeekBreakEvents = [];
|
||||
try {
|
||||
final nextWeekResponse = await client.getTimeTable(
|
||||
nextWeekStart,
|
||||
nextWeekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(nextWeekStart, nextWeekEnd);
|
||||
|
||||
if (nextWeekResponse.response != null) {
|
||||
nextWeekBreakEvents = nextWeekResponse.response!.where((lesson) {
|
||||
if (true) {
|
||||
nextWeekBreakEvents = <Lesson>[].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -1049,14 +961,10 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(candidateDay, candidateDayEnd);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -1203,7 +1111,7 @@ class LiveActivityService {
|
||||
static Future<void> checkAndUpdateTimetable({
|
||||
required KretaClient client,
|
||||
required String studentName,
|
||||
SettingsStore? settingsStore,
|
||||
SettingsRepository? settingsStore,
|
||||
bool forceUpdate = false,
|
||||
}) async {
|
||||
if (!Platform.isIOS || !_isInitialized) return;
|
||||
@@ -1228,35 +1136,17 @@ class LiveActivityService {
|
||||
List<Lesson> allLessons = [];
|
||||
|
||||
try {
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
} else {
|
||||
throw Exception('KRÉTA API returned null response');
|
||||
}
|
||||
allLessons = List<Lesson>.from([]);
|
||||
} catch (e) {
|
||||
_logger.warning(
|
||||
'checkAndUpdateTimetable: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
} else {
|
||||
_logger.severe(
|
||||
'checkAndUpdateTimetable: Both API and cache failed',
|
||||
);
|
||||
return;
|
||||
}
|
||||
await client.getLessons(startOfWeek, endOfWeek);
|
||||
|
||||
allLessons = <Lesson>[];
|
||||
} catch (cacheError) {
|
||||
_logger.severe(
|
||||
'checkAndUpdateTimetable: Cache fallback also failed: $cacheError',
|
||||
@@ -1274,14 +1164,10 @@ class LiveActivityService {
|
||||
|
||||
List<Lesson> nextWeekBreakEvents = [];
|
||||
try {
|
||||
final nextWeekResponse = await client.getTimeTable(
|
||||
nextWeekStart,
|
||||
nextWeekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(nextWeekStart, nextWeekEnd);
|
||||
|
||||
if (nextWeekResponse.response != null) {
|
||||
nextWeekBreakEvents = nextWeekResponse.response!.where((lesson) {
|
||||
if (true) {
|
||||
nextWeekBreakEvents = <Lesson>[].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -1375,14 +1261,10 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(candidateDay, candidateDayEnd);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -1490,7 +1372,7 @@ class LiveActivityService {
|
||||
static Future<void> _startTimetableMonitoring({
|
||||
required KretaClient client,
|
||||
required String studentName,
|
||||
SettingsStore? settingsStore,
|
||||
SettingsRepository? settingsStore,
|
||||
}) async {
|
||||
_stopTimetableMonitoring();
|
||||
|
||||
@@ -1893,14 +1775,11 @@ class LiveActivityService {
|
||||
'Morning notifications re-enabled, fetching timetable to recreate notifications',
|
||||
);
|
||||
try {
|
||||
final client = initData.client;
|
||||
final client = initData.client!;
|
||||
final settingsStore = initData.settings;
|
||||
|
||||
final studentResp = await client.getStudent();
|
||||
final studentName =
|
||||
studentResp.response?.name ??
|
||||
client.model.studentId ??
|
||||
'Student';
|
||||
final studentName = studentResp.name;
|
||||
|
||||
await checkAndUpdateTimetable(
|
||||
client: client,
|
||||
@@ -1957,12 +1836,7 @@ class LiveActivityService {
|
||||
if (!initDone) {
|
||||
return null;
|
||||
}
|
||||
final setting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("notifications")["morning_notification_enabled"]
|
||||
as SettingsBoolean?;
|
||||
return setting?.value;
|
||||
return Settings.morningNotificationEnabled.value;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting current morning notification enabled: $e');
|
||||
return null;
|
||||
@@ -1975,12 +1849,7 @@ class LiveActivityService {
|
||||
if (!initDone) {
|
||||
return null;
|
||||
}
|
||||
final setting =
|
||||
initData.settings
|
||||
.group("settings")
|
||||
.subGroup("notifications")["morning_notification_time"]
|
||||
as SettingsDouble?;
|
||||
return setting?.value;
|
||||
return Settings.morningNotificationTime.value;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting current morning notification time: $e');
|
||||
return null;
|
||||
@@ -2014,16 +1883,10 @@ class LiveActivityService {
|
||||
);
|
||||
|
||||
try {
|
||||
final response = await client.getTimeTable(
|
||||
weekStart,
|
||||
weekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
await client.getLessons(weekStart, weekEnd);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final weekLessons = response.response!;
|
||||
|
||||
final breakEvents = weekLessons.where((lesson) {
|
||||
if (true) {
|
||||
final breakEvents = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -2035,26 +1898,26 @@ class LiveActivityService {
|
||||
name.contains('nem órarendi nap'));
|
||||
}).toList();
|
||||
|
||||
final schoolLessons = weekLessons.where((lesson) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
uid.contains('uresora');
|
||||
}).toList();
|
||||
|
||||
allLessons.addAll(weekLessons);
|
||||
allLessons.addAll([]);
|
||||
|
||||
if (breakEvents.isNotEmpty) {
|
||||
breakEvents.sort((a, b) => a.start.compareTo(b.start));
|
||||
lastBreakDay = breakEvents.last;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in week ${weeksSearched + 1}, last: ${lastBreakDay.name} on ${lastBreakDay.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in week ${weeksSearched + 1}, last: $lastBreakDay on $lastBreakDay',
|
||||
);
|
||||
} else if (schoolLessons.isNotEmpty) {
|
||||
schoolLessons.sort((a, b) => a.start.compareTo(b.start));
|
||||
firstSchoolDayAfterBreak = schoolLessons.first;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found first school day after break: ${firstSchoolDayAfterBreak.name} on ${firstSchoolDayAfterBreak.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found first school day after break: $firstSchoolDayAfterBreak on $firstSchoolDayAfterBreak',
|
||||
);
|
||||
break;
|
||||
} else {
|
||||
@@ -2062,10 +1925,6 @@ class LiveActivityService {
|
||||
'[GlobalBreakSearcher] Week ${weeksSearched + 1} is empty, continuing search...',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Week ${weeksSearched + 1} returned no data, continuing search...',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
final isTokenError =
|
||||
@@ -2084,15 +1943,10 @@ class LiveActivityService {
|
||||
}
|
||||
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
weekStart,
|
||||
weekEnd,
|
||||
forceCache: true,
|
||||
);
|
||||
await client.getLessons(weekStart, weekEnd);
|
||||
|
||||
if (cachedResponse.response != null &&
|
||||
cachedResponse.response!.isNotEmpty) {
|
||||
final weekLessons = cachedResponse.response!;
|
||||
if (true) {
|
||||
final weekLessons = [];
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Loaded ${weekLessons.length} lessons from cache for week ${weeksSearched + 1}',
|
||||
);
|
||||
@@ -2109,33 +1963,29 @@ class LiveActivityService {
|
||||
name.contains('nem órarendi nap'));
|
||||
}).toList();
|
||||
|
||||
final schoolLessons = weekLessons.where((lesson) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
uid.contains('uresora');
|
||||
}).toList();
|
||||
|
||||
allLessons.addAll(weekLessons);
|
||||
allLessons.addAll([]);
|
||||
|
||||
if (breakEvents.isNotEmpty) {
|
||||
breakEvents.sort((a, b) => a.start.compareTo(b.start));
|
||||
lastBreakDay = breakEvents.last;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in cached week ${weeksSearched + 1}, last: ${lastBreakDay.name} on ${lastBreakDay.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in cached week ${weeksSearched + 1}, last: $lastBreakDay on $lastBreakDay',
|
||||
);
|
||||
} else if (schoolLessons.isNotEmpty) {
|
||||
schoolLessons.sort((a, b) => a.start.compareTo(b.start));
|
||||
firstSchoolDayAfterBreak = schoolLessons.first;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found first school day after break in cache: ${firstSchoolDayAfterBreak.name} on ${firstSchoolDayAfterBreak.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found first school day after break in cache: $firstSchoolDayAfterBreak on $firstSchoolDayAfterBreak',
|
||||
);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] No cache available for week ${weeksSearched + 1}',
|
||||
);
|
||||
}
|
||||
} catch (cacheError) {
|
||||
_logger.warning(
|
||||
|
||||
67
firka/lib/services/local_notification_service.dart
Normal file
@@ -0,0 +1,67 @@
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
|
||||
/// Thin wrapper around flutter_local_notifications for showing the
|
||||
/// notifications posted by [NotificationDiffService] after a background FCM
|
||||
/// wakeup. Usable from both the main isolate and the headless background
|
||||
/// isolate (each needs its own [init] call — plugin state isn't shared
|
||||
/// across isolates).
|
||||
class LocalNotificationService {
|
||||
static const _channelId = 'firka_updates';
|
||||
static const _channelName = 'Firka frissítések';
|
||||
static const _channelDescription =
|
||||
'Új jegyek, házi feladatok, hiányzások és üzenetek értesítései.';
|
||||
|
||||
static final FlutterLocalNotificationsPlugin _plugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
static bool _initialized = false;
|
||||
|
||||
static Future<void> init() async {
|
||||
if (_initialized) return;
|
||||
|
||||
const androidInit = AndroidInitializationSettings('ic_notification');
|
||||
const iosInit = DarwinInitializationSettings();
|
||||
await _plugin.initialize(
|
||||
const InitializationSettings(android: androidInit, iOS: iosInit),
|
||||
);
|
||||
|
||||
const channel = AndroidNotificationChannel(
|
||||
_channelId,
|
||||
_channelName,
|
||||
description: _channelDescription,
|
||||
importance: Importance.defaultImportance,
|
||||
);
|
||||
await _plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.createNotificationChannel(channel);
|
||||
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/// Shows a single notification. [id] should be stable per logical
|
||||
/// notification (e.g. derived from account key + category) so a repeat
|
||||
/// wakeup that finds the same new items updates rather than duplicates it.
|
||||
static Future<void> show({
|
||||
required int id,
|
||||
required String title,
|
||||
required String body,
|
||||
}) async {
|
||||
await init();
|
||||
await _plugin.show(
|
||||
id,
|
||||
title,
|
||||
body,
|
||||
const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
_channelId,
|
||||
_channelName,
|
||||
channelDescription: _channelDescription,
|
||||
importance: Importance.defaultImportance,
|
||||
priority: Priority.defaultPriority,
|
||||
),
|
||||
iOS: DarwinNotificationDetails(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
339
firka/lib/services/notification_diff_service.dart
Normal file
@@ -0,0 +1,339 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/last_seen.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/core/last_seen_helper.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/fcm_headless_bootstrap.dart';
|
||||
import 'package:firka/services/local_notification_service.dart';
|
||||
|
||||
/// Runs on a silent FCM wakeup: for every locally logged-in account, fetches
|
||||
/// grades/homework/tests/absences/lessons/messages, diffs each against what
|
||||
/// was last seen by *this pipeline* (see LastSeenHelper's notif* kinds,
|
||||
/// which are deliberately separate from the UI's "opened" tracking), and
|
||||
/// shows a local notification per category with genuinely new items.
|
||||
class NotificationDiffService {
|
||||
static final Logger _logger = Logger('NotificationDiffService');
|
||||
|
||||
static Future<void> checkAll() async {
|
||||
await bootstrapHeadless();
|
||||
await LocalNotificationService.init();
|
||||
|
||||
if (!Settings.notifyAll.value) {
|
||||
_logger.info('checkAll: push disabled, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
final tokens = await isarInit.tokenModels.where().findAll();
|
||||
for (final token in tokens) {
|
||||
try {
|
||||
final client = KretaClient(token);
|
||||
await _checkAccount(client, token.key, token.username);
|
||||
} catch (e, st) {
|
||||
_logger.warning('checkAll: account ${token.username} failed: $e', e, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _checkAccount(
|
||||
KretaClient client,
|
||||
int accountKey,
|
||||
String username,
|
||||
) async {
|
||||
final mutedSubjects = _mutedSubjects();
|
||||
|
||||
if (Settings.notifyGrades.value) {
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifGrades,
|
||||
items: _excludeMuted(await client.getGrades(), mutedSubjects, (g) => g.subject.value?.name),
|
||||
title: (n) => n.length == 1 ? 'Új jegy érkezett' : '${n.length} új jegy érkezett',
|
||||
body: (n) => n
|
||||
.map((g) => '${g.subject.value?.name ?? "?"}: ${g.textValue} (${_fmtDate(g.writtenAt)})')
|
||||
.take(5)
|
||||
.join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifGrades),
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyHomeworkTests.value) {
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifHomework,
|
||||
items: _excludeMuted(await client.getHomework(), mutedSubjects, (h) => h.subject.value?.name),
|
||||
title: (n) => n.length == 1 ? 'Új házi feladat' : '${n.length} új házi feladat',
|
||||
body: (n) => n.map((h) => h.subject.value?.name ?? "?").take(5).join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifHomework),
|
||||
);
|
||||
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifTests,
|
||||
items: await client.getTests(),
|
||||
title: (n) => n.length == 1 ? 'Új témazáró/dolgozat' : '${n.length} új témazáró/dolgozat',
|
||||
body: (n) => n.map((t) => t.topic ?? t.method).take(5).join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifTests),
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyAbsences.value) {
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifAbsences,
|
||||
items: await client.getOmissions(),
|
||||
title: (n) => n.length == 1 ? 'Új hiányzás/késés' : '${n.length} új hiányzás/késés',
|
||||
body: (n) => n.map((o) => o.state.name).take(5).join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifAbsences),
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyLessons.value) {
|
||||
final now = DateTime.now();
|
||||
final lessons = await client.getLessons(now, now.add(const Duration(days: 7)));
|
||||
|
||||
final cancelled = lessons.where(_isCancelledLesson).toList();
|
||||
final substituted = lessons
|
||||
.where((l) => !_isCancelledLesson(l) && l.substituteTeacher != null)
|
||||
.toList();
|
||||
final otherChanges = lessons
|
||||
.where((l) => !_isCancelledLesson(l) && l.substituteTeacher == null)
|
||||
.toList();
|
||||
|
||||
// Split into three separately-diffed notifications instead of one lump
|
||||
// "schedule changed" — cancellations and substitutions carry which
|
||||
// teacher and (for cancellations) that Kréta doesn't give a free-text
|
||||
// reason, only the state label, so that's the most that's shown.
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifLessonsCancelled,
|
||||
items: cancelled,
|
||||
title: (n) => n.length == 1 ? 'Elmaradt óra' : '${n.length} elmaradt óra',
|
||||
body: (n) => n
|
||||
.map(
|
||||
(l) =>
|
||||
'${l.subject.value?.name ?? l.name} - ${l.teacher ?? "?"} '
|
||||
'(${_fmtDateTime(l.start)})',
|
||||
)
|
||||
.take(5)
|
||||
.join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifLessonsCancelled),
|
||||
);
|
||||
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifLessonsSubstituted,
|
||||
items: substituted,
|
||||
title: (n) => n.length == 1 ? 'Helyettesítés' : '${n.length} helyettesítés',
|
||||
body: (n) => n
|
||||
.map(
|
||||
(l) =>
|
||||
'${l.subject.value?.name ?? l.name}: ${l.teacher ?? "?"} -> '
|
||||
'${l.substituteTeacher} (${_fmtDateTime(l.start)})',
|
||||
)
|
||||
.take(5)
|
||||
.join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifLessonsSubstituted),
|
||||
);
|
||||
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifLessons,
|
||||
items: otherChanges,
|
||||
title: (n) => n.length == 1
|
||||
? 'Órarendváltozás'
|
||||
: '${n.length} órarendváltozás',
|
||||
body: (n) => n
|
||||
.map((l) => '${l.subject.value?.name ?? l.name} (${l.roomName ?? "?"})')
|
||||
.take(5)
|
||||
.join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifLessons),
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyMessages.value) {
|
||||
final combined = [
|
||||
...await client.getNoticeBoard(),
|
||||
...await client.getInfoBoard(),
|
||||
];
|
||||
await _diffAndNotify(
|
||||
accountKey: accountKey,
|
||||
kind: LastSeenHelper.notifMessages,
|
||||
items: combined,
|
||||
title: (n) => n.length == 1 ? 'Új üzenet' : '${n.length} új üzenet',
|
||||
body: (n) => n.map((m) => m.title).take(5).join(', '),
|
||||
notificationId: _notificationId(accountKey, LastSeenHelper.notifMessages),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Diffs [items] against the stored last-seen marker for (accountKey,
|
||||
/// kind). On the very first run for an account+kind there's no baseline
|
||||
/// yet, so it seeds one silently instead of notifying about the entire
|
||||
/// historical backlog.
|
||||
static Future<void> _diffAndNotify<T extends GenericCacheModel>({
|
||||
required int accountKey,
|
||||
required String kind,
|
||||
required List<T> items,
|
||||
required String Function(List<T> newItems) title,
|
||||
required String Function(List<T> newItems) body,
|
||||
required int notificationId,
|
||||
}) async {
|
||||
final seen = LastSeenHelper.get(accountKey, kind);
|
||||
|
||||
if (seen != null) {
|
||||
final newItems = LastSeen.newerThan(items, seen);
|
||||
if (newItems.isNotEmpty) {
|
||||
await LocalNotificationService.show(
|
||||
id: notificationId,
|
||||
title: title(newItems),
|
||||
body: body(newItems),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final newest = LastSeen.newestOf(items);
|
||||
if (newest != null) {
|
||||
await LastSeenHelper.set(accountKey, kind, newest);
|
||||
}
|
||||
}
|
||||
|
||||
/// Muted-subject filtering only applies where the model has a directly
|
||||
/// resolvable subject link populated during fetch (grades, homework).
|
||||
/// Tests/lessons/absences/messages don't carry a reliably-loaded subject
|
||||
/// reference at this point, so they're never muted by subject.
|
||||
static List<T> _excludeMuted<T>(
|
||||
List<T> items,
|
||||
Set<String> mutedSubjects,
|
||||
String? Function(T) subjectOf,
|
||||
) {
|
||||
if (mutedSubjects.isEmpty) return items;
|
||||
return items.where((i) => !mutedSubjects.contains(subjectOf(i))).toList();
|
||||
}
|
||||
|
||||
static Set<String> _mutedSubjects() {
|
||||
try {
|
||||
final decoded = jsonDecode(Settings.notifyMutedSubjects.value);
|
||||
if (decoded is List) return decoded.whereType<String>().toSet();
|
||||
} catch (_) {}
|
||||
return const {};
|
||||
}
|
||||
|
||||
static int _notificationId(int accountKey, String kind) =>
|
||||
Object.hash(accountKey, kind) & 0x7fffffff;
|
||||
|
||||
/// Matches the "isCancelled" convention already used across the app's
|
||||
/// live-activity/widget code (state names aren't a stable enum, just a
|
||||
/// Kréta-provided label; "elmarad" is the substring that consistently
|
||||
/// shows up for cancelled lessons across localizations seen so far).
|
||||
static bool _isCancelledLesson(LessonCacheModel l) =>
|
||||
l.state.toLowerCase().contains('elmarad');
|
||||
|
||||
static String _fmtDate(DateTime d) =>
|
||||
'${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
|
||||
|
||||
static String _fmtDateTime(DateTime d) =>
|
||||
'${_fmtDate(d)} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
|
||||
|
||||
/// Sample content per category for [showTestNotification]. `titleSingle`
|
||||
/// matches the wording `_checkAccount` uses for a lone new item on a
|
||||
/// single-account device; `titleMulti` drops the possessive so it reads
|
||||
/// naturally with a "(username)" suffix appended per account.
|
||||
static const _testContent = {
|
||||
LastSeenHelper.notifGrades: (
|
||||
titleSingle: 'Új jegyed érkezett',
|
||||
titleMulti: 'Új jegy érkezett',
|
||||
body: 'Matematika: 5 (2026-01-02)',
|
||||
),
|
||||
LastSeenHelper.notifHomework: (
|
||||
titleSingle: 'Új házi feladatod érkezett',
|
||||
titleMulti: 'Új házi feladat érkezett',
|
||||
body: 'Történelem: Olvasd el a 24. fejezetet (határidő: 2026-01-05)',
|
||||
),
|
||||
LastSeenHelper.notifTests: (
|
||||
titleSingle: 'Új témazáród/dolgozatod érkezett',
|
||||
titleMulti: 'Új témazáró/dolgozat érkezett',
|
||||
body: 'Fizika: Mechanika témazáró (2026-01-09 10:00)',
|
||||
),
|
||||
LastSeenHelper.notifAbsences: (
|
||||
titleSingle: 'Új hiányzásod/késésed érkezett',
|
||||
titleMulti: 'Új hiányzás/késés érkezett',
|
||||
body: 'Kémia: Igazolatlan hiányzás (2026-01-02 09:00)',
|
||||
),
|
||||
LastSeenHelper.notifLessons: (
|
||||
titleSingle: 'Órarendváltozás történt',
|
||||
titleMulti: 'Órarendváltozás történt',
|
||||
body: 'Kémia (A-002, 2026-01-06 12:00)',
|
||||
),
|
||||
LastSeenHelper.notifLessonsCancelled: (
|
||||
titleSingle: 'Elmaradt órád van',
|
||||
titleMulti: 'Elmaradt óra',
|
||||
body: 'Testnevelés - Nagy Béla (2026-01-06 12:00)',
|
||||
),
|
||||
LastSeenHelper.notifLessonsSubstituted: (
|
||||
titleSingle: 'Helyettesítés van az órarendedben',
|
||||
titleMulti: 'Helyettesítés',
|
||||
body: 'Kémia: Nagy Béla -> Kovács Anna (2026-01-06 09:50)',
|
||||
),
|
||||
LastSeenHelper.notifMessages: (
|
||||
titleSingle: 'Új üzeneted érkezett',
|
||||
titleMulti: 'Új üzenet érkezett',
|
||||
body: 'Nulladik óra átnevezése első órára - Müller Attila (2026-01-15 07:42)',
|
||||
),
|
||||
};
|
||||
|
||||
static const _simulatedUsernames = ['Gipsz Jakab', 'Kis Anna'];
|
||||
|
||||
/// Fires a local notification with placeholder content for [kind], for
|
||||
/// eyeballing what each category looks like on-device without needing
|
||||
/// real new data from the backend. Bypasses last-seen diffing entirely,
|
||||
/// so it always shows regardless of what's already been seen.
|
||||
///
|
||||
/// With a single account logged in (the common case), shows one
|
||||
/// notification with the personalized singular title. With more than one
|
||||
/// account, fires one per account instead, with the impersonal title
|
||||
/// suffixed by that account's username so they're distinguishable — this
|
||||
/// mirrors what a real multi-account wakeup would look like, since
|
||||
/// [checkAll] runs the diff separately per account. Pass
|
||||
/// [simulateMultiAccount] to preview that layout without needing a second
|
||||
/// account actually logged in on this device.
|
||||
static Future<void> showTestNotification(
|
||||
String kind, {
|
||||
bool simulateMultiAccount = false,
|
||||
}) async {
|
||||
final content = _testContent[kind];
|
||||
if (content == null) return;
|
||||
await LocalNotificationService.init();
|
||||
|
||||
final usernames = simulateMultiAccount
|
||||
? _simulatedUsernames
|
||||
: (await isarInit.tokenModels.where().findAll())
|
||||
.map((t) => t.username)
|
||||
.toList();
|
||||
|
||||
if (usernames.length <= 1) {
|
||||
await LocalNotificationService.show(
|
||||
id: _notificationId(0, kind),
|
||||
title: content.titleSingle,
|
||||
body: content.body,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; i < usernames.length; i++) {
|
||||
await LocalNotificationService.show(
|
||||
id: _notificationId(i + 1, kind),
|
||||
title: '${content.titleMulti} (${usernames[i]})',
|
||||
body: content.body,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
@@ -9,10 +10,9 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:watch_connectivity/watch_connectivity.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/services/wear_sync_cache.dart';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
|
||||
/// Helper class for Watch ↔ iPhone token sync (iOS) and Wear OS sync (Android).
|
||||
class WatchSyncHelper {
|
||||
@@ -60,42 +60,6 @@ class WatchSyncHelper {
|
||||
}
|
||||
}
|
||||
|
||||
static TokenModel? _resolveCurrentToken({
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) {
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
if (effectiveTokens == null || effectiveTokens.isEmpty) return null;
|
||||
|
||||
final preferredStudentIdNorm = client?.model.studentIdNorm;
|
||||
if (preferredStudentIdNorm != null) {
|
||||
for (final token in effectiveTokens) {
|
||||
if (token.studentIdNorm == preferredStudentIdNorm) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (initDone) {
|
||||
return pickActiveToken(
|
||||
tokens: effectiveTokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: preferredStudentIdNorm,
|
||||
);
|
||||
}
|
||||
|
||||
return effectiveTokens.first;
|
||||
}
|
||||
|
||||
static int? _resolveExpectedStudentIdNorm({
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) {
|
||||
final fromClient = client?.model.studentIdNorm;
|
||||
if (fromClient != null) return fromClient;
|
||||
return _resolveCurrentToken(tokens: tokens, client: client)?.studentIdNorm;
|
||||
}
|
||||
|
||||
static int? _asInt(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is double) return value.toInt();
|
||||
@@ -152,9 +116,6 @@ class WatchSyncHelper {
|
||||
required TokenModel currentToken,
|
||||
}) {
|
||||
final currentExpiry = currentToken.expiryDate;
|
||||
if (currentExpiry == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final incomingVersion =
|
||||
incomingTokenVersion ??
|
||||
@@ -196,7 +157,6 @@ class WatchSyncHelper {
|
||||
|
||||
final currentRefresh = currentToken.refreshToken;
|
||||
if (incomingRefreshToken != null &&
|
||||
currentRefresh != null &&
|
||||
incomingRefreshToken != currentRefresh) {
|
||||
if (incomingIdToken != null && incomingIdToken != currentToken.idToken) {
|
||||
return true;
|
||||
@@ -225,13 +185,13 @@ class WatchSyncHelper {
|
||||
? token.updatedAtMs!
|
||||
: nowMs;
|
||||
final payload = <String, dynamic>{
|
||||
'studentId': token.studentId,
|
||||
'studentIdNorm': token.studentIdNorm,
|
||||
'studentId': token.username,
|
||||
'studentIdNorm': token.key,
|
||||
'iss': token.iss,
|
||||
'idToken': token.idToken,
|
||||
'accessToken': token.accessToken,
|
||||
'refreshToken': token.refreshToken,
|
||||
'expiryDate': token.expiryDate!.millisecondsSinceEpoch,
|
||||
'expiryDate': token.expiryDate.millisecondsSinceEpoch,
|
||||
'tokenVersion': tokenVersion,
|
||||
'updatedAtMs': updatedAtMs,
|
||||
};
|
||||
@@ -448,10 +408,7 @@ class WatchSyncHelper {
|
||||
await isar.tokenModels.clear();
|
||||
});
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = [];
|
||||
}
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
if (initDone) initData.toastCubit.clear();
|
||||
|
||||
await prefs.setBool(_iosFreshInstallHandledKey, true);
|
||||
return true;
|
||||
@@ -523,7 +480,6 @@ class WatchSyncHelper {
|
||||
try {
|
||||
final recovered = await checkAndRecoverFromiCloud(
|
||||
isar: initData.isar,
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
|
||||
@@ -532,13 +488,10 @@ class WatchSyncHelper {
|
||||
'[WatchSync] Token recovered from iCloud, reauth flag cleared',
|
||||
);
|
||||
} else {
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
final expiryDate = token?.expiryDate;
|
||||
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
final token = initData.client!.cache.token;
|
||||
final expiryDate = token.expiryDate;
|
||||
if (expiryDate.isAfter(DateTime.now())) {
|
||||
if (initDone) initData.toastCubit.clear();
|
||||
debugPrint(
|
||||
'[WatchSync] Cleared reauth flag after iCloud notification (token is valid)',
|
||||
);
|
||||
@@ -550,28 +503,14 @@ class WatchSyncHelper {
|
||||
}
|
||||
|
||||
static Map<String, dynamic>? _getTokenForWatch() {
|
||||
if (!initDone || initData.tokens.isEmpty) {
|
||||
if (!initDone) {
|
||||
debugPrint('[WatchSync] No token available');
|
||||
return {'error': 'no_token'};
|
||||
}
|
||||
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
if (token == null) {
|
||||
debugPrint('[WatchSync] No active token available');
|
||||
return {'error': 'no_token'};
|
||||
}
|
||||
final token = initData.client!.cache.token;
|
||||
|
||||
if (token.accessToken == null ||
|
||||
token.refreshToken == null ||
|
||||
token.expiryDate == null) {
|
||||
debugPrint('[WatchSync] Token incomplete');
|
||||
return {'error': 'token_incomplete'};
|
||||
}
|
||||
|
||||
if (initData.client.needsReauth) {
|
||||
if (initData.client!.needsReauth) {
|
||||
debugPrint('[WatchSync] iPhone needs reauth');
|
||||
return {'error': 'needsReauth'};
|
||||
}
|
||||
@@ -730,14 +669,8 @@ class WatchSyncHelper {
|
||||
return {'success': false, 'error': 'no_student_id_norm'};
|
||||
}
|
||||
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
final currentToken = initData.client!.cache.token;
|
||||
|
||||
final watchExpiryDate = DateTime.fromMillisecondsSinceEpoch(watchExpiry);
|
||||
if (!_isAccessTokenUsable(watchExpiryDate, skew: const Duration())) {
|
||||
@@ -751,12 +684,8 @@ class WatchSyncHelper {
|
||||
final watchIdToken = tokenData['idToken'] as String?;
|
||||
final watchRefreshToken = tokenData['refreshToken'] as String?;
|
||||
|
||||
final isForActiveAccount =
|
||||
expectedStudentIdNorm == null ||
|
||||
watchStudentIdNorm == expectedStudentIdNorm;
|
||||
if (isForActiveAccount &&
|
||||
currentToken != null &&
|
||||
currentToken.studentIdNorm == watchStudentIdNorm) {
|
||||
final isForActiveAccount = watchStudentIdNorm == expectedStudentIdNorm;
|
||||
if (isForActiveAccount && currentToken.key == watchStudentIdNorm) {
|
||||
if (!_isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: watchExpiryDate,
|
||||
incomingIdToken: watchIdToken,
|
||||
@@ -792,10 +721,9 @@ class WatchSyncHelper {
|
||||
await initData.isar.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
initData.tokens = await initData.isar.tokenModels.where().findAll();
|
||||
if (isForActiveAccount) {
|
||||
initData.client.model = newToken;
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
initData.client!.cache.token = newToken;
|
||||
if (initDone) initData.toastCubit.clear();
|
||||
} else {
|
||||
debugPrint(
|
||||
'[WatchSync] Stored token for inactive account ($watchStudentIdNorm), active is $expectedStudentIdNorm',
|
||||
@@ -821,13 +749,6 @@ class WatchSyncHelper {
|
||||
return;
|
||||
}
|
||||
|
||||
if (token.accessToken == null ||
|
||||
token.refreshToken == null ||
|
||||
token.expiryDate == null) {
|
||||
debugPrint('[WatchSync] Token incomplete, not sending to Watch');
|
||||
return;
|
||||
}
|
||||
|
||||
final accessExpired = !_isAccessTokenUsable(
|
||||
token.expiryDate,
|
||||
skew: const Duration(),
|
||||
@@ -894,7 +815,6 @@ class WatchSyncHelper {
|
||||
}
|
||||
|
||||
final effectiveIsar = isar ?? (initDone ? initData.isar : null);
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
|
||||
if (effectiveIsar == null) {
|
||||
@@ -921,14 +841,10 @@ class WatchSyncHelper {
|
||||
return false;
|
||||
}
|
||||
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
|
||||
final iCloudStudentIdNorm = tokenData['studentIdNorm'] as int?;
|
||||
if (expectedStudentIdNorm != null &&
|
||||
iCloudStudentIdNorm != expectedStudentIdNorm) {
|
||||
if (iCloudStudentIdNorm != expectedStudentIdNorm) {
|
||||
debugPrint(
|
||||
'[WatchSync] iCloud token belongs to different account ($iCloudStudentIdNorm), active is $expectedStudentIdNorm - ignoring',
|
||||
);
|
||||
@@ -959,21 +875,16 @@ class WatchSyncHelper {
|
||||
final iCloudIdToken = tokenData['idToken'] as String?;
|
||||
final iCloudRefreshToken = tokenData['refreshToken'] as String?;
|
||||
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
final currentToken = initData.client!.cache.token;
|
||||
final localExpiry = currentToken.expiryDate;
|
||||
final shouldAccept = _isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: iCloudExpiryDate,
|
||||
incomingIdToken: iCloudIdToken,
|
||||
incomingRefreshToken: iCloudRefreshToken,
|
||||
incomingTokenVersion: iCloudTokenVersion,
|
||||
incomingUpdatedAtMs: iCloudUpdatedAtMs,
|
||||
currentToken: currentToken,
|
||||
);
|
||||
final localExpiry = currentToken?.expiryDate;
|
||||
final shouldAccept = currentToken == null
|
||||
? true
|
||||
: _isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: iCloudExpiryDate,
|
||||
incomingIdToken: iCloudIdToken,
|
||||
incomingRefreshToken: iCloudRefreshToken,
|
||||
incomingTokenVersion: iCloudTokenVersion,
|
||||
incomingUpdatedAtMs: iCloudUpdatedAtMs,
|
||||
currentToken: currentToken,
|
||||
);
|
||||
|
||||
if (shouldAccept) {
|
||||
debugPrint(
|
||||
@@ -997,24 +908,14 @@ class WatchSyncHelper {
|
||||
await effectiveIsar.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
final updatedTokens = await effectiveIsar.tokenModels.where().findAll();
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = updatedTokens;
|
||||
}
|
||||
|
||||
if (effectiveClient != null &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm)) {
|
||||
effectiveClient.model = newToken;
|
||||
if (effectiveClient != null && newToken.key == expectedStudentIdNorm) {
|
||||
effectiveClient.cache.token = newToken;
|
||||
}
|
||||
|
||||
final shouldClearReauth =
|
||||
!iCloudAccessExpired &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm);
|
||||
!iCloudAccessExpired && newToken.key == expectedStudentIdNorm;
|
||||
if (shouldClearReauth) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
if (initDone) initData.toastCubit.clear();
|
||||
}
|
||||
|
||||
debugPrint(
|
||||
@@ -1040,13 +941,6 @@ class WatchSyncHelper {
|
||||
}) async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
if (token.accessToken == null ||
|
||||
token.refreshToken == null ||
|
||||
token.expiryDate == null) {
|
||||
debugPrint('[WatchSync] Token incomplete, not saving to iCloud');
|
||||
return;
|
||||
}
|
||||
|
||||
final watchInstalled = await isWatchAppInstalled();
|
||||
if (!watchInstalled) {
|
||||
debugPrint(
|
||||
@@ -1071,16 +965,7 @@ class WatchSyncHelper {
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
final effectiveIsar = isar ?? (initDone ? initData.isar : null);
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
|
||||
if (effectiveIsar == null || effectiveTokens == null) {
|
||||
debugPrint('[WatchSync] Cannot sync: no isar or tokens available');
|
||||
return;
|
||||
}
|
||||
if (!Platform.isIOS || !initDone) return;
|
||||
|
||||
try {
|
||||
debugPrint('[WatchSync] Requesting token from Watch...');
|
||||
@@ -1089,22 +974,12 @@ class WatchSyncHelper {
|
||||
null,
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
final currentToken = initData.client!.cache.token;
|
||||
|
||||
if (result == null) {
|
||||
debugPrint('[WatchSync] No response from Watch');
|
||||
if (currentToken != null &&
|
||||
currentToken.accessToken != null &&
|
||||
currentToken.refreshToken != null &&
|
||||
currentToken.expiryDate != null &&
|
||||
!(initData.reauthCubit?.state.needsReauth ?? false)) {
|
||||
if (!initData.client!.needsReauth) {
|
||||
debugPrint('[WatchSync] Sending iPhone token to Watch (no response)');
|
||||
await _sendTokenToWatchInternal(
|
||||
currentToken,
|
||||
@@ -1117,11 +992,7 @@ class WatchSyncHelper {
|
||||
final tokenData = result as Map<dynamic, dynamic>;
|
||||
if (tokenData.containsKey('error')) {
|
||||
debugPrint('[WatchSync] Watch returned error: ${tokenData['error']}');
|
||||
if (currentToken != null &&
|
||||
currentToken.accessToken != null &&
|
||||
currentToken.refreshToken != null &&
|
||||
currentToken.expiryDate != null &&
|
||||
!(initData.reauthCubit?.state.needsReauth ?? false)) {
|
||||
if (!initData.client!.needsReauth) {
|
||||
debugPrint(
|
||||
'[WatchSync] Sending iPhone token to Watch (Watch has no token)',
|
||||
);
|
||||
@@ -1145,16 +1016,11 @@ class WatchSyncHelper {
|
||||
return;
|
||||
}
|
||||
|
||||
if (expectedStudentIdNorm != null &&
|
||||
watchStudentIdNorm != expectedStudentIdNorm) {
|
||||
if (watchStudentIdNorm != expectedStudentIdNorm) {
|
||||
debugPrint(
|
||||
'[WatchSync] Watch token belongs to different account ($watchStudentIdNorm), active is $expectedStudentIdNorm - keeping active account',
|
||||
);
|
||||
if (currentToken != null &&
|
||||
currentToken.accessToken != null &&
|
||||
currentToken.refreshToken != null &&
|
||||
currentToken.expiryDate != null &&
|
||||
!(initData.reauthCubit?.state.needsReauth ?? false)) {
|
||||
if (!(initData.client!.needsReauth)) {
|
||||
await _sendTokenToWatchInternal(
|
||||
currentToken,
|
||||
allowExpiredAccessToken: true,
|
||||
@@ -1168,15 +1034,11 @@ class WatchSyncHelper {
|
||||
debugPrint(
|
||||
'[WatchSync] Watch provided expired token, ignoring and keeping iPhone token',
|
||||
);
|
||||
if (currentToken != null &&
|
||||
currentToken.accessToken != null &&
|
||||
currentToken.refreshToken != null &&
|
||||
currentToken.expiryDate != null &&
|
||||
_isAccessTokenUsable(
|
||||
if (_isAccessTokenUsable(
|
||||
currentToken.expiryDate,
|
||||
skew: const Duration(),
|
||||
) &&
|
||||
!(initData.reauthCubit?.state.needsReauth ?? false)) {
|
||||
!initData.client!.needsReauth) {
|
||||
await _sendTokenToWatchInternal(
|
||||
currentToken,
|
||||
allowExpiredAccessToken: true,
|
||||
@@ -1188,16 +1050,14 @@ class WatchSyncHelper {
|
||||
final watchUpdatedAtMs = _asInt(tokenData['updatedAtMs']);
|
||||
final watchIdToken = tokenData['idToken'] as String?;
|
||||
final watchRefreshToken = tokenData['refreshToken'] as String?;
|
||||
final shouldAccept = currentToken == null
|
||||
? true
|
||||
: _isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: watchExpiryDate,
|
||||
incomingIdToken: watchIdToken,
|
||||
incomingRefreshToken: watchRefreshToken,
|
||||
incomingTokenVersion: watchTokenVersion,
|
||||
incomingUpdatedAtMs: watchUpdatedAtMs,
|
||||
currentToken: currentToken,
|
||||
);
|
||||
final shouldAccept = _isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: watchExpiryDate,
|
||||
incomingIdToken: watchIdToken,
|
||||
incomingRefreshToken: watchRefreshToken,
|
||||
incomingTokenVersion: watchTokenVersion,
|
||||
incomingUpdatedAtMs: watchUpdatedAtMs,
|
||||
currentToken: currentToken,
|
||||
);
|
||||
if (shouldAccept) {
|
||||
debugPrint('[WatchSync] Watch has newer token, updating iPhone');
|
||||
final newToken = TokenModel.fromValues(
|
||||
@@ -1213,25 +1073,14 @@ class WatchSyncHelper {
|
||||
watchUpdatedAtMs ?? DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
|
||||
await effectiveIsar.writeTxn(() async {
|
||||
await effectiveIsar.tokenModels.put(newToken);
|
||||
await isarInit.writeTxn(() async {
|
||||
await isarInit.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
final updatedTokens = await effectiveIsar.tokenModels.where().findAll();
|
||||
initData.client!.cache.token = newToken;
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = updatedTokens;
|
||||
}
|
||||
|
||||
if (effectiveClient != null &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm)) {
|
||||
effectiveClient.model = newToken;
|
||||
}
|
||||
|
||||
if (expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
if (newToken.key == expectedStudentIdNorm) {
|
||||
if (initDone) initData.toastCubit.clear();
|
||||
}
|
||||
|
||||
debugPrint(
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:watch_connectivity/watch_connectivity.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.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_common/data/models/token_model.dart';
|
||||
import 'package:firka/services/wear_sync_cache.dart';
|
||||
|
||||
/// Background isolate entrypoint for Wear sync (Android).
|
||||
@@ -29,30 +25,12 @@ void wearSyncBackgroundEntrypoint() {
|
||||
final appDirPath = args?['appDirPath'] as String?;
|
||||
if (cachePath == null || appDirPath == null) return null;
|
||||
try {
|
||||
final isar = await Isar.open([
|
||||
TokenModelSchema,
|
||||
GenericCacheModelSchema,
|
||||
TimetableCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
HomeworkDoneModelSchema,
|
||||
], directory: appDirPath);
|
||||
final tokens = await isar.tokenModels.where().findAll();
|
||||
await isar.close();
|
||||
await initDB();
|
||||
final tokens = await isarInit.tokenModels.where().findAll();
|
||||
if (tokens.isEmpty) return null;
|
||||
final token = tokens.first;
|
||||
final isar2 = await Isar.open([
|
||||
TokenModelSchema,
|
||||
GenericCacheModelSchema,
|
||||
TimetableCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
HomeworkDoneModelSchema,
|
||||
], directory: appDirPath);
|
||||
final reauthCubit = ReauthCubit();
|
||||
final client = KretaClient(token, isar2, reauthCubit);
|
||||
final client = KretaClient(token);
|
||||
final payload = await buildWearSyncPayload(client);
|
||||
await isar2.close();
|
||||
if (payload == null) return null;
|
||||
await writeWearSyncCache(cachePath, payload);
|
||||
final wc = WatchConnectivity();
|
||||
|
||||
@@ -28,25 +28,11 @@ const String wearSyncCacheFileName = 'wear_sync_cache.json';
|
||||
/// Builds the sync payload (same shape as init_data / sync_data): timetable (2 weeks), grades, lastSyncAt.
|
||||
Future<Map<String, dynamic>?> buildWearSyncPayload(KretaClient client) async {
|
||||
final (start, end) = getWearSyncTimetableRange();
|
||||
final timetableResp = await client.getTimeTable(
|
||||
start,
|
||||
end,
|
||||
forceCache: false,
|
||||
);
|
||||
if (timetableResp.err != null && timetableResp.response == null) {
|
||||
return null;
|
||||
}
|
||||
final gradesResp = await client.getGrades(forceCache: false);
|
||||
if (gradesResp.err != null && gradesResp.response == null) {
|
||||
return null;
|
||||
}
|
||||
await client.getLessons(start, end);
|
||||
await client.getGrades();
|
||||
final now = timeNow();
|
||||
final timetable = (timetableResp.response ?? <Lesson>[])
|
||||
.map((l) => l.toJson())
|
||||
.toList();
|
||||
final grades = (gradesResp.response ?? <Grade>[])
|
||||
.map((g) => g.toJson())
|
||||
.toList();
|
||||
final timetable = (<Lesson>[]).map((l) => l.toJson()).toList();
|
||||
final grades = (<Grade>[]).map((g) => g.toJson()).toList();
|
||||
return {
|
||||
'lastSyncAt': now.toUtc().toIso8601String(),
|
||||
'timetable': timetable,
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka/ui/phone/widgets/info_card.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:firka_common/ui/shared/grade_small_card.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_html/flutter_html.dart';
|
||||
@@ -19,9 +27,8 @@ import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/grade.dart';
|
||||
|
||||
Future<void> showFirkaBottomSheet(
|
||||
BuildContext context,
|
||||
@@ -45,28 +52,30 @@ Future<void> showFirkaBottomSheet(
|
||||
color: appStyle.colors.background,
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Align(
|
||||
heightFactor: 0,
|
||||
alignment: Alignment.topCenter,
|
||||
child: Container(
|
||||
margin: EdgeInsets.only(top: 18),
|
||||
width: 40,
|
||||
height: 4,
|
||||
foregroundDecoration: ShapeDecoration(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadiusGeometry.circular(2),
|
||||
child: SelectionArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Align(
|
||||
heightFactor: 0,
|
||||
alignment: Alignment.topCenter,
|
||||
child: Container(
|
||||
margin: EdgeInsets.only(top: 18),
|
||||
width: 40,
|
||||
height: 4,
|
||||
foregroundDecoration: ShapeDecoration(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadiusGeometry.circular(2),
|
||||
),
|
||||
color: appStyle.colors.shadowColor,
|
||||
),
|
||||
color: appStyle.colors.shadowColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 40),
|
||||
...children,
|
||||
],
|
||||
SizedBox(height: 40),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -78,16 +87,14 @@ Future<void> showFirkaBottomSheet(
|
||||
Future<void> showLessonBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Lesson lesson,
|
||||
LessonCacheModel lesson,
|
||||
Color accent,
|
||||
Color secondary,
|
||||
Color bgColor,
|
||||
Test? test,
|
||||
) async {
|
||||
final statsForNerdsEnabled = data.settings
|
||||
.group("settings")
|
||||
.subGroup("developer")
|
||||
.boolean("stats_for_nerds");
|
||||
// we dont like events
|
||||
assert(lesson.type != TimetableConsts.event);
|
||||
final statsForNerdsEnabled = Settings.statsForNerds.value;
|
||||
|
||||
Widget? statsForNerds;
|
||||
|
||||
@@ -96,8 +103,8 @@ Future<void> showLessonBottomSheet(
|
||||
if (statsForNerdsEnabled) {
|
||||
final stats =
|
||||
"${data.l10n.stats_date}: ${lesson.start.isAfter(y2k) ? lesson.start.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n"
|
||||
"${data.l10n.stats_created_at}: ${lesson.createdAt.isAfter(y2k) ? lesson.createdAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n"
|
||||
"${data.l10n.stats_last_mod}: ${lesson.lastModifiedAt.isAfter(y2k) ? lesson.lastModifiedAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}";
|
||||
"${data.l10n.stats_created_at}: ${lesson.createdAt.isAfter(y2k) ? lesson.createdAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n";
|
||||
//"${data.l10n.stats_last_mod}: ${lesson.lastModifiedAt.isAfter(y2k) ? lesson.lastModifiedAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}";
|
||||
statsForNerds = Text(
|
||||
stats,
|
||||
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
|
||||
@@ -106,65 +113,62 @@ Future<void> showLessonBottomSheet(
|
||||
showFirkaBottomSheet(context, [
|
||||
Row(
|
||||
children: [
|
||||
lesson.lessonNumber == null
|
||||
? SizedBox()
|
||||
: SizedBox(
|
||||
SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/icons/subtract.svg",
|
||||
color: bgColor,
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/icons/subtract.svg",
|
||||
color: bgColor,
|
||||
width: 24,
|
||||
height: 24,
|
||||
),
|
||||
Text(
|
||||
lesson.lessonNumber!.toString(),
|
||||
style: appStyle.fonts.B_16R.apply(color: secondary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_16R.apply(color: secondary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledCircle(
|
||||
diameter: 40,
|
||||
color: bgColor,
|
||||
child: ClassIconWidget.subject(
|
||||
subject: lesson.subject!,
|
||||
child: ClassIconWidget(
|
||||
subject: lesson.subject.loadAndGet()!,
|
||||
color: accent,
|
||||
size: 26,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
if (lesson.roomName != null)
|
||||
Card(
|
||||
shadowColor: Colors.transparent,
|
||||
color: appStyle.colors.a15p,
|
||||
margin: EdgeInsets.all(0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
lesson.roomName!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
Card(
|
||||
shadowColor: Colors.transparent,
|
||||
color: appStyle.colors.a15p,
|
||||
margin: EdgeInsets.all(0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
lesson.roomName!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
"${lesson.name} ${statsForNerdsEnabled ? "(${lesson.classGroup?.name ?? ''})" : ""}",
|
||||
"${lesson.name} ${statsForNerdsEnabled ? "(${lesson.subject.loadAndGet()!.name})" : ""}",
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -173,7 +177,7 @@ Future<void> showLessonBottomSheet(
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
lesson.teacher ?? 'N/A',
|
||||
lesson.teacher!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
decoration: lesson.substituteTeacher != null
|
||||
@@ -208,7 +212,7 @@ Future<void> showLessonBottomSheet(
|
||||
SizedBox(
|
||||
width: MediaQuery.of(context).size.width * 0.7,
|
||||
child: Text(
|
||||
lesson.theme ?? 'N/A',
|
||||
lesson.topic ?? 'N/A',
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -222,7 +226,8 @@ Future<void> showLessonBottomSheet(
|
||||
],
|
||||
),
|
||||
SizedBox(height: 6),
|
||||
if (test != null) InfoCard.testDesc(test),
|
||||
if (lesson.test.loadAndGet() != null)
|
||||
InfoCard.testDesc(lesson.test.loadAndGet()!),
|
||||
SizedBox(height: 16),
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
@@ -245,12 +250,47 @@ Future<void> showLessonBottomSheet(
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> showOmissionBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
String description,
|
||||
List<OmissionCacheModel> omissions,
|
||||
) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
Text(
|
||||
omissions.first.createdAt.format(data.l10n, FormatMode.yyyymmdd),
|
||||
style: appStyle.fonts.H_18px.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
description,
|
||||
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textSecondary),
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
LimitedBox(
|
||||
maxHeight: 336,
|
||||
child: ListView.separated(
|
||||
itemCount: omissions.length,
|
||||
separatorBuilder: (ctx, i) {
|
||||
return const SizedBox(height: 10);
|
||||
},
|
||||
itemBuilder: (b, i) {
|
||||
final o = omissions[i];
|
||||
return LessonWidget(data, o.lesson.loadAndGet()!);
|
||||
},
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> showTestBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Test test,
|
||||
TestCacheModel test,
|
||||
) async {
|
||||
final date = test.date;
|
||||
final lesson = test.lesson.loadAndGet()!;
|
||||
final subject = lesson.subject.loadAndGet()!;
|
||||
final date = lesson.start;
|
||||
final formattedDate =
|
||||
"${date.format(data.l10n, FormatMode.yearly).firstUpper()}, ${DateFormat.EEEE(data.l10n.localeName).format(date).firstUpper()}";
|
||||
|
||||
@@ -272,13 +312,13 @@ Future<void> showTestBottomSheet(
|
||||
spacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
"${test.theme}",
|
||||
test.topic ?? test.method,
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
test.method.description,
|
||||
test.method,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -325,7 +365,7 @@ Future<void> showTestBottomSheet(
|
||||
height: 18,
|
||||
),
|
||||
Text(
|
||||
test.lessonNumber.toString(),
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
@@ -338,9 +378,7 @@ Future<void> showTestBottomSheet(
|
||||
diameter: 36,
|
||||
color: appStyle.colors.a15p,
|
||||
child: ClassIconWidget(
|
||||
uid: test.uid,
|
||||
className: test.subjectName,
|
||||
category: test.subject.name,
|
||||
subject: subject,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
),
|
||||
@@ -348,7 +386,7 @@ Future<void> showTestBottomSheet(
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
test.subject.name,
|
||||
subject.name,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -364,7 +402,7 @@ Future<void> showTestBottomSheet(
|
||||
Future<void> showGradeBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Grade grade,
|
||||
GradeCacheModel grade,
|
||||
) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
grade.numericValue == null
|
||||
@@ -381,7 +419,7 @@ Future<void> showGradeBottomSheet(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
grade.strValue,
|
||||
grade.textValue,
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
@@ -392,12 +430,12 @@ Future<void> showGradeBottomSheet(
|
||||
: GradeWidget(grade, size: 40),
|
||||
SizedBox(height: 20),
|
||||
Text(
|
||||
(grade.topic ?? grade.type.description).firstUpper(),
|
||||
(grade.topic ?? grade.type).firstUpper(),
|
||||
style: appStyle.fonts.H_18px.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
grade.mode != null
|
||||
? Text(
|
||||
grade.mode!.description,
|
||||
grade.mode!,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -405,11 +443,11 @@ Future<void> showGradeBottomSheet(
|
||||
: SizedBox(),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
grade.recordDate.format(data.l10n, FormatMode.yyyymmdd),
|
||||
grade.writtenAt.format(data.l10n, FormatMode.yyyymmdd),
|
||||
style: appStyle.fonts.B_14R.apply(color: appStyle.colors.textSecondary),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeSmallCard([], null, grade.subject),
|
||||
GradeSmallCard(null, null, grade.subject.loadAndGet()!),
|
||||
SizedBox(height: 10),
|
||||
FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
@@ -418,13 +456,13 @@ Future<void> showGradeBottomSheet(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
"${data.l10n.grade_teacherName}${grade.teacher}",
|
||||
"${data.l10n.grade_teacherName}${grade.teacherName}",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${data.l10n.tt_added}${grade.creationDate.format(data.l10n, FormatMode.yyyymmdd)}",
|
||||
"${data.l10n.tt_added}${grade.createdAt.format(data.l10n, FormatMode.yyyymmdd)}",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -449,7 +487,7 @@ Future<void> showGradeBottomSheet(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: grade.subject);
|
||||
context.go('/grades/subject', extra: grade.subject.loadAndGet());
|
||||
},
|
||||
),
|
||||
]);
|
||||
@@ -458,8 +496,9 @@ Future<void> showGradeBottomSheet(
|
||||
Future<void> showHomeworkBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Homework homework,
|
||||
HomeworkCacheModel homework,
|
||||
) async {
|
||||
final subject = homework.subject.loadAndGet()!;
|
||||
showFirkaBottomSheet(context, [
|
||||
Text(
|
||||
data.l10n.homework,
|
||||
@@ -471,7 +510,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
style: appStyle.fonts.B_14R.apply(color: appStyle.colors.textSecondary),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeSmallCard([], null, homework.subject),
|
||||
GradeSmallCard(null, null, subject),
|
||||
SizedBox(height: 20),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
@@ -479,7 +518,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
margin: EdgeInsets.all(0),
|
||||
padding: EdgeInsets.all(12),
|
||||
child: Html(
|
||||
data: homework.description,
|
||||
data: homework.description.withoutFontFeatureSettings(),
|
||||
style: {
|
||||
"*": Style.fromTextStyle(
|
||||
appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
|
||||
@@ -489,42 +528,34 @@ Future<void> showHomeworkBottomSheet(
|
||||
),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
FutureBuilder<bool>(
|
||||
future: isHomeworkDone(data.isar, homework.uid),
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return SizedBox(); // or a loading indicator
|
||||
}
|
||||
|
||||
final done = snapshot.data!;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
left: [],
|
||||
center: [
|
||||
Text(
|
||||
!done ? data.l10n.mark_as_done : data.l10n.mark_as_not_done,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimaryLight,
|
||||
),
|
||||
),
|
||||
],
|
||||
color: appStyle.colors.accent,
|
||||
Column(
|
||||
children: [
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
left: [],
|
||||
center: [
|
||||
Text(
|
||||
!homework.isDone
|
||||
? data.l10n.mark_as_done
|
||||
: data.l10n.mark_as_not_done,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimaryLight,
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
context.read<HomeRefreshCubit>().requestRefresh();
|
||||
Navigator.pop(context);
|
||||
!done
|
||||
? markAsDone(data.isar, homework.uid)
|
||||
: markAsNotDone(data.isar, homework.uid);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
],
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
onTap: () {
|
||||
data.isar.writeTxnSync(() {
|
||||
homework.isDone = true;
|
||||
data.isar.homeworkCacheModels.putSync(homework);
|
||||
});
|
||||
context.read<HomeRefreshCubit>().requestRefresh();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
GestureDetector(
|
||||
@@ -542,7 +573,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/home/subject', extra: homework.subject);
|
||||
context.go('/home/subject', extra: subject);
|
||||
},
|
||||
),
|
||||
]);
|
||||
@@ -551,7 +582,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
Future<void> showGradeCalculatorBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Subject subject, {
|
||||
SubjectCacheModel subject, {
|
||||
void Function(int grade, int weight)? onAdd,
|
||||
}) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
@@ -561,7 +592,7 @@ Future<void> showGradeCalculatorBottomSheet(
|
||||
|
||||
class _GradeCalculatorSheetContent extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
final Subject subject;
|
||||
final SubjectCacheModel subject;
|
||||
final void Function(int grade, int weight)? onAdd;
|
||||
|
||||
const _GradeCalculatorSheetContent({
|
||||
@@ -695,7 +726,7 @@ class _GradeCalculatorSheetContentState
|
||||
min: 0,
|
||||
max: (_snapPoints.length - 1).toDouble(),
|
||||
divisions: _snapPoints.length - 1,
|
||||
label: '${weightPercent}%',
|
||||
label: '$weightPercent%',
|
||||
onChanged: (v) => setState(() => weightIndex = v.round()),
|
||||
),
|
||||
),
|
||||
@@ -749,7 +780,7 @@ class _GradeCalculatorSheetContentState
|
||||
Future<void> showSubjectBottomSheetSettings(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Subject subject, {
|
||||
SubjectCacheModel subject, {
|
||||
void Function(int grade, int weight)? onAddFromCalculator,
|
||||
}) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/firka_card.dart';
|
||||
42
firka/lib/ui/components/firka_icon_button.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "package:firka/ui/theme/style.dart";
|
||||
|
||||
class FirkaIconButton extends StatelessWidget {
|
||||
final Widget child;
|
||||
final VoidCallback? onTap;
|
||||
final Color? color;
|
||||
|
||||
const FirkaIconButton({
|
||||
required this.child,
|
||||
this.onTap,
|
||||
this.color,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final button = Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
padding: const EdgeInsets.all(6),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: color ?? appStyle.colors.buttonSecondaryFill,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
offset: const Offset(0, 1),
|
||||
blurRadius: appStyle.colors.shadowBlur.toDouble(),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
|
||||
if (onTap == null) return button;
|
||||
|
||||
return GestureDetector(onTap: onTap, child: button);
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/firka_shadow.dart';
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/grade.dart';
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
@@ -1,12 +1,13 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:firka/core/image_preloader.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/core/swear_generator.dart';
|
||||
|
||||
class ErrorPage extends StatelessWidget {
|
||||
final String exception;
|
||||
|
||||
const ErrorPage({super.key, required this.exception});
|
||||
|
||||
@override
|
||||
@@ -51,7 +52,6 @@ class ErrorPage extends StatelessWidget {
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
Text(
|
||||
//'a,',
|
||||
generateSwearSentence(),
|
||||
style: appStyle.fonts.H_H2.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
@@ -86,14 +86,21 @@ class ErrorPage extends StatelessWidget {
|
||||
color: appStyle.colors.card,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
exception,
|
||||
style: appStyle.fonts.B_14R.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
fontFamily: 'RobotoMono',
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
exception,
|
||||
style: appStyle.fonts.B_14R.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
fontFamily: 'RobotoMono',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: _CopyButton(exception: exception),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
right: 16,
|
||||
@@ -160,3 +167,34 @@ class ErrorPage extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CopyButton extends StatefulWidget {
|
||||
final String exception;
|
||||
const _CopyButton({required this.exception});
|
||||
|
||||
@override
|
||||
State<_CopyButton> createState() => _CopyButtonState();
|
||||
}
|
||||
|
||||
class _CopyButtonState extends State<_CopyButton> {
|
||||
final _tooltipKey = GlobalKey<TooltipState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Tooltip(
|
||||
key: _tooltipKey,
|
||||
message: initData.l10n.copied,
|
||||
triggerMode: TooltipTriggerMode.manual,
|
||||
child: IconButton(
|
||||
icon: Icon(Icons.copy, size: 18),
|
||||
color: appStyle.colors.textSecondary,
|
||||
onPressed: () async {
|
||||
await Clipboard.setData(ClipboardData(text: widget.exception));
|
||||
_tooltipKey.currentState?.ensureTooltipVisible();
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
_tooltipKey.currentState?.deactivate();
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,47 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/theme_cubit.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/ui/components/firka_shadow.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
Widget _extrasActionTile({
|
||||
required double width,
|
||||
required VoidCallback onTap,
|
||||
required Widget icon,
|
||||
required String label,
|
||||
}) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: FirkaCard.single(
|
||||
width: width,
|
||||
height: 60,
|
||||
margin: EdgeInsets.zero,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
child: Row(
|
||||
children: [
|
||||
icon,
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
textAlign: TextAlign.right,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void showExtrasBottomSheet(BuildContext context, AppInitialization data) {
|
||||
Widget Function(double) debugBtn = (_) => const SizedBox();
|
||||
@@ -17,49 +49,20 @@ void showExtrasBottomSheet(BuildContext context, AppInitialization data) {
|
||||
logger.finest("showExtrasBottomSheet() developer mode: ${isDeveloper()}");
|
||||
|
||||
if (isDeveloper()) {
|
||||
debugBtn = (double itemWidth) => GestureDetector(
|
||||
debugBtn = (double itemWidth) => _extrasActionTile(
|
||||
// Fejlesztői menü
|
||||
width: itemWidth,
|
||||
onTap: () {
|
||||
context.pop();
|
||||
context.push('/debug');
|
||||
},
|
||||
child: SizedBox(
|
||||
height: 60,
|
||||
width: itemWidth,
|
||||
child: FirkaShadow(
|
||||
shadow: true,
|
||||
child: Card(
|
||||
color: appStyle.colors.card,
|
||||
shadowColor: context.watch<ThemeCubit>().state.isLightMode
|
||||
? null
|
||||
: Colors.transparent,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
child: Row(
|
||||
children: [
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.bug2Solid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
data.l10n.debug_screen,
|
||||
textAlign: TextAlign.right,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
icon: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.bug2Solid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
label: data.l10n.debug_screen,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,120 +115,44 @@ void showExtrasBottomSheet(BuildContext context, AppInitialization data) {
|
||||
builder: (context, constraints) {
|
||||
final itemWidth = (constraints.maxWidth - 8) / 2;
|
||||
return Wrap(
|
||||
spacing: 2,
|
||||
runSpacing: 2,
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
debugBtn(itemWidth),
|
||||
GestureDetector(
|
||||
_extrasActionTile(
|
||||
// Fiókod
|
||||
width: itemWidth,
|
||||
onTap: () {
|
||||
context.pop();
|
||||
context.push(
|
||||
'/settings',
|
||||
extra: data.settings.items.group(
|
||||
"profile_settings",
|
||||
),
|
||||
extra: buildProfileSettingsTree(
|
||||
data.l10n,
|
||||
).children,
|
||||
);
|
||||
},
|
||||
child: SizedBox(
|
||||
height: 60,
|
||||
width: itemWidth,
|
||||
child: FirkaShadow(
|
||||
shadow: true,
|
||||
child: Card(
|
||||
color: appStyle.colors.card,
|
||||
shadowColor:
|
||||
context
|
||||
.watch<ThemeCubit>()
|
||||
.state
|
||||
.isLightMode
|
||||
? null
|
||||
: Colors.transparent,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12.0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.userSolid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
data.l10n.s_your_account,
|
||||
textAlign: TextAlign.right,
|
||||
style: appStyle.fonts.B_16R
|
||||
.apply(
|
||||
color: appStyle
|
||||
.colors
|
||||
.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
icon: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.userSolid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
label: data.l10n.s_your_account,
|
||||
),
|
||||
GestureDetector(
|
||||
_extrasActionTile(
|
||||
// Beállítás
|
||||
width: itemWidth,
|
||||
onTap: () {
|
||||
context.pop();
|
||||
context.push('/settings');
|
||||
},
|
||||
child: SizedBox(
|
||||
height: 60,
|
||||
width: itemWidth,
|
||||
child: FirkaShadow(
|
||||
shadow: true,
|
||||
child: Card(
|
||||
color: appStyle.colors.card,
|
||||
shadowColor:
|
||||
context
|
||||
.watch<ThemeCubit>()
|
||||
.state
|
||||
.isLightMode
|
||||
? null
|
||||
: Colors.transparent,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12.0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.settingsCogSolid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
data.l10n.settings_screen,
|
||||
textAlign: TextAlign.right,
|
||||
style: appStyle.fonts.B_16R
|
||||
.apply(
|
||||
color: appStyle
|
||||
.colors
|
||||
.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
icon: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.settingsCogSolid,
|
||||
size: 22.0,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
label: data.l10n.settings_screen,
|
||||
),
|
||||
// Ide jön a többi gomb majd
|
||||
],
|
||||
@@ -252,24 +179,9 @@ void showExtrasBottomSheet(BuildContext context, AppInitialization data) {
|
||||
if (debugCounter == 10) {
|
||||
final navigator = Navigator.of(context);
|
||||
final router = GoRouter.of(context);
|
||||
data.settings
|
||||
.group("settings")
|
||||
.setBoolean(
|
||||
"developer_enabled",
|
||||
!data.settings
|
||||
.group("settings")
|
||||
.boolean("developer_enabled"),
|
||||
);
|
||||
|
||||
await data.isar.writeTxn(() async {
|
||||
await data.settings
|
||||
.group("settings")["developer_enabled"]!
|
||||
.save(data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
await data.settings
|
||||
.group("settings")["developer_enabled"]!
|
||||
.postUpdate();
|
||||
await Settings.developerOptsEnabled.set(
|
||||
!Settings.developerOptsEnabled.value,
|
||||
);
|
||||
|
||||
navigator.pop();
|
||||
router.go('/home');
|
||||
|
||||
152
firka/lib/ui/phone/pages/extras/firka_toast.dart
Normal file
@@ -0,0 +1,152 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/phone/pages/extras/main_error.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/pages/extras/main_reauth.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
class FirkaToastWidget extends StatefulWidget {
|
||||
final Function()? onTap;
|
||||
final Function()? onDismiss;
|
||||
final List<Widget> children;
|
||||
final Color backgroundColor;
|
||||
|
||||
const FirkaToastWidget({
|
||||
super.key,
|
||||
required this.backgroundColor,
|
||||
this.onTap,
|
||||
this.onDismiss,
|
||||
required this.children,
|
||||
});
|
||||
|
||||
factory FirkaToastWidget.fetching(BuildContext context) {
|
||||
return FirkaToastWidget(
|
||||
backgroundColor: appStyle.colors.card,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(color: appStyle.colors.accent),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
initData.l10n.refreshing,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
factory FirkaToastWidget.error(BuildContext context, Object e) {
|
||||
return FirkaToastWidget(
|
||||
backgroundColor: appStyle.colors.errorCard,
|
||||
onDismiss: () {
|
||||
initData.toastCubit.clear();
|
||||
},
|
||||
children: [
|
||||
Text(
|
||||
initData.l10n.api_error,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.errorText,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
GestureDetector(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.questionCircleSolid,
|
||||
color: appStyle.colors.errorAccent,
|
||||
size: 24,
|
||||
),
|
||||
onTap: () {
|
||||
showErrorBottomSheet(
|
||||
context,
|
||||
"$e\n${e is Error ? e.stackTrace ?? '' : ''}",
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
factory FirkaToastWidget.reauth(BuildContext context) {
|
||||
return FirkaToastWidget(
|
||||
backgroundColor: appStyle.colors.errorCard,
|
||||
onTap: () {
|
||||
showReauthBottomSheet(context, initData, initData.l10n.reauth);
|
||||
},
|
||||
onDismiss: () {
|
||||
initData.toastCubit.clear();
|
||||
},
|
||||
children: [
|
||||
Text(
|
||||
initData.l10n.reauth,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.errorText,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.loginSolid,
|
||||
color: appStyle.colors.errorAccent,
|
||||
size: 24,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
State<FirkaToastWidget> createState() => _FirkaToastWidgetState();
|
||||
}
|
||||
|
||||
class _FirkaToastWidgetState extends State<FirkaToastWidget> {
|
||||
double _dragOffset = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Positioned(
|
||||
top: MediaQuery.of(context).size.height / 1.6 + _dragOffset,
|
||||
left: 0.0,
|
||||
right: 0.0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
onVerticalDragUpdate: (details) {
|
||||
setState(() {
|
||||
if (widget.onDismiss != null) _dragOffset += details.delta.dy;
|
||||
if (_dragOffset < 0) _dragOffset = 0;
|
||||
});
|
||||
},
|
||||
onVerticalDragEnd: (details) {
|
||||
if (_dragOffset > 50) {
|
||||
widget.onDismiss!();
|
||||
} else {
|
||||
setState(() {
|
||||
_dragOffset = 0;
|
||||
});
|
||||
}
|
||||
},
|
||||
child: Card(
|
||||
color: appStyle.colors.errorCard,
|
||||
shadowColor: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(20)),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(10),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: widget.children,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,9 @@ void showErrorBottomSheet(BuildContext context, String err) {
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Center(child: Text(err, style: appStyle.fonts.B_16R)),
|
||||
child: SelectionArea(
|
||||
child: Center(child: Text(err, style: appStyle.fonts.B_16R)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/widgets/login_webview.dart';
|
||||
@@ -9,18 +8,6 @@ void showReauthBottomSheet(
|
||||
AppInitialization data,
|
||||
String message,
|
||||
) {
|
||||
final accountPicker =
|
||||
(data.settings.group("profile_settings")["e_kreta_account_picker"]
|
||||
as SettingsKretenAccountPicker);
|
||||
|
||||
final currentToken =
|
||||
data.tokens.isNotEmpty && accountPicker.accountIndex < data.tokens.length
|
||||
? data.tokens[accountPicker.accountIndex]
|
||||
: null;
|
||||
|
||||
final username = currentToken?.studentId;
|
||||
final schoolId = currentToken?.iss;
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
elevation: 100,
|
||||
@@ -54,8 +41,8 @@ void showReauthBottomSheet(
|
||||
Expanded(
|
||||
child: LoginWebviewWidget(
|
||||
data,
|
||||
username: username,
|
||||
schoolId: schoolId,
|
||||
username: data.client!.cache.token.username,
|
||||
schoolId: data.client!.cache.token.iss,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -4,7 +4,7 @@ import 'package:firka/services/wear_sync_cache.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
void showWearBottomSheet(
|
||||
@@ -12,7 +12,7 @@ void showWearBottomSheet(
|
||||
AppInitialization data,
|
||||
String model,
|
||||
) async {
|
||||
final payload = await buildWearSyncPayload(data.client);
|
||||
final payload = await buildWearSyncPayload(data.client!);
|
||||
if (payload == null) return;
|
||||
if (!context.mounted) return;
|
||||
|
||||
@@ -66,17 +66,17 @@ class _WearPairSheetContentState extends State<_WearPairSheetContent> {
|
||||
|
||||
void _onPairTap() {
|
||||
setState(() => _syncing = true);
|
||||
final m = widget.data.client.model;
|
||||
final m = widget.data.client!.cache.token;
|
||||
WatchSyncHelper.sendMessageToWatch({
|
||||
'id': 'init_data',
|
||||
'auth': {
|
||||
'studentId': m.studentId,
|
||||
'studentIdNorm': m.studentIdNorm,
|
||||
'studentId': m.username,
|
||||
'studentIdNorm': m.key,
|
||||
'iss': m.iss,
|
||||
'idToken': m.idToken,
|
||||
'accessToken': m.accessToken,
|
||||
'refreshToken': m.refreshToken,
|
||||
'expiryDate': m.expiryDate!.millisecondsSinceEpoch,
|
||||
'expiryDate': m.expiryDate.millisecondsSinceEpoch,
|
||||
},
|
||||
'lastSyncAt': widget.payload['lastSyncAt'],
|
||||
'timetable': widget.payload['timetable'],
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/pages/extras/main_reauth.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
class ReauthToastWidget extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
final Function() onDismiss;
|
||||
|
||||
const ReauthToastWidget({
|
||||
super.key,
|
||||
required this.data,
|
||||
required this.onDismiss,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ReauthToastWidget> createState() => _ReauthToastWidgetState();
|
||||
}
|
||||
|
||||
class _ReauthToastWidgetState extends State<ReauthToastWidget> {
|
||||
double _dragOffset = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Positioned(
|
||||
top: MediaQuery.of(context).size.height / 1.6 + _dragOffset,
|
||||
left: 0.0,
|
||||
right: 0.0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
showReauthBottomSheet(
|
||||
context,
|
||||
widget.data,
|
||||
widget.data.l10n.reauth,
|
||||
);
|
||||
},
|
||||
onVerticalDragUpdate: (details) {
|
||||
setState(() {
|
||||
_dragOffset += details.delta.dy;
|
||||
if (_dragOffset < 0) _dragOffset = 0;
|
||||
});
|
||||
},
|
||||
onVerticalDragEnd: (details) {
|
||||
if (_dragOffset > 50) {
|
||||
widget.onDismiss();
|
||||
} else {
|
||||
setState(() {
|
||||
_dragOffset = 0;
|
||||
});
|
||||
}
|
||||
},
|
||||
child: Card(
|
||||
color: appStyle.colors.errorCard,
|
||||
shadowColor: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(200)),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.reauth,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.errorText,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.loginSolid,
|
||||
color: appStyle.colors.errorAccent,
|
||||
size: 24,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget buildReauthToast(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Function() onDismiss,
|
||||
) {
|
||||
return ReauthToastWidget(data: data, onDismiss: onDismiss);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_chart.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_summary_bar.dart';
|
||||
import 'package:firka/ui/shared/grade_small_card.dart';
|
||||
@@ -11,14 +10,11 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/last_seen_helper.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/shared/delayed_spinner.dart';
|
||||
|
||||
class HomeGradesScreen extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
@@ -30,297 +26,233 @@ class HomeGradesScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeGradesScreen extends FirkaState<HomeGradesScreen> {
|
||||
ApiResponse<List<Grade>>? grades;
|
||||
ApiResponse<List<Lesson>>? week;
|
||||
ApiResponse<List<ClassGroup>>? classGroups;
|
||||
ApiResponse<List<SubjectAverage>>? lessons;
|
||||
ApiResponse<List<ClassGroupSubjectAverage>>? classAvgs;
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
var now = timeNow();
|
||||
var start = now.subtract(Duration(days: now.weekday - 1));
|
||||
var end = start.add(Duration(days: 6));
|
||||
|
||||
grades = await widget.data.client.getGrades(forceCache: false);
|
||||
week = await widget.data.client.getTimeTable(start, end, forceCache: false);
|
||||
classGroups = await widget.data.client.getClassGroups(forceCache: false);
|
||||
if (classGroups?.response?.isNotEmpty ?? false) {
|
||||
var group = classGroups!.response!.first;
|
||||
lessons = await widget.data.client.getSubjectAverage(
|
||||
group,
|
||||
forceCache: false,
|
||||
);
|
||||
classAvgs = await widget.data.client.getClassGroupAverages(
|
||||
group,
|
||||
forceCache: false,
|
||||
);
|
||||
await Future.delayed(Duration(milliseconds: 100));
|
||||
}
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
(() async {
|
||||
var now = timeNow();
|
||||
var start = now.subtract(Duration(days: now.weekday - 1));
|
||||
var end = start.add(Duration(days: 6));
|
||||
|
||||
grades = await widget.data.client.getGrades();
|
||||
week = await widget.data.client.getTimeTable(start, end);
|
||||
classGroups = await widget.data.client.getClassGroups();
|
||||
if (classGroups?.response?.isNotEmpty ?? false) {
|
||||
var group = classGroups!.response!.first;
|
||||
lessons = await widget.data.client.getSubjectAverage(group);
|
||||
classAvgs = await widget.data.client.getClassGroupAverages(group);
|
||||
await Future.delayed(Duration(milliseconds: 100));
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
})();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<HomeRefreshCubit, HomeRefreshState>(
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (grades == null ||
|
||||
lessons == null ||
|
||||
classAvgs == null ||
|
||||
week == null) {
|
||||
return SizedBox(
|
||||
height: MediaQuery.of(context).size.height / 1.35,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [SizedBox(), DelayedSpinnerWidget(), SizedBox()],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
final allGrades = grades!.response!;
|
||||
final allLessons = lessons!.response!;
|
||||
final allGrades = LastSeenHelper.openedGrades(
|
||||
widget.data.settings.selectedAccountKey,
|
||||
widget.data.client!.cache.getGrades().findAllSync(),
|
||||
);
|
||||
|
||||
final subjectAverage = allGrades.getSubjectAverage();
|
||||
final roundedSubjectAverage = allGrades.getRoundedSubjectAverage();
|
||||
final classAverages = classAvgs!.response!
|
||||
.map((c) => c.classGroupAverage)
|
||||
.nonNulls;
|
||||
final subjectAverage = allGrades.getSubjectAverage();
|
||||
final roundedSubjectAverage = allGrades.getRoundedSubjectAverage();
|
||||
final classAverages = widget.data.client!.cache
|
||||
.getClassAverages()
|
||||
.findAllSync();
|
||||
|
||||
double? classAverage = classAverages.isNotEmpty
|
||||
? classAverages.reduce((f, s) => f + s) / classAverages.length
|
||||
: null;
|
||||
double? classAverage = classAverages.isNotEmpty
|
||||
? classAverages.map((c) => c.classAverage).reduce((f, s) => f + s) /
|
||||
classAverages.length
|
||||
: null;
|
||||
|
||||
final Set<Subject> subjects = HashSet(
|
||||
hashCode: (s) => s.uid.hashCode,
|
||||
equals: (s, s2) => s.uid == s2.uid,
|
||||
);
|
||||
final List<Widget> gradeCards = [];
|
||||
final List<SubjectCacheModel> subjects = widget.data.client!.cache
|
||||
.getSubjects()
|
||||
.findAllSync();
|
||||
final List<Widget> gradeCards = [];
|
||||
|
||||
allGrades.map((g) => g.subject).forEach(subjects.add);
|
||||
allLessons.map((l) => l.subject).forEach(subjects.add);
|
||||
|
||||
for (var subject
|
||||
in subjects.toList()..sort((s1, s2) => s1.name.compareTo(s2.name))) {
|
||||
gradeCards.add(
|
||||
GestureDetector(
|
||||
child: GradeSmallCard(
|
||||
allGrades,
|
||||
classAvgs!.response!
|
||||
.firstWhereOrNull((s) => s.subject.uid == subject.uid)
|
||||
?.classGroupAverage,
|
||||
subject,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: subject);
|
||||
},
|
||||
for (var subject
|
||||
in subjects.toList()..sort((s1, s2) => s1.name.compareTo(s2.name))) {
|
||||
gradeCards.add(
|
||||
GestureDetector(
|
||||
child: GradeSmallCard(
|
||||
allGrades.getAverageBySubject(subject),
|
||||
subject.classAverage.loadAndGet()?.classAverage,
|
||||
subject,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.subjects,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeChartWithInteraction(grades: allGrades),
|
||||
SizedBox(height: 10),
|
||||
GradeSummaryBar(grades: allGrades, l10n: widget.data.l10n),
|
||||
SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.your_subjects,
|
||||
style: appStyle.fonts.H_14px.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Column(
|
||||
spacing: 16,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: gradeCards,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
widget.data.l10n.data,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (subjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(subjectAverage).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
subjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(subjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg_rounded,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (roundedSubjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(
|
||||
roundedSubjectAverage,
|
||||
).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
roundedSubjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(roundedSubjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (classAverage != null)
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
classAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_n,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Text(
|
||||
week!.response!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.type.name != TimetableConsts.event,
|
||||
)
|
||||
.length
|
||||
.toString(),
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: subject);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
headingText(widget.data.l10n.subjects),
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeChartWithInteraction(grades: allGrades),
|
||||
SizedBox(height: 10),
|
||||
GradeSummaryBar(grades: allGrades, l10n: widget.data.l10n),
|
||||
SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => widget.data.client!.pullRefresh(
|
||||
() => widget.data.client!.getGrades(),
|
||||
),
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.your_subjects,
|
||||
style: appStyle.fonts.H_14px.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Column(
|
||||
spacing: 16,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: gradeCards,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
widget.data.l10n.data,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (subjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(subjectAverage).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
subjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(subjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg_rounded,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (roundedSubjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(
|
||||
roundedSubjectAverage,
|
||||
).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
roundedSubjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(roundedSubjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (classAverage != null)
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
classAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
/*
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_n,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Text(
|
||||
week!.response!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.type.name != TimetableConsts.event,
|
||||
)
|
||||
.length
|
||||
.toString(),
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),*/
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||