28 Commits

Author SHA1 Message Date
6290c27a7e chore: update l10n 2026-09-04 19:55:20 +02:00
a3a036440a fix: bold monochrome icon and notification tray icon silhouettes
Both were derived from a thin, mostly-transparent outline stroke.
Android renders adaptive monochrome icons and notification-tray icons
using only the alpha channel (system applies its own tint), so thin
strokes read as illegible scribbles when shrunk, and any opaque fill
sharing alpha with the outline collapses into one shapeless blob.

Regenerated monochrome_logo.png as a bold filled silhouette (derived
from the existing colored logo art) that keeps the eye holes as
transparent negative space, and rebuilt the ic_notification drawables
from the same source so the status-bar icon isn't a solid blob either.
2026-09-04 17:44:58 +02:00
062f1afe67 feat(notifications): add FCM debug status panel to developer settings
Adds an FcmStatus row + refresh-notification toggle to the Developer
settings subgroup: shows init state, token presence (last 6 chars),
notification permission (non-prompting), subscribed wakeup topic, and
last token-refresh time. Also registers on resumed sessions (app
reopened while already logged in), which previously only got FCM
registration via the explicit login/logout flow.
2026-09-04 16:26:23 +02:00
6d30767cb0 feat(notifications): add Firebase Cloud Messaging push support
Firebase project config, topic subscriptions synced to
login state and per-category settings, a client for the Go FCM
backend, and a settings UI to toggle push and its wakeup interval.
2026-09-04 16:17:34 +02:00
0e3c3c421f feat(notifications): add local notification diffing for FCM wakeups
Diffs grades/homework/tests/absences/lessons/messages against a
separate last-seen namespace on each silent FCM wakeup, and shows a
local notification per category for genuinely new items. Adds a
headless bootstrap so the background isolate can populate the
minimal app state KretaClient needs.
2026-09-04 16:17:32 +02:00
b6d1b221b8 ci: publish appbundle/apks to gitea package registry 2026-09-03 17:44:29 +02:00
e79c489de6 ci: release appbundle on main only 2026-09-03 17:41:00 +02:00
c9a034c0f8 ci: build an appbundle instead of an apk 2026-09-03 17:39:50 +02:00
4dbe0b71e6 fix(ci): persist PUB_CACHE across woodpecker steps
Each step runs in a fresh container from the builder image, so the
default /root/.pub-cache doesn't survive from `flutter pub get` into
the codegen/build steps. Point PUB_CACHE at a workspace-local path
instead, which is shared across steps.
2026-09-03 17:23:23 +02:00
eddfe52a51 ref(ci): switch to woodpecker ci 2026-09-03 17:20:03 +02:00
1f2f7e9d4e Merge pull request 'fixin maybe pt 2' (#43) from checkedearrabbit/firka:dev into dev
Reviewed-on: firka/firka#43
2026-09-02 11:09:07 +02:00
checkedear
5766eb6675 fixin maybe 3 2026-09-02 10:08:39 +02:00
b28bebcce1 Merge pull request 'fixin maybe' (#42) from checkedearrabbit/firka:dev into dev
Reviewed-on: firka/firka#42
2026-09-02 09:05:34 +02:00
checkedear
8fb5d5c89b fixin maybe 2 2026-09-02 07:56:35 +02:00
checkedear
f22ab629bc fixin maybe 2026-09-02 07:48:39 +02:00
zypherift
09ac4b7f61 delete mock from this repo 2026-08-28 13:16:42 +02:00
zypherift
5320625d83 add copy jwt 2026-08-28 13:12:40 +02:00
zypherift
eccdf90fd8 change mock data 2026-08-28 13:12:33 +02:00
zypherift
b4ccd52321 change gitignore 2026-08-28 10:57:10 +02:00
zypherift
4658366fd4 chore: bump l10n submodule 2026-08-28 10:50:09 +02:00
zypherift
aa77e25fe4 fix: mock server fills grade links and keeps sessions across restarts 2026-08-28 10:47:18 +02:00
zypherift
8984f8a915 feat: settings screen redesign with extras page and toggles 2026-08-28 10:47:10 +02:00
zypherift
4c28999d10 feat: surprise grades card and hide new grades until opened 2026-08-28 10:47:01 +02:00
zypherift
50274575f6 fix: mock server token claims and omission data 2026-08-27 20:44:05 +02:00
zypherift
fb8fad142a feat: clear account data and fix login redirect on logout 2026-08-27 20:43:48 +02:00
zypherift
2dccb59f7f fix: read grade kind from the correct api field 2026-08-27 20:43:42 +02:00
zypherift
7c9ade35f0 feat: add epic grades reveal screen 2026-08-27 20:43:33 +02:00
zypherift
ca9e6c3efa feat: add mock kréta server + login-screen mock mode toggle
Adds a standalone Go mock server (mock_kreta_server/) with an admin
GUI for editing student/grade/timetable/etc data, plus a login-screen
long-press toggle to point the app at it instead of the real e-Kréta
service for local testing. Also pulls in updated translations from
the firka-localization submodule.
2026-08-26 22:07:21 +02:00
78 changed files with 4314 additions and 1114 deletions

1
.gitignore vendored
View File

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

128
.woodpecker.yml Normal file
View 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
View File

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

View File

@@ -2,6 +2,9 @@ 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.
@@ -14,6 +17,7 @@ android {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
isCoreLibraryDesugaringEnabled = true
}
buildFeatures {
compose = true
@@ -73,6 +77,7 @@ configurations.all {
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")

View 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"
}

View 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"
}

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 957 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View 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

View 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

View 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

View 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

View File

@@ -1,16 +1,16 @@
icons:
"flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1"
"pubspec.yaml": "d0f795bcffd597e260202b29476fc99caa3bb4aac5abd48a210cadb9f45c19e7"
"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_hu.arb": "e11b8fe4d4fd239584792971c341f1e329fb91f5f49fa6baa664c98b06fc5176"
"lib/l10n/app_de.arb": "5114c70b506f290217161881336d6118c975d59f32347bbdc94a51c1a25293e7"
"lib/l10n/app_en.arb": "a5417b2de058a67db40fa7bfb3526d800fd2f82349dfbc895cff8b298069e707"
"lib/l10n/app_pl.arb": "36cad0796cf8bd20fe969d5fd8443430d25fa932028c0177917ecef6964a08dd"
"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/token_model.dart": "8c957cd07e473827d78fd8fd4fb6c1336b636a69c25c93618e1e7f94b7cf0683"

1
firka/firebase.json Normal file
View 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"}}}}}}

View File

@@ -21,6 +21,7 @@ import 'package:kreta_api/kreta_api.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/core/bloc/toast_cubit.dart';
import 'package:firka/core/dev/mock_backend.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:firka/core/debug_helper.dart';
import 'package:firka_common/data/util.dart';
@@ -480,7 +481,7 @@ class KretaClient {
};
return await dio.get(
url,
MockBackend.rewrite(url),
options: Options(
method: method,
headers: headers,

View 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;
}
}
}

View 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 (_) {}
}
}
}

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

View File

@@ -3,6 +3,7 @@ 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';
Future<TokenGrantResponse> getAccessToken(String code) async {
@@ -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,
);
@@ -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,
);

View File

@@ -8,6 +8,7 @@ import 'package:flutter/services.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/api/client/kreta_client.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/settings_effects.dart';
import 'package:firka/core/settings/settings_repository.dart';
@@ -195,11 +196,19 @@ Future<void> _initData(AppInitialization init) async {
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);
// 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 {
@@ -306,6 +315,14 @@ Future<void> initializeApp() async {
}
}
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);
}
await _initData(initData);
initDone = true;

View 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();
}
}

View 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));
}
}

View File

@@ -28,6 +28,8 @@ bool isMorningNotificationEnabled() =>
bool isWearOsSupportEnabled() =>
Platform.isAndroid && Settings.wearOsSupport.value;
bool isPushNotificationsEnabled() => Settings.notifyAll.value;
bool isDebug() => kDebugMode;
bool isDebugIOS() => kDebugMode && Platform.isIOS;
@@ -200,7 +202,7 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.settingsCogSolid,
l10n.s_a,
l10n.s_ag,
[
SettingsUiBackHeader(l10n.s_settings, always),
SettingsUiHeader(l10n.s_ag, always),
@@ -280,6 +282,8 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
], always),
],
always,
null,
l10n.s_a_desc,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
@@ -289,6 +293,69 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsUiPersonalization(appIconPickerTree, always),
],
always,
null,
l10n.s_c_desc,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.bellSolid,
l10n.s_notifications,
[
SettingsUiBackHeader(l10n.s_settings, always),
SettingsUiHeader(l10n.s_notifications, always),
SettingsUiPadding(23, always),
SettingsUiBoolean(
FirkaIconType.majesticons,
Majesticon.bellSolid,
l10n.s_notif_push_enabled,
SettingsRegistry.notifyAll,
always,
),
SettingsUiHeaderSmall(l10n.s_notif_wakeup_interval_header, isPushNotificationsEnabled),
SettingsUiEnum(SettingsRegistry.notifyWakeupInterval, [
l10n.s_notif_wakeup_hourly,
l10n.s_notif_wakeup_two_hourly,
], isPushNotificationsEnabled),
SettingsUiHeaderSmall(l10n.s_notif_categories_header, isPushNotificationsEnabled),
SettingsUiBoolean(
null,
null,
l10n.s_notif_grades,
SettingsRegistry.notifyGrades,
isPushNotificationsEnabled,
),
SettingsUiBoolean(
null,
null,
l10n.s_notif_homework_tests,
SettingsRegistry.notifyHomeworkTests,
isPushNotificationsEnabled,
),
SettingsUiBoolean(
null,
null,
l10n.s_notif_absences,
SettingsRegistry.notifyAbsences,
isPushNotificationsEnabled,
),
SettingsUiBoolean(
null,
null,
l10n.s_notif_lessons,
SettingsRegistry.notifyLessons,
isPushNotificationsEnabled,
),
SettingsUiBoolean(
null,
null,
l10n.s_notif_messages,
SettingsRegistry.notifyMessages,
isPushNotificationsEnabled,
),
],
isAndroid,
null,
l10n.s_notifications_desc,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
@@ -351,11 +418,85 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
FirkaIconType.majesticons,
Majesticon.lightningBoltSolid,
l10n.s_extras,
[SettingsUiBackHeader(l10n.s_settings, always)],
never,
[
SettingsUiBackHeader(l10n.s_settings, always),
SettingsUiHeader(l10n.s_extras, always),
SettingsUiPadding(23, always),
SettingsUiBoolean(
FirkaIconType.majesticons,
Majesticon.questionCircleSolid,
l10n.s_surprise_grades,
SettingsRegistry.surpriseGrades,
always,
),
SettingsUiBoolean(
FirkaIconType.majesticons,
Majesticon.shootingStarSolid,
l10n.s_seasonal_icons,
SettingsRegistry.seasonalAppIcons,
always,
),
SettingsUiBoolean(
FirkaIconType.majesticons,
Majesticon.flower2Solid,
l10n.s_uwu_mode,
SettingsRegistry.uwuMode,
always,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.calendarSolid,
l10n.s_calendar_sync,
const [],
always,
null,
l10n.s_todo,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.bookmarkSolid,
l10n.s_save_grades,
const [],
always,
null,
l10n.s_todo,
),
SettingsUiPadding(20, always),
SettingsUiHeaderSmall(l10n.s_welcome_msg, always),
SettingsUiSubGroup(
null,
null,
l10n.s_welcome_msg,
const [],
always,
null,
l10n.s_todo,
),
],
always,
null,
l10n.s_extras_desc,
),
SettingsUiPadding(20, always),
SettingsUiHeaderSmall(l10n.s_other, always),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.mapMarkerAreaSolid,
l10n.s_sticker_map,
const [],
always,
null,
l10n.s_todo,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.qrCodeSolid,
l10n.s_qr_reader,
const [],
always,
null,
l10n.s_todo,
),
SettingsUiPadding(20, never),
SettingsUiHeaderSmall(l10n.s_other, never),
SettingsUiSubGroup(
FirkaIconType.majesticonsLocal,
"wrenchSolid",
@@ -369,6 +510,15 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsRegistry.statsForNerds,
always,
),
SettingsUiHeaderSmall(l10n.s_fcm_status_title, always),
SettingsUiFcmStatus(always),
SettingsUiBoolean(
null,
null,
l10n.s_fcm_notify_on_message,
SettingsRegistry.fcmDebugNotifyOnMessage,
always,
),
SettingsUiLogs(always),
],
isDeveloper,
@@ -417,6 +567,15 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
],
always,
),
SettingsUiSubGroup(
FirkaIconType.majesticons,
Majesticon.phoneSolid,
l10n.s_feedback,
const [],
always,
null,
l10n.s_todo,
),
SettingsUiBoolean(
null,
null,

View File

@@ -4,9 +4,9 @@ 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 "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
import "settings_repository.dart";
import "settings_schema.dart";
@@ -38,24 +38,6 @@ void registerSettingsEffects(
repo.onChange(SettingsRegistry.titleWeight, refreshTitleStyle);
repo.onChange(SettingsRegistry.titleCapitalization, refreshTitleStyle);
Future<void> refreshPresetTheme(_) async {
if (isBuiltinThemeId(Settings.selectedThemeId.value)) {
final next = composeBuiltinThemeId(
Settings.selectedCoreThemeId.value,
Settings.selectedGradeThemeId.value,
);
if (next != Settings.selectedThemeId.value) {
await Settings.selectedThemeId.setSilently(next);
}
}
initTheme(initData);
initData.themeCubit.refresh();
initData.homeRefreshCubit.requestRefresh();
}
repo.onChange(SettingsRegistry.selectedCoreThemeId, refreshPresetTheme);
repo.onChange(SettingsRegistry.selectedGradeThemeId, refreshPresetTheme);
repo.onChange(SettingsRegistry.wearOsSupport, (enabled) async {
if (!Platform.isAndroid) return;
if (enabled && initDone) {
@@ -81,6 +63,26 @@ void registerSettingsEffects(
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) {

View File

@@ -19,6 +19,11 @@ enum TitleFont {
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;
@@ -142,4 +147,53 @@ abstract class SettingsSchema {
@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;
}

View File

@@ -33,9 +33,24 @@ class SettingsRegistry {
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,
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,
];
}
@@ -70,4 +85,19 @@ extension SettingsAccessors on SettingsRepository {
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);
}

View File

@@ -59,6 +59,7 @@ class SettingsUiSubGroup extends SettingsUiNode {
final String title;
final List<SettingsUiNode> children;
final String? redirectTo;
final String? subtitle;
const SettingsUiSubGroup(
this.iconType,
@@ -67,6 +68,7 @@ class SettingsUiSubGroup extends SettingsUiNode {
this.children,
bool Function() visible, [
this.redirectTo,
this.subtitle,
]) : super(visible);
}
@@ -155,6 +157,14 @@ 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);
}

View 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',
);
}

View 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;
}

View 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);
}
}
}

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

View 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,
);
}
}
}

View File

@@ -12,6 +12,7 @@ import 'package:go_router/go_router.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/ui/theme/style.dart';
@@ -38,7 +39,10 @@ class _HomeGradesScreen extends FirkaState<HomeGradesScreen> {
}
Widget _buildContent(BuildContext context) {
final allGrades = widget.data.client!.cache.getGrades().findAllSync();
final allGrades = LastSeenHelper.openedGrades(
widget.data.settings.selectedAccountKey,
widget.data.client!.cache.getGrades().findAllSync(),
);
final subjectAverage = allGrades.getSubjectAverage();
final roundedSubjectAverage = allGrades.getRoundedSubjectAverage();

View File

@@ -18,6 +18,7 @@ import 'package:isar_community/isar.dart';
import 'package:majesticons_flutter/majesticons_flutter.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/state/firka_state.dart';
import 'package:firka/ui/theme/style.dart';
@@ -30,11 +31,14 @@ class HomeGradesSubjectScreen extends StatefulWidget {
factory HomeGradesSubjectScreen.subject(SubjectCacheModel subject) {
return HomeGradesSubjectScreen(
subject,
initData.client!.cache
.getGrades()
.subject((s) => s.cacheKeyEqualTo(subject.cacheKey))
.sortByCreatedAtDesc()
.findAllSync(),
LastSeenHelper.openedGrades(
initData.settings.selectedAccountKey,
initData.client!.cache
.getGrades()
.subject((s) => s.cacheKeyEqualTo(subject.cacheKey))
.sortByCreatedAtDesc()
.findAllSync(),
),
);
}

View File

@@ -1,4 +1,10 @@
import 'package:firka_common/data/last_seen.dart';
import 'package:firka_common/data/models/grade_cache_model.dart';
import 'package:firka_common/data/models/lesson_cache_model.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/ui/phone/screens/surprise_grades/surprise_grades_screen.dart';
import 'package:firka/ui/phone/widgets/info_card.dart';
import 'package:firka/ui/phone/widgets/lesson_slider.dart';
import 'package:firka_common/data/util.dart';
@@ -35,13 +41,69 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _seedLastSeen();
if (mounted) setState(() => _fadeNewInserts = true);
});
}
List<GradeCacheModel> _newGrades() {
if (!Settings.surpriseGrades.value) return const [];
final account = widget.data.settings.selectedAccountKey;
final seen = LastSeenHelper.get(account, LastSeenHelper.grades);
if (seen == null) return const [];
return LastSeen.newerThan(
widget.data.client!.cache.getGrades().findAllSync(),
seen,
);
}
Future<void> _seedLastSeen() async {
final account = widget.data.settings.selectedAccountKey;
final existing = LastSeenHelper.get(account, LastSeenHelper.grades);
if (existing != null) return;
final newest = LastSeen.newestOf(
widget.data.client!.cache.getGrades().findAllSync(),
);
if (newest == null) return;
await LastSeenHelper.set(account, LastSeenHelper.grades, newest);
}
void _openNewGrades(List<GradeCacheModel> grades) async {
if (grades.isEmpty) return;
final revealed = <int>{};
await Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(
builder: (context) => SurpriseGradesScreen(
grades,
widget.data.l10n,
onRevealed: (g) => revealed.add(g.cacheKey),
),
),
);
final newest = revealed.length == grades.length
? LastSeen.newestOf(grades)
: null;
if (newest != null) {
await LastSeenHelper.set(
widget.data.settings.selectedAccountKey,
LastSeenHelper.grades,
newest,
);
}
if (mounted) setState(() {});
}
void _onRefreshRequested(BuildContext context) async {
final cubit = context.read<HomeRefreshCubit>();
await _seedLastSeen();
if (mounted) {
setState(() {});
cubit.onRefreshComplete();
@@ -66,8 +128,12 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
Widget _buildContent(BuildContext context, ToastState toastState) {
final now = timeNow();
final student = widget.data.client!.cache.findStudentOrNull();
final newGrades = _newGrades();
final infoItems = widget.data.client!.cache.getMessages().findAllSync();
final gradeItems = widget.data.client!.cache.getGrades().findAllSync();
final gradeItems = LastSeenHelper.openedGrades(
widget.data.settings.selectedAccountKey,
widget.data.client!.cache.getGrades().findAllSync(),
);
final testItems = widget.data.client!.cache.getTests().findAllSync();
final homeworkItems = widget.data.client!.cache
.getHomeworks()
@@ -154,8 +220,13 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
child: const Center(child: DelayedSpinnerWidget()),
),
_FadeInWhenLoaded(
loaded: todayLesson.isNotEmpty,
child: LessonSlider(todayLesson, testsTomorrow),
loaded: todayLesson.isNotEmpty || newGrades.isNotEmpty,
child: LessonSlider(
todayLesson,
testsTomorrow,
newGrades: newGrades,
onNewGradesTap: () => _openNewGrades(newGrades),
),
),
SizedBox(height: 24),
...noticeBoardWidgets

View File

@@ -20,12 +20,15 @@ import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firka/core/debug_helper.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/core/state/firka_state.dart';
import 'package:firka/ui/phone/screens/surprise_grades/surprise_grades_screen.dart';
import 'package:firka/ui/shared/firka_icon.dart';
import 'package:firka/ui/theme/style.dart';
import 'package:firka_common/ui/components/filled_circle.dart';
import 'package:flutter/services.dart';
import 'package:home_widget/home_widget.dart';
import 'package:isar_community/isar.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
@@ -45,6 +48,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
Uint8List? profilePictureData;
bool useCache = true;
late TextEditingController _mockBackendUrlController;
@override
void initState() {
@@ -52,6 +56,15 @@ class _DebugScreen extends FirkaState<DebugScreen> {
_picker = ImagePicker();
profilePictureData = widget.data.profilePicture;
_mockBackendUrlController = TextEditingController(
text: Settings.mockBackendUrl.value,
);
}
@override
void dispose() {
_mockBackendUrlController.dispose();
super.dispose();
}
@override
@@ -100,6 +113,30 @@ class _DebugScreen extends FirkaState<DebugScreen> {
),
],
),
const SizedBox(height: 5),
Row(
children: [
Text('use mock backend'),
Switch(
value: Settings.mockBackendEnabled.value,
onChanged: (bool value) {
setState(() {
Settings.mockBackendEnabled.set(value);
});
},
),
],
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
controller: _mockBackendUrlController,
decoration: const InputDecoration(labelText: 'mock backend url'),
onSubmitted: (value) {
Settings.mockBackendUrl.set(value);
},
),
),
const SizedBox(height: 20),
profilePicture,
ElevatedButton(
@@ -218,6 +255,80 @@ class _DebugScreen extends FirkaState<DebugScreen> {
},
child: const Text('getGrades()'),
),
ElevatedButton(
onPressed: () {
final grades = widget.data.isar.gradeCacheModels
.where()
.findAllSync();
if (grades.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('no new grades uwu')),
);
return;
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
SurpriseGradesScreen(grades, widget.data.l10n),
),
);
},
child: const Text('Epikus jegyszerzés'),
),
ElevatedButton(
onPressed: () {
final grades = widget.data.isar.gradeCacheModels
.where()
.findAllSync();
if (grades.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('no new grades uwu')),
);
return;
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
SurpriseCardFaceDebugScreen(grades.first, widget.data.l10n),
),
);
},
child: const Text('Epikus jegyszerzés (card face debug)'),
),
ElevatedButton(
onPressed: () async {
final token = widget.data.settings.getSelectedToken();
if (token == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No token available to copy')),
);
return;
}
await Clipboard.setData(
ClipboardData(text: token.accessToken),
);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Access token copied')),
);
},
child: const Text('Copy JWT'),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SurpriseParticleDebugScreen(),
),
);
},
child: const Text('Epikus jegyszerzés (particle debug)'),
),
ElevatedButton(
onPressed: () async {
var now = timeNow();
@@ -320,16 +431,6 @@ class _DebugScreen extends FirkaState<DebugScreen> {
},
child: const Text('wipe users'),
),
const SizedBox(height: 20),
Wrap(
alignment: WrapAlignment.center,
spacing: 16,
runSpacing: 16,
children: [
for (final entry in _themeColorSwatches())
_themeColorSwatch(context, entry.$1, entry.$2),
],
),
SizedBox(
height: 600,
child: GridView.count(
@@ -373,70 +474,3 @@ class _DebugScreen extends FirkaState<DebugScreen> {
);
}
}
List<(String, Color)> _themeColorSwatches() {
final c = appStyle.colors;
return [
("background", c.background),
("backgroundAmoled", c.backgroundAmoled),
("background0p", c.background0p),
("success", c.success),
("textPrimary", c.textPrimary),
("textSecondary", c.textSecondary),
("textTertiary", c.textTertiary),
if (c.textTeritary != null) ("textTeritary", c.textTeritary!),
("textPrimaryLight", c.textPrimaryLight),
("textSecondaryLight", c.textSecondaryLight),
("textTertiaryLight", c.textTertiaryLight),
("card", c.card),
("cardTranslucent", c.cardTranslucent),
("buttonSecondaryFill", c.buttonSecondaryFill),
("buttonDisabledIcon", c.buttonDisabledIcon),
("accent", c.accent),
("secondary", c.secondary),
("shadowColor", c.shadowColor),
("a10p", c.a10p),
("a15p", c.a15p),
("warningAccent", c.warningAccent),
("warningText", c.warningText),
("warning15p", c.warning15p),
("warningCard", c.warningCard),
("errorAccent", c.errorAccent),
("errorText", c.errorText),
("error15p", c.error15p),
("errorCard", c.errorCard),
("grade5", c.grade5),
("grade4", c.grade4),
("grade3", c.grade3),
("grade2", c.grade2),
("grade1", c.grade1),
];
}
Widget _themeColorSwatch(BuildContext context, String name, Color color) {
final darkBg = color.computeLuminance() > 0.5;
final bg = darkBg ? const Color(0xFF121212) : const Color(0xFFF2F2F2);
final labelColor = darkBg ? const Color(0xFFF2F2F2) : const Color(0xFF121212);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
decoration: BoxDecoration(
color: bg,
borderRadius: BorderRadius.circular(8),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
name,
style: TextTheme.of(context).bodySmall?.copyWith(color: labelColor),
),
FilledCircle(
diameter: 40,
color: color,
child: const SizedBox(),
),
],
),
);
}

View File

@@ -15,7 +15,11 @@ import 'package:flutter_svg/flutter_svg.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'package:vibration/vibration.dart';
import 'package:firka/api/login_finish.dart';
import 'package:firka/api/mock_login.dart';
import 'package:firka/core/bloc/theme_cubit.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/core/state/firka_state.dart';
import 'package:firka/core/image_preloader.dart';
import 'package:firka/ui/theme/style.dart';
@@ -32,6 +36,11 @@ class _LoginScreenState extends FirkaState<LoginScreen> {
late LoginWebviewWidget _loginWebView;
bool _preloadDone = false;
final _mockUsernameController = TextEditingController(text: "student");
final _mockPasswordController = TextEditingController(text: "student");
bool _mockLoginInProgress = false;
String? _mockLoginError;
@override
void initState() {
super.initState();
@@ -40,6 +49,125 @@ class _LoginScreenState extends FirkaState<LoginScreen> {
_preloadImages();
}
@override
void dispose() {
_mockUsernameController.dispose();
_mockPasswordController.dispose();
super.dispose();
}
Future<void> _showMockModeDialog() async {
final wasEnabled = Settings.mockBackendEnabled.value;
final urlController = TextEditingController(
text: Settings.mockBackendUrl.value,
);
final confirmed = await showDialog<bool>(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
backgroundColor: appStyle.colors.card,
title: Text(
wasEnabled ? 'Disable mock mode?' : 'Enable mock mode?',
style: appStyle.fonts.H_16px.copyWith(
color: appStyle.colors.textPrimary,
),
),
content: wasEnabled
? Text(
'Logging in will go back to the real e-Kréta service.',
style: appStyle.fonts.B_14R.apply(
color: appStyle.colors.textSecondary,
),
)
: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Logging in will talk to this mock kréta server instead of the real e-Kréta service. Use the mock API\'s IP, not localhost.',
style: appStyle.fonts.B_14R.apply(
color: appStyle.colors.textSecondary,
),
),
const SizedBox(height: 12),
TextField(
controller: urlController,
autofocus: true,
style: appStyle.fonts.B_14R.apply(
color: appStyle.colors.textPrimary,
),
decoration: InputDecoration(
hintText: 'http://10.0.0.144:8090',
hintStyle: appStyle.fonts.B_14R.apply(
color: appStyle.colors.textTertiary,
),
),
),
],
),
actions: [
TextButton(
child: Text(
'Cancel',
style: appStyle.fonts.B_14R.apply(
color: appStyle.colors.textSecondary,
),
),
onPressed: () => Navigator.of(dialogContext).pop(false),
),
TextButton(
child: Text(
wasEnabled ? 'Disable' : 'Enable',
style: appStyle.fonts.B_14R.apply(color: appStyle.colors.accent),
),
onPressed: () => Navigator.of(dialogContext).pop(true),
),
],
);
},
);
if (confirmed != true) return;
if (!wasEnabled) {
await Settings.mockBackendUrl.set(urlController.text.trim());
}
await Settings.mockBackendEnabled.set(!wasEnabled);
if (!mounted) return;
setState(() {
_mockLoginError = null;
});
}
Future<void> _submitMockLogin() async {
setState(() {
_mockLoginInProgress = true;
_mockLoginError = null;
});
try {
final resp = await mockLogin(
_mockUsernameController.text,
_mockPasswordController.text,
);
await completeLogin(widget.data, resp);
if (!mounted) return;
appRouter?.go('/home');
} catch (ex) {
if (!mounted) return;
setState(() {
_mockLoginError = ex.toString();
});
} finally {
if (mounted) {
setState(() {
_mockLoginInProgress = false;
});
}
}
}
String _getPrivacyPolicyUrl() {
return "https://firka.app/privacy";
}
@@ -87,6 +215,143 @@ class _LoginScreenState extends FirkaState<LoginScreen> {
}
}
Widget _buildRealLoginButton() {
return InkWell(
onTap: () {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: false,
builder: (BuildContext context) {
return SizedBox(
height: MediaQuery.sizeOf(context).height,
child: _loginWebView,
);
},
);
},
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
height: 48,
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: ShapeDecoration(
color: appStyle.colors.accent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shadows: [
BoxShadow(
color: appStyle.colors.textPrimary.withAlpha(13),
blurRadius: 2,
offset: const Offset(0, 1),
spreadRadius: 0,
),
],
),
child: Center(
child: Text(
widget.data.l10n.loginBtn,
textAlign: TextAlign.center,
style: appStyle.fonts.H_16px.copyWith(
color: appStyle.colors.textPrimaryLight,
fontVariations: const [FontVariation("wght", 800)],
),
),
),
),
);
}
Widget _buildMockLoginField(
TextEditingController controller,
String hint, {
bool obscure = false,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
decoration: BoxDecoration(
color: appStyle.colors.card,
borderRadius: BorderRadius.circular(24),
),
child: TextField(
controller: controller,
obscureText: obscure,
textInputAction: TextInputAction.next,
cursorColor: appStyle.colors.accent,
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
decoration: InputDecoration(
hintText: hint,
hintStyle: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textTertiary,
),
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
),
);
}
Widget _buildMockLoginForm() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Mock mode, will connect to: ${Settings.mockBackendUrl.value.isEmpty ? "(not set, long-press the logo to disable then enable again and fill in the URL)" : Settings.mockBackendUrl.value}',
textAlign: TextAlign.center,
style: appStyle.fonts.B_12R.copyWith(
color: appStyle.colors.textTertiary,
),
),
const SizedBox(height: 8),
_buildMockLoginField(_mockUsernameController, 'Username'),
const SizedBox(height: 8),
_buildMockLoginField(
_mockPasswordController,
'Password',
obscure: true,
),
if (_mockLoginError != null) ...[
const SizedBox(height: 8),
Text(
_mockLoginError!,
textAlign: TextAlign.center,
style: appStyle.fonts.B_12R.copyWith(color: Colors.red),
),
],
const SizedBox(height: 8),
InkWell(
onTap: _mockLoginInProgress ? null : _submitMockLogin,
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
height: 48,
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: ShapeDecoration(
color: appStyle.colors.accent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: Center(
child: _mockLoginInProgress
? const DelayedSpinnerWidget()
: Text(
widget.data.l10n.loginBtn,
textAlign: TextAlign.center,
style: appStyle.fonts.H_16px.copyWith(
color: appStyle.colors.textPrimaryLight,
fontVariations: const [FontVariation("wght", 800)],
),
),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
if (!_preloadDone) {
@@ -176,33 +441,44 @@ class _LoginScreenState extends FirkaState<LoginScreen> {
const SizedBox(height: 16),
Padding(
padding: EdgeInsets.only(left: paddingWidthHorizontal),
child: Row(
children: [
Container(
width: 30,
height: 30,
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
image: DecorationImage(
image: PreloadedImageProvider(
DefaultAssetBundle.of(context),
'assets/images/logos/colored_logo.webp',
child: GestureDetector(
onLongPress: _showMockModeDialog,
behavior: HitTestBehavior.opaque,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 8,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 30,
height: 30,
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
image: DecorationImage(
image: PreloadedImageProvider(
DefaultAssetBundle.of(context),
'assets/images/logos/colored_logo.webp',
),
fit: BoxFit.cover,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
fit: BoxFit.cover,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
const SizedBox(width: 8),
Text(
'Firka Napló',
style: appStyle.fonts.H_18px.copyWith(
color: appStyle.colors.textPrimary,
),
),
),
],
),
const SizedBox(width: 8),
Text(
'Firka Napló',
style: appStyle.fonts.H_18px.copyWith(
color: appStyle.colors.textPrimary,
),
),
],
),
),
),
const SizedBox(height: 16),
@@ -459,61 +735,13 @@ class _LoginScreenState extends FirkaState<LoginScreen> {
right: 0,
child: Column(
children: [
Center(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: paddingWidthHorizontal,
),
child: InkWell(
onTap: () {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: false,
builder: (BuildContext context) {
return SizedBox(
height: MediaQuery.sizeOf(context).height,
child: _loginWebView,
);
},
);
},
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
height: 48,
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: ShapeDecoration(
color: appStyle.colors.accent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shadows: [
BoxShadow(
color: appStyle.colors.textPrimary.withAlpha(
13,
),
blurRadius: 2,
offset: const Offset(0, 1),
spreadRadius: 0,
),
],
),
child: Center(
child: Text(
widget.data.l10n.loginBtn,
textAlign: TextAlign.center,
style: appStyle.fonts.H_16px.copyWith(
color: appStyle.colors.textPrimaryLight,
fontVariations: const [
FontVariation("wght", 800),
],
),
),
),
),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: paddingWidthHorizontal,
),
child: Settings.mockBackendEnabled.value
? _buildMockLoginForm()
: _buildRealLoginButton(),
),
const SizedBox(height: 20),
GestureDetector(

View File

@@ -3,6 +3,7 @@ import "dart:io";
import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart";
import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
import "package:firka/services/fcm_service.dart";
import "package:firka/services/live_activity_service.dart";
import "package:firka/services/watch_sync_helper.dart";
import "package:firka/ui/shared/firka_icon.dart";
@@ -141,6 +142,7 @@ class SettingsAccountPickerView extends StatelessWidget {
}
final previousAccountId = data.client!.cache.token.key;
await FcmService.onUserLogout();
if (Platform.isIOS) {
await LiveActivityService.onUserLogout();
try {
@@ -162,6 +164,13 @@ class SettingsAccountPickerView extends StatelessWidget {
await data.settings.setSelectedAccountKey(token.key);
await initializeApp();
if (data.client != null) {
await FcmService.onUserLogin(
client: data.client!,
settingsStore: data.settings,
);
}
if (Platform.isIOS) {
var watchReachable = false;
try {
@@ -207,6 +216,7 @@ class SettingsAccountPickerView extends StatelessWidget {
Future<void> _logout(BuildContext context) async {
try {
await FcmService.onUserLogout();
if (Platform.isIOS) {
await LiveActivityService.onUserLogout();
}
@@ -229,6 +239,12 @@ class SettingsAccountPickerView extends StatelessWidget {
}
}
try {
await data.client!.cache.clearAccountData();
} catch (e) {
logger.warning('[Settings] Failed to clear cached data on logout: $e');
}
await data.isar.writeTxn(() async {
await data.isar.tokenModels.delete(active);
});
@@ -287,9 +303,10 @@ class SettingsAccountPickerView extends StatelessWidget {
await initializeApp();
if (!context.mounted) return;
final nav = Navigator.of(context);
if (nav.canPop()) nav.pop();
if (context.mounted) {
final nav = Navigator.of(context);
if (nav.canPop()) nav.pop();
}
if (accounts.isEmpty) {
appRouter?.go('/login');
} else {

View File

@@ -185,7 +185,7 @@ class SettingsAppIconPickerView extends StatelessWidget {
if (group == data.l10n.s_ci_icon_g7 || group == data.l10n.s_ci_icon_g8) {
pWidgets.add(SizedBox(height: 12));
pWidgets.add(
buildBoolRow(item.childProtection, settings, setStateOuter),
buildBoolRow(context, item.childProtection, settings, setStateOuter),
);
}

View File

@@ -1,19 +1,24 @@
import "package:firka/core/settings/settings_repository.dart";
import "package:firka/core/settings/settings_ui.dart";
import "package:firka/ui/phone/screens/settings/settings_metrics.dart";
import "package:firka/ui/phone/screens/settings/settings_toggle.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka_common/ui/components/firka_card.dart";
import "package:flutter/material.dart";
Widget buildBoolRow(
BuildContext context,
SettingsUiBoolean item,
SettingsRepository settings,
void Function(VoidCallback fn) setStateOuter,
) {
final value = settings.get(item.setting);
final scale = settingsScale(context);
return FirkaCard(
height: 52 + 12,
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
item.iconType != null
? Row(
@@ -23,7 +28,7 @@ Widget buildBoolRow(
item.iconData!,
color: appStyle.colors.accent,
),
SizedBox(width: 4),
SizedBox(width: 12 * scale),
],
)
: SizedBox(),
@@ -33,20 +38,9 @@ Widget buildBoolRow(
),
],
right: [
Switch(
SettingsToggle(
value: value,
thumbColor: WidgetStateProperty.fromMap({
WidgetState.selected: appStyle.colors.buttonSecondaryFill,
WidgetState.any: appStyle.colors.accent,
}),
trackColor: WidgetStateProperty.fromMap({
WidgetState.selected: appStyle.colors.accent,
WidgetState.any: appStyle.colors.a10p,
}),
trackOutlineColor: WidgetStateProperty.fromMap({
WidgetState.selected: appStyle.colors.accent,
WidgetState.any: appStyle.colors.a15p,
}),
scale: scale,
onChanged: (v) async {
await settings.set(item.setting, v);
setStateOuter(() {});

View File

@@ -0,0 +1,195 @@
import "package:firebase_messaging/firebase_messaging.dart";
import "package:flutter/material.dart";
import "package:majesticons_flutter/majesticons_flutter.dart";
import "package:firka/app/app_state.dart";
import "package:firka/core/last_seen_helper.dart";
import "package:firka/services/fcm_service.dart";
import "package:firka/services/notification_diff_service.dart";
import "package:firka/ui/phone/screens/settings/settings_metrics.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka_common/ui/components/firka_card.dart";
/// Read-only diagnostic panel for the developer settings screen: shows
/// whether FcmService has initialized, whether a token/permission is
/// present, which wakeup topic is currently subscribed, and when the token
/// last refreshed. Has its own refresh button since permission status is
/// read asynchronously and can change outside the app (system settings).
class SettingsFcmStatusView extends StatefulWidget {
final AppInitialization data;
const SettingsFcmStatusView({required this.data, super.key});
@override
State<SettingsFcmStatusView> createState() => _SettingsFcmStatusViewState();
}
class _SettingsFcmStatusViewState extends State<SettingsFcmStatusView> {
AuthorizationStatus? _permissionStatus;
bool _permissionLoaded = false;
@override
void initState() {
super.initState();
_loadPermissionStatus();
}
Future<void> _loadPermissionStatus() async {
final status = await FcmService.permissionStatus();
if (!mounted) return;
setState(() {
_permissionStatus = status;
_permissionLoaded = true;
});
}
String _permissionLabel() {
final l10n = widget.data.l10n;
if (!_permissionLoaded) return "…";
switch (_permissionStatus) {
case AuthorizationStatus.authorized:
case AuthorizationStatus.provisional:
return l10n.s_fcm_status_permission_granted;
case AuthorizationStatus.denied:
case AuthorizationStatus.deniedPermanently:
return l10n.s_fcm_status_permission_denied;
case AuthorizationStatus.notDetermined:
case null:
return l10n.s_fcm_status_permission_unknown;
}
}
List<(String kind, String label)> _testKinds() {
final l10n = widget.data.l10n;
return [
(LastSeenHelper.notifGrades, l10n.s_notif_grades),
(LastSeenHelper.notifHomework, l10n.s_notif_homework_tests),
(LastSeenHelper.notifTests, l10n.s_notif_homework_tests),
(LastSeenHelper.notifAbsences, l10n.s_notif_absences),
(LastSeenHelper.notifLessons, l10n.s_notif_lessons),
(LastSeenHelper.notifLessonsCancelled, l10n.s_notif_lessons_cancelled),
(LastSeenHelper.notifLessonsSubstituted, l10n.s_notif_lessons_substituted),
(LastSeenHelper.notifMessages, l10n.s_notif_messages),
];
}
Widget _testButton(String kind, String label, {bool simulateMultiAccount = false}) {
final scale = settingsScale(context);
return GestureDetector(
onTap: () => NotificationDiffService.showTestNotification(
kind,
simulateMultiAccount: simulateMultiAccount,
),
child: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.bellSolid,
color: appStyle.colors.accent,
),
const SizedBox(width: 8),
Text(
label,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
);
}
Widget _row(String label, String value) {
final scale = settingsScale(context);
return FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
Text(
label,
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
),
],
right: [
Text(
value,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textSecondary,
),
),
],
);
}
@override
Widget build(BuildContext context) {
final l10n = widget.data.l10n;
final scale = settingsScale(context);
final initialized = FcmService.isInitialized;
final token = FcmService.cachedToken;
final lastRefresh = FcmService.lastTokenRefreshAt;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_row(
l10n.s_fcm_status_title,
initialized
? l10n.s_fcm_status_initialized
: l10n.s_fcm_status_not_initialized,
),
_row(
token != null
? l10n.s_fcm_status_token_present
: l10n.s_fcm_status_token_missing,
token != null ? "...${token.substring(token.length - 6)}" : "-",
),
_row(l10n.s_fcm_status_permission_label, _permissionLabel()),
_row(l10n.s_fcm_status_topic_label, FcmService.subscribedTopic),
_row(
l10n.s_fcm_status_last_refresh_label,
lastRefresh?.toIso8601String() ?? l10n.s_fcm_status_last_refresh_never,
),
GestureDetector(
onTap: _loadPermissionStatus,
child: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.reloadSolid,
color: appStyle.colors.accent,
),
const SizedBox(width: 8),
Text(
l10n.s_fcm_status_refresh_button,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
),
const SizedBox(height: 12),
Text(
l10n.s_fcm_test_notifications_title,
style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary),
),
for (final (kind, label) in _testKinds()) _testButton(kind, label),
const SizedBox(height: 12),
Text(
l10n.s_fcm_test_notifications_multi_title,
style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary),
),
for (final (kind, label) in _testKinds())
_testButton(kind, label, simulateMultiAccount: true),
],
);
}
}

View File

@@ -0,0 +1,8 @@
import "package:flutter/widgets.dart";
const settingsDesignWidth = 376.0;
const settingsItemHeight = 56.0;
const settingsItemRounding = 16.0;
double settingsScale(BuildContext context) =>
MediaQuery.sizeOf(context).width / settingsDesignWidth;

View File

@@ -10,8 +10,6 @@ import "package:firka/l10n/app_localizations.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka_common/ui/components/firka_card.dart";
import "package:firka_common/ui/theme/core_theme.dart";
import "package:firka_common/ui/theme/grade_theme.dart";
import "package:flutter/material.dart";
import "package:flutter_bloc/flutter_bloc.dart";
import "package:go_router/go_router.dart";
@@ -127,66 +125,23 @@ class _SettingsPersonalizationViewState
);
}
List<Color> _coreSwatch(CoreThemeColors colors) {
return [
colors.secondary,
colors.accent,
colors.background,
colors.card,
];
}
List<Color> _gradeSwatch(GradeThemeColors colors) {
return [
colors.grade5,
colors.grade4,
colors.grade3,
colors.grade2,
colors.grade1,
];
}
Widget _coreThemePager() {
final cores = coreThemes.values.toList(growable: false);
final selectedId = _settings.get(SettingsRegistry.selectedCoreThemeId);
var selectedIndex = cores.indexWhere((theme) => theme.id == selectedId);
if (selectedIndex < 0) selectedIndex = 0;
return _PresetSwatchPager(
key: const ValueKey("core-themes"),
swatches: [
for (final core in cores)
_coreSwatch(core.forBrightness(appStyle.isLight)),
],
selectedIndex: selectedIndex,
onSelected: (index) async {
await _settings.set(
SettingsRegistry.selectedCoreThemeId,
cores[index].id,
);
},
);
}
Widget _gradeThemePager() {
final grades = gradeThemes.values.toList(growable: false);
final selectedId = _settings.get(SettingsRegistry.selectedGradeThemeId);
var selectedIndex = grades.indexWhere((theme) => theme.id == selectedId);
if (selectedIndex < 0) selectedIndex = 0;
return _PresetSwatchPager(
key: const ValueKey("grade-themes"),
swatches: [
for (final grade in grades)
_gradeSwatch(grade.forBrightness(appStyle.isLight)),
],
selectedIndex: selectedIndex,
onSelected: (index) async {
await _settings.set(
SettingsRegistry.selectedGradeThemeId,
grades[index].id,
);
},
Widget _swatchPreview(List<Color> colors) {
return FirkaCard.single(
width: double.infinity,
padding: EdgeInsets.zero,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: SizedBox(
height: 88,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final color in colors)
Expanded(child: ColoredBox(color: color)),
],
),
),
),
);
}
@@ -612,14 +567,25 @@ class _SettingsPersonalizationViewState
},
),
_sectionLabel(_l10n.s_c_colors_header),
_coreThemePager(),
_swatchPreview([
appStyle.colors.secondary,
appStyle.colors.accent,
appStyle.colors.background,
appStyle.colors.card,
]),
_stubCustomizeButton(),
_sectionLabel(_l10n.s_c_theme_header),
_themeOption(_l10n.s_c_theme_auto, ThemeBrightness.auto),
_themeOption(_l10n.s_c_theme_light, ThemeBrightness.light),
_themeOption(_l10n.s_c_theme_dark, ThemeBrightness.dark),
_sectionLabel(_l10n.s_c_grade_colors_header),
_gradeThemePager(),
_swatchPreview([
appStyle.colors.grade5,
appStyle.colors.grade4,
appStyle.colors.grade3,
appStyle.colors.grade2,
appStyle.colors.grade1,
]),
_stubCustomizeButton(),
_sectionLabel(_l10n.s_c_title_style_header),
_fontPicker(selectedFont),
@@ -633,165 +599,3 @@ class _SettingsPersonalizationViewState
);
}
}
class _PresetSwatchPager extends StatefulWidget {
final List<List<Color>> swatches;
final int selectedIndex;
final ValueChanged<int> onSelected;
const _PresetSwatchPager({
super.key,
required this.swatches,
required this.selectedIndex,
required this.onSelected,
});
@override
State<_PresetSwatchPager> createState() => _PresetSwatchPagerState();
}
class _PresetSwatchPagerState extends State<_PresetSwatchPager> {
late final PageController _controller;
@override
void initState() {
super.initState();
_controller = PageController(initialPage: widget.selectedIndex);
}
@override
void didUpdateWidget(_PresetSwatchPager oldWidget) {
super.didUpdateWidget(oldWidget);
if (!_controller.hasClients) return;
if (widget.selectedIndex == oldWidget.selectedIndex) return;
if (_controller.page?.round() == widget.selectedIndex) return;
_controller.animateToPage(
widget.selectedIndex,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Color _accentFor(double page) {
final index = page.round().clamp(0, widget.swatches.length - 1);
final swatch = widget.swatches[index];
if (swatch.length > 1) return swatch[1];
return appStyle.colors.accent;
}
@override
Widget build(BuildContext context) {
return FirkaCard.single(
width: double.infinity,
height: 88,
padding: EdgeInsets.zero,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Stack(
fit: StackFit.expand,
children: [
PageView.builder(
controller: _controller,
itemCount: widget.swatches.length,
physics: widget.swatches.length <= 1
? const NeverScrollableScrollPhysics()
: null,
onPageChanged: (index) {
if (index == widget.selectedIndex) return;
widget.onSelected(index);
},
itemBuilder: (context, index) {
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final color in widget.swatches[index])
Expanded(child: ColoredBox(color: color)),
],
);
},
),
if (widget.swatches.length > 1)
Positioned(
left: 0,
right: 0,
bottom: 8,
child: IgnorePointer(
child: AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final page = _controller.hasClients
? (_controller.page ??
widget.selectedIndex.toDouble())
: widget.selectedIndex.toDouble();
return Center(
child: _SwatchPageDots(
count: widget.swatches.length,
page: page,
accent: _accentFor(page),
),
);
},
),
),
),
],
),
),
);
}
}
class _SwatchPageDots extends StatelessWidget {
final int count;
final double page;
final Color accent;
const _SwatchPageDots({
required this.count,
required this.page,
required this.accent,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
decoration: BoxDecoration(
color: const Color(0xCCFFFFFF),
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var i = 0; i < count; i++) ...[
if (i > 0) const SizedBox(width: 5),
_dot(i),
],
],
),
);
}
Widget _dot(int index) {
final t = (1 - (index - page).abs()).clamp(0.0, 1.0);
final size = 5.0 + 3.0 * t;
return Container(
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color.lerp(
accent.withValues(alpha: 0.28),
accent,
t,
),
),
);
}
}

View File

@@ -24,6 +24,8 @@ import 'package:firka/core/state/firka_state.dart';
import 'settings_account_picker.dart';
import 'settings_app_icon_picker.dart';
import 'settings_bool_row.dart';
import 'settings_fcm_status.dart';
import 'settings_metrics.dart';
import 'settings_license_page.dart';
import 'settings_logs.dart';
import 'settings_personalization_view.dart';
@@ -77,6 +79,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
bool forceRender = false,
}) {
var widgets = List<Widget>.empty(growable: true);
final scale = settingsScale(context);
for (var item in items) {
if (!forceRender && !item.visible()) continue;
@@ -93,34 +96,38 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
if (item is SettingsUiBackHeader) {
widgets.add(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Transform.translate(
offset: const Offset(-4, 0),
child: GestureDetector(
child: FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.chevronLeftLine,
color: appStyle.colors.textSecondary,
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => Navigator.of(context).pop(),
child: Padding(
padding: const EdgeInsets.fromLTRB(4, 8, 16, 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Transform.translate(
offset: const Offset(-8, 0),
child: FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.chevronLeftLine,
color: appStyle.colors.textSecondary,
),
),
onTap: () {
Navigator.of(context).pop();
},
),
),
Transform.translate(
offset: const Offset(-4, 1),
child: Text(
item.title,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
Transform.translate(
offset: const Offset(-8, 1),
child: Text(
item.title,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
),
),
),
),
],
),
],
),
),
SizedBox(height: 13),
SizedBox(height: 5),
],
),
);
@@ -174,21 +181,42 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
color: appStyle.colors.accent,
),
);
cardWidgets.add(SizedBox(width: 8));
cardWidgets.add(SizedBox(width: 12 * scale));
}
cardWidgets.add(
Text(
item.title,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
item.subtitle == null
? Text(
item.title,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
spacing: 2,
children: [
Text(
item.title,
style: appStyle.fonts.B_16SB
.apply(color: appStyle.colors.textPrimary)
.copyWith(height: 1.1),
),
Text(
item.subtitle!,
style: appStyle.fonts.B_14R
.apply(color: appStyle.colors.textSecondary)
.copyWith(height: 1.1),
),
],
),
);
widgets.add(
GestureDetector(
onTap: () {
if (item.children.isEmpty && item.redirectTo == null) return;
if (item.redirectTo != null && item.redirectTo == "discord") {
launchUrlString(
"https://discord.com/invite/firka-1111649116020285532",
@@ -204,6 +232,8 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
},
child: item.redirectTo != null
? FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: cardWidgets,
right: [
RotationTransition(
@@ -217,7 +247,11 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
),
],
)
: FirkaCard(left: cardWidgets),
: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: cardWidgets,
),
),
);
@@ -231,7 +265,8 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
widgets.add(
GestureDetector(
child: FirkaCard(
height: 52 + 12,
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
item.iconType != null
? Row(
@@ -270,7 +305,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
continue;
}
if (item is SettingsUiBoolean) {
widgets.add(buildBoolRow(item, settings, setState));
widgets.add(buildBoolRow(context, item, settings, setState));
continue;
}
@@ -282,7 +317,8 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
if (i == activeIndex) {
widgets.add(
FirkaCard(
height: 52 + 12,
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
Text(
k,
@@ -320,7 +356,8 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
widgets.add(
GestureDetector(
child: FirkaCard(
height: 52 + 12,
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
Text(
k,
@@ -388,6 +425,8 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
widgets.add(
GestureDetector(
child: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
item.iconType != null
? Row(
@@ -421,6 +460,10 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
widgets.add(SettingsLogsView(data: widget.data));
continue;
}
if (item is SettingsUiFcmStatus) {
widgets.add(SettingsFcmStatusView(data: widget.data));
continue;
}
}
return widgets;
@@ -437,21 +480,16 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
child: Scaffold(
backgroundColor: appStyle.colors.background,
body: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: Stack(
children: [
Padding(
padding: EdgeInsetsGeometry.all(20),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: body,
),
),
child: Stack(
children: [
SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: body,
),
],
),
),
],
),
),
),

View File

@@ -0,0 +1,63 @@
import "package:firka/ui/theme/style.dart";
import "package:flutter/material.dart";
class SettingsToggle extends StatelessWidget {
static const _designWidth = 40.0;
static const _designHeight = 24.0;
static const _designKnob = 20.0;
final bool value;
final double scale;
final ValueChanged<bool> onChanged;
const SettingsToggle({
required this.value,
required this.onChanged,
this.scale = 1,
super.key,
});
@override
Widget build(BuildContext context) {
final width = _designWidth * scale;
final height = _designHeight * scale;
final knob = _designKnob * scale;
final inset = (height - knob) / 2;
return GestureDetector(
onTap: () => onChanged(!value),
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
curve: Curves.easeOut,
width: width,
height: height,
decoration: BoxDecoration(
color: value ? appStyle.colors.accent : appStyle.colors.a15p,
borderRadius: BorderRadius.circular(height / 2),
),
child: Stack(
children: [
AnimatedAlign(
duration: const Duration(milliseconds: 150),
curve: Curves.easeOut,
alignment: value ? Alignment.centerRight : Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: inset),
child: Container(
width: knob,
height: knob,
decoration: BoxDecoration(
color: value
? appStyle.colors.buttonSecondaryFill
: appStyle.colors.accent,
shape: BoxShape.circle,
),
),
),
),
],
),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,6 @@ class ThemePreviewData {
required this.messages,
required this.tests,
required this.grades,
required this.chartGrades,
required this.omissions,
required this.omissionBarSegments,
required this.omissionExcusedCount,
@@ -39,7 +38,6 @@ class ThemePreviewData {
final List<MessageCacheModel> messages;
final List<TestCacheModel> tests;
final List<GradeCacheModel> grades;
final List<GradeCacheModel> chartGrades;
final List<OmissionCacheModel> omissions;
final List<OmissionState?> omissionBarSegments;
final int omissionExcusedCount;
@@ -145,7 +143,6 @@ class ThemePreviewData {
start: ttBase.add(const Duration(minutes: 55)),
end: ttBase.add(const Duration(minutes: 100)),
roomName: "123",
type: "UresOra",
test: testLektion,
),
_lesson(
@@ -210,31 +207,6 @@ class ThemePreviewData {
_grade(509, matematika, 5, midnight.subtract(const Duration(days: 15))),
];
final sept = DateTime(
day.month >= DateTime.september ? day.year : day.year - 1,
DateTime.september,
15,
);
final chartSpanDays = day.difference(sept).inDays.clamp(1, 365);
const chartValues = [
1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 3, 3, 4, 4, 4, 4, 5, 5,
5, 4, 4, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
];
final chartGrades = [
for (var i = 0; i < chartValues.length; i++)
_grade(
700 + i,
matematika,
chartValues[i],
sept.add(
Duration(days: (i * chartSpanDays / (chartValues.length - 1)).round()),
),
),
];
final omissions = [
_omission(
601,
@@ -345,7 +317,6 @@ class ThemePreviewData {
messages: messages,
tests: [homeTest],
grades: grades,
chartGrades: chartGrades,
omissions: omissions,
omissionBarSegments: omissionBarSegments,
omissionExcusedCount: 2,
@@ -375,7 +346,6 @@ class ThemePreviewData {
required DateTime end,
required String roomName,
String? substituteTeacher,
String type = "OrarendiOra",
TestCacheModel? test,
}) {
final lesson = LessonCacheModel()
@@ -388,7 +358,7 @@ class ThemePreviewData {
..name = subject.name
..roomName = roomName
..state = "Naplozott"
..type = type
..type = "OrarendiOra"
..teacher = "Tanár"
..substituteTeacher = substituteTeacher;
lesson.subject.value = subject;
@@ -408,9 +378,8 @@ class ThemePreviewData {
int id,
SubjectCacheModel subject,
int value,
DateTime at, {
int? weightPercentage = 100,
}) {
DateTime at,
) {
final grade = GradeCacheModel()
..cacheKey = id
..createdAt = at
@@ -420,7 +389,7 @@ class ThemePreviewData {
..valueType = "Osztalyzat"
..writtenAt = at
..numericValue = value
..weightPercentage = weightPercentage
..weightPercentage = 100
..textValue = value.toString()
..teacherName = "Tanár";
grade.subject.value = subject;

View File

@@ -167,9 +167,9 @@ class ThemePreviewHomeGrades extends StatelessWidget {
),
),
const SizedBox(height: 20),
GradeChart(grades: preview.chartGrades, plotRawValues: true),
GradeChart(grades: allGrades),
const SizedBox(height: 10),
GradeSummaryBar(grades: preview.chartGrades, l10n: data.l10n),
GradeSummaryBar(grades: allGrades, l10n: data.l10n),
const SizedBox(height: 20),
Expanded(
child: ListView(

View File

@@ -13,12 +13,10 @@ import 'package:flutter/material.dart';
class GradeChart extends StatefulWidget {
final List<GradeCacheModel> grades;
final bool halfYearFallback;
final bool plotRawValues;
GradeChart({
super.key,
required List<GradeCacheModel> grades,
this.halfYearFallback = true,
this.plotRawValues = false,
}) : grades = grades.where((g) => g.hasClassicValue()).toList()
..sort((a, b) => a.writtenAt.compareTo(b.writtenAt));
@@ -51,21 +49,19 @@ class _GradeChartState extends State<GradeChart> {
void _computeSpots() {
spots = [];
if (!widget.plotRawValues) {
for (var i = 0; i < widget.grades.length; i++) {
final grade = widget.grades[i];
if (!grade.shouldIncludeInAverage()) {
continue;
}
final partialAvg = widget.grades
.take(i + 1)
.getSubjectAverage(halfYearFallback: widget.halfYearFallback);
spots.add(
DateSpot(spots.length.toDouble(), partialAvg!, grade.writtenAt),
);
for (var i = 0; i < widget.grades.length; i++) {
final grade = widget.grades[i];
if (!grade.shouldIncludeInAverage()) {
continue;
}
final partialAvg = widget.grades
.take(i + 1)
.getSubjectAverage(halfYearFallback: widget.halfYearFallback);
spots.add(
DateSpot(spots.length.toDouble(), partialAvg!, grade.writtenAt),
);
}
if (spots.isEmpty) {

View File

@@ -0,0 +1,97 @@
import 'dart:math';
import 'package:firka/l10n/app_localizations.dart';
import 'package:firka/ui/phone/screens/surprise_grades/surprise_grades_screen.dart';
import 'package:firka/ui/theme/style.dart';
import 'package:firka_common/data/models/grade_cache_model.dart';
import 'package:firka_common/ui/components/firka_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
const _cardIcon = "assets/images/surprise_grades/play_card_star.svg";
class NewGradesWidget extends StatelessWidget {
static const _designWidth = 336.0;
static const _miniWidth = 90.117;
static const _tilt = 15 * pi / 180;
static const _slots = [
(172.04, 46.86, -_tilt, 1),
(302.63, 20.32, _tilt, 2),
(222.92, 9.0, 0.0, 0),
];
final AppLocalizations l10n;
final List<GradeCacheModel> grades;
final VoidCallback? onTap;
const NewGradesWidget(this.l10n, this.grades, {this.onTap, super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: FirkaCard.single(
margin: EdgeInsets.only(bottom: 1),
padding: EdgeInsets.zero,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: LayoutBuilder(
builder: (context, constraints) {
final s = constraints.maxWidth / _designWidth;
return Stack(
clipBehavior: Clip.hardEdge,
children: [
for (final (left, top, angle, index) in _slots)
if (index < grades.length)
Positioned(
left: left * s,
top: top * s,
child: Transform.rotate(
angle: angle,
child: SurpriseGradeMiniCard(
grades[index],
l10n,
width: _miniWidth * s,
),
),
),
Positioned(left: 16 * s, top: 16 * s, child: _icon(s)),
Positioned(
left: 16 * s,
top: 67 * s,
child: Text(
l10n.new_grades_card,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
),
],
);
},
),
),
),
);
}
Widget _icon(double s) {
return Container(
width: 32 * s,
height: 32 * s,
decoration: BoxDecoration(
color: appStyle.colors.a15p,
borderRadius: BorderRadius.circular(16 * s),
),
alignment: Alignment.center,
child: SvgPicture.asset(
_cardIcon,
width: 20 * s,
height: 20 * s,
color: appStyle.colors.accent,
),
);
}
}

View File

@@ -1,242 +1,293 @@
import 'dart:async';
import 'dart:collection';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:firka_common/core/consts.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/core/extensions.dart';
import 'package:firka/ui/phone/widgets/home_main_starting_soon.dart';
import 'package:firka/ui/phone/widgets/lesson_big.dart';
import 'package:firka/ui/shared/firka_icon.dart';
import 'package:firka_common/core/debug_helper.dart';
import 'package:firka_common/data/models/lesson_cache_model.dart';
import 'package:firka_common/ui/components/filled_circle.dart';
import 'package:firka_common/ui/components/firka_card.dart';
import 'package:firka_common/ui/theme/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:majesticons_flutter/majesticons_flutter.dart';
class _LessonSliderState extends State<LessonSlider> {
DateTime now = timeNow();
int? swipeBack;
late Timer timer;
int? activeLessonIndex;
int? centeredPageIndex;
CarouselSliderController controller = CarouselSliderController();
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (timer) async {
if (widget.lessons.isEmpty || !mounted) return;
setState(() {
if (swipeBack != null) swipeBack = swipeBack! - 1;
now = timeNow();
});
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.lessons.isEmpty) {
return SizedBox();
}
LessonCacheModel? currentLesson;
int tmpIndex;
if (now.isBefore(widget.lessons.first.start)) {
tmpIndex = 0;
} else {
(int, LessonCacheModel)? currentIndex = widget.lessons.indexed
.firstWhereOrNull((e) => now.isBefore(e.$2.end));
tmpIndex = (currentIndex?.$1 ?? widget.lessons.length) + 1;
if (currentIndex != null) {
currentLesson = currentIndex.$2;
}
}
if (activeLessonIndex == null || tmpIndex != activeLessonIndex) {
activeLessonIndex = tmpIndex;
swipeBack = 0;
}
centeredPageIndex ??= activeLessonIndex!;
if (controller.ready && swipeBack == 0) {
controller.animateToPage(activeLessonIndex!);
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
spacing: 12,
children: [
OverflowBox(
maxWidth: MediaQuery.widthOf(context),
fit: OverflowBoxFit.deferToChild,
child: CarouselSlider(
items: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: StartingSoonWidget(initData.l10n, now, widget.lessons),
),
...widget.lessons.map(
(entry) => Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: LessonBigWidget(
initData,
entry,
active: currentLesson == entry,
),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: FirkaCard.single(
padding: EdgeInsets.all(16),
margin: EdgeInsets.only(bottom: 1),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
FilledCircle(
diameter: 32,
color: appStyle.colors.a15p,
child: FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.moonSolid,
size: 20,
color: appStyle.colors.accent,
),
),
SizedBox(width: 8),
Text(
widget.tomorrowTestAmount == 0
? initData.l10n.tt_no_classes_l2
: initData.l10n.get_ready,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
Container(
height: 28,
padding: EdgeInsets.symmetric(horizontal: 6),
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
color: appStyle.colors.background,
),
child: Row(
children: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.editPen4Solid,
size: 12,
color: appStyle.colors.accent,
),
SizedBox(width: 8),
Text(
widget.tomorrowTestAmount == 0
? initData.l10n.no_tests_tomorrow
: initData.l10n.tests_tomorrow(
widget.tomorrowTestAmount.toString(),
),
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
),
],
),
),
),
],
carouselController: controller,
options: CarouselOptions(
initialPage: activeLessonIndex!,
height: 106,
viewportFraction: 346 / 376,
enableInfiniteScroll: false,
onPageChanged: (index, reason) {
centeredPageIndex = index;
if (index == activeLessonIndex) {
swipeBack = null;
} else if (reason == CarouselPageChangedReason.manual) {
swipeBack = 5;
} else {
return;
}
setState(() {});
},
),
),
),
SizedBox(
height: 16,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
spacing: 8,
children: [
FirkaIconWidget(
FirkaIconType.majesticonsLocal,
"sunSolid",
color: centeredPageIndex == 0
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
size: centeredPageIndex == 0 ? 16 : 12,
),
...widget.lessons.indexed.map(
(i) => FilledCircle(
diameter: centeredPageIndex == i.$1 + 1 ? 10 : 8,
color: centeredPageIndex == i.$1 + 1
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
child: SizedBox(),
),
),
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.moonSolid,
color: centeredPageIndex == widget.lessons.length + 1
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
size: centeredPageIndex == widget.lessons.length + 1 ? 16 : 12,
),
],
),
),
],
);
}
}
class LessonSlider extends StatefulWidget {
final List<LessonCacheModel> lessons;
final int tomorrowTestAmount;
LessonSlider(
Iterable<LessonCacheModel> lessons,
this.tomorrowTestAmount, {
super.key,
}) : lessons = lessons
.where(((l) => l.type != TimetableConsts.event))
.toList();
@override
State<StatefulWidget> createState() => _LessonSliderState();
}
import 'dart:async';
import 'dart:collection';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:firka_common/core/consts.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/core/extensions.dart';
import 'package:firka/routing/chart_interaction_scope.dart';
import 'package:firka/ui/phone/widgets/home_main_new_grades.dart';
import 'package:firka/ui/phone/widgets/home_main_starting_soon.dart';
import 'package:firka/ui/phone/widgets/lesson_big.dart';
import 'package:firka/ui/shared/firka_icon.dart';
import 'package:firka_common/core/debug_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/ui/components/filled_circle.dart';
import 'package:firka_common/ui/components/firka_card.dart';
import 'package:firka_common/ui/theme/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:majesticons_flutter/majesticons_flutter.dart';
class _LessonSliderState extends State<LessonSlider> {
DateTime now = timeNow();
int? swipeBack;
late Timer timer;
int? activeLessonIndex;
int? centeredPageIndex;
CarouselSliderController controller = CarouselSliderController();
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (timer) async {
if (widget.lessons.isEmpty || !mounted) return;
setState(() {
if (swipeBack != null) swipeBack = swipeBack! - 1;
now = timeNow();
});
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final hasNewGrades = widget.newGrades.isNotEmpty;
final hasLessons = widget.lessons.isNotEmpty;
if (!hasNewGrades && !hasLessons) {
return SizedBox();
}
final offset = hasNewGrades ? 1 : 0;
LessonCacheModel? currentLesson;
int tmpIndex;
if (!hasLessons) {
tmpIndex = 0;
} else if (now.isBefore(widget.lessons.first.start)) {
tmpIndex = 0;
} else {
(int, LessonCacheModel)? currentIndex = widget.lessons.indexed
.firstWhereOrNull((e) => now.isBefore(e.$2.end));
tmpIndex = (currentIndex?.$1 ?? widget.lessons.length) + 1;
if (currentIndex != null) {
currentLesson = currentIndex.$2;
}
}
if (activeLessonIndex == null || tmpIndex != activeLessonIndex) {
activeLessonIndex = tmpIndex;
swipeBack = 0;
}
final initialPage = hasNewGrades ? 0 : activeLessonIndex!;
centeredPageIndex ??= initialPage;
if (controller.ready && swipeBack == 0 && !hasNewGrades) {
controller.animateToPage(activeLessonIndex!);
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
spacing: 12,
children: [
OverflowBox(
maxWidth: MediaQuery.widthOf(context),
fit: OverflowBoxFit.deferToChild,
child: Listener(
behavior: HitTestBehavior.deferToChild,
onPointerDown: (_) =>
ChartInteractionScope.of(context).value = true,
onPointerUp: (_) => ChartInteractionScope.of(context).value = false,
onPointerCancel: (_) =>
ChartInteractionScope.of(context).value = false,
child: CarouselSlider(
items: [
if (hasNewGrades)
Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: NewGradesWidget(
initData.l10n,
widget.newGrades,
onTap: widget.onNewGradesTap,
),
),
if (hasLessons)
Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: StartingSoonWidget(
initData.l10n,
now,
widget.lessons,
),
),
...widget.lessons.map(
(entry) => Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: LessonBigWidget(
initData,
entry,
active: currentLesson == entry,
),
),
),
if (hasLessons)
Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: FirkaCard.single(
padding: EdgeInsets.all(16),
margin: EdgeInsets.only(bottom: 1),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
FilledCircle(
diameter: 32,
color: appStyle.colors.a15p,
child: FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.moonSolid,
size: 20,
color: appStyle.colors.accent,
),
),
SizedBox(width: 8),
Text(
widget.tomorrowTestAmount == 0
? initData.l10n.tt_no_classes_l2
: initData.l10n.get_ready,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
Container(
height: 28,
padding: EdgeInsets.symmetric(horizontal: 6),
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
color: appStyle.colors.background,
),
child: Row(
children: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.editPen4Solid,
size: 12,
color: appStyle.colors.accent,
),
SizedBox(width: 8),
Text(
widget.tomorrowTestAmount == 0
? initData.l10n.no_tests_tomorrow
: initData.l10n.tests_tomorrow(
widget.tomorrowTestAmount.toString(),
),
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
),
],
),
),
),
],
carouselController: controller,
options: CarouselOptions(
initialPage: initialPage,
height: 106,
viewportFraction: 346 / 376,
enableInfiniteScroll: false,
onPageChanged: (index, reason) {
centeredPageIndex = index;
if (index == activeLessonIndex! + offset) {
swipeBack = null;
} else if (reason == CarouselPageChangedReason.manual) {
swipeBack = 5;
} else {
return;
}
setState(() {});
},
),
),
),
),
SizedBox(
height: 16,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
spacing: 8,
children: [
if (hasNewGrades)
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.shootingStarSolid,
color: centeredPageIndex == 0
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
size: centeredPageIndex == 0 ? 16 : 12,
),
if (hasLessons) ...[
FirkaIconWidget(
FirkaIconType.majesticonsLocal,
"sunSolid",
color: centeredPageIndex == offset
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
size: centeredPageIndex == offset ? 16 : 12,
),
...widget.lessons.indexed.map(
(i) => FilledCircle(
diameter: centeredPageIndex == i.$1 + 1 + offset ? 10 : 8,
color: centeredPageIndex == i.$1 + 1 + offset
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
child: SizedBox(),
),
),
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.moonSolid,
color: centeredPageIndex == widget.lessons.length + 1 + offset
? appStyle.colors.accent
: appStyle.colors.accent.withAlpha(128),
size: centeredPageIndex == widget.lessons.length + 1 + offset
? 16
: 12,
),
],
],
),
),
],
);
}
}
class LessonSlider extends StatefulWidget {
final List<LessonCacheModel> lessons;
final int tomorrowTestAmount;
final List<GradeCacheModel> newGrades;
final VoidCallback? onNewGradesTap;
LessonSlider(
Iterable<LessonCacheModel> lessons,
this.tomorrowTestAmount, {
this.newGrades = const [],
this.onNewGradesTap,
super.key,
}) : lessons = lessons
.where(((l) => l.type != TimetableConsts.event))
.toList();
@override
State<StatefulWidget> createState() => _LessonSliderState();
}

View File

@@ -1,9 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:firka_common/core/consts.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/app/initialization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
@@ -11,9 +9,9 @@ import 'package:flutter_svg/svg.dart';
import 'package:majesticons_flutter/majesticons_flutter.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:firka/services/watch_sync_helper.dart';
import 'package:firka/api/login_finish.dart';
import 'package:firka/api/token_grant.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:firka/core/dev/mock_backend.dart';
import 'package:firka/core/state/firka_state.dart';
import 'package:firka/ui/theme/style.dart';
@@ -65,6 +63,8 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
);
}
loginUrl = MockBackend.rewrite(loginUrl);
final trimmed = loginUrl.replaceFirst(RegExp(r'^https?://'), '');
final parts = trimmed.split('/');
_displayHost = parts.isNotEmpty ? parts.first : trimmed;
@@ -102,37 +102,11 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
var code = uri.queryParameters["code"]!;
try {
var isar = widget.data.isar;
var resp = await getAccessToken(code);
logger.info("getAccessToken(): $resp");
var tokenModel = TokenModel.fromResp(resp);
await isar.writeTxn(() async {
await isar.tokenModels.put(tokenModel);
});
await widget.data.settings.setSelectedAccountKey(
tokenModel.key,
);
await initializeApp();
if (Platform.isIOS) {
final watchInstalled =
await WatchSyncHelper.isWatchAppInstalled();
if (watchInstalled) {
try {
await WatchSyncHelper.saveTokenToiCloud(tokenModel);
} catch (_) {}
try {
await WatchSyncHelper.sendTokenToWatch();
} catch (_) {
// Watch may be unavailable, ignore
}
}
}
await completeLogin(widget.data, resp);
if (!mounted) return NavigationDecision.prevent;

View File

@@ -17,6 +17,9 @@ dependencies:
cupertino_icons: ^1.0.8
flutter_launcher_icons: ^0.14.3
firebase_core: ^4.1.1
firebase_messaging: ^16.0.2
flutter_local_notifications: ^18.0.1
dio: ^5.8.0+1
isar_community: 3.3.0
isar_community_flutter_libs: 3.3.0
@@ -96,6 +99,7 @@ flutter:
- assets/images/cactus_error_screen.png
- assets/images/logos/dave_error.png
- assets/icons/button/colorwheel.png
- assets/images/surprise_grades/
fonts:
- family: Montserrat
@@ -132,4 +136,5 @@ flutter:
style: normal
dependency_overrides:
html: 0.15.6
vector_math: ^2.2.0

View File

@@ -9,6 +9,7 @@ const _lockFileName = 'codegen-lock.yaml';
void main() async {
final root = _projectRoot();
print(root);
var ran = false;
if (_iconsOutOfDate(root)) {
@@ -56,14 +57,15 @@ void main() async {
ran = true;
}
if (_isarOutOfDate(root) || _isarGeneratedFilesMissing(root)) {
final inputs = _isarInputs(root);
final hashes = _computeHashes(root, inputs);
var common = p.join(p.dirname(root), "firka_common");
if (_isarOutOfDate(common) || _isarGeneratedFilesMissing(common)) {
final inputs = _isarInputs(common);
final hashes = _computeHashes(common, inputs);
stdout.writeln(
'Isar generated dart files out of date or missing, running build_runner...',
);
await _run('dart', ['run', 'build_runner', 'build'], root);
_updateLockWithHashes(root, 'isar', hashes);
await _run('dart', ['run', 'build_runner', 'build'], common);
_updateLockWithHashes(common, 'isar', hashes);
ran = true;
}

View File

@@ -107,6 +107,26 @@ class CacheManager {
);
}
Future<void> clearAccountData() async {
await isarInit.writeTxn(() async {
await getGrades().deleteAll();
await getHomeworks().deleteAll();
await getTests().deleteAll();
await getOmissions().deleteAll();
await getTimeTable().deleteAll();
await getClassAverages().deleteAll();
await getMessages().deleteAll();
await isarInit.classGroupCacheModels
.filter()
.group(isCurrentClassGroup)
.deleteAll();
await isarInit.studentCacheModels
.filter()
.group(isCurrentStudent)
.deleteAll();
});
}
void resolveTeachers() {
Set<TeacherModel> teachers = HashSet<TeacherModel>(
equals: (t, t2) =>

View File

@@ -0,0 +1,51 @@
import 'package:firka_common/data/models/generic_cache_model.dart';
class LastSeen {
final DateTime createdAt;
final int cacheKey;
const LastSeen(this.createdAt, this.cacheKey);
static LastSeen? parse(String? raw) {
if (raw == null || raw.isEmpty) return null;
final parts = raw.split(":");
if (parts.length != 2) return null;
final millis = int.tryParse(parts[0]);
final key = int.tryParse(parts[1]);
if (millis == null || key == null) return null;
return LastSeen(DateTime.fromMillisecondsSinceEpoch(millis), key);
}
static LastSeen? newestOf(Iterable<GenericCacheModel> items) {
LastSeen? newest;
for (final item in items) {
final seen = LastSeen(item.createdAt, item.cacheKey);
if (newest == null || seen.isAfter(newest)) newest = seen;
}
return newest;
}
static List<T> newerThan<T extends GenericCacheModel>(
Iterable<T> items,
LastSeen? seen,
) {
if (seen == null) return items.toList();
return items
.where((i) => LastSeen(i.createdAt, i.cacheKey).isAfter(seen))
.toList();
}
bool isAfter(LastSeen other) {
if (createdAt.isAfter(other.createdAt)) return true;
if (createdAt.isAtSameMomentAs(other.createdAt)) {
return cacheKey > other.cacheKey;
}
return false;
}
String toText() => "${createdAt.millisecondsSinceEpoch}:$cacheKey";
}

View File

@@ -14,6 +14,7 @@ class FirkaCard extends StatelessWidget {
final Attach attached;
final Color? color;
final bool? isLightMode;
final double? rounding;
final Widget child;
factory FirkaCard({
@@ -29,6 +30,7 @@ class FirkaCard extends StatelessWidget {
double? height,
double? width,
bool? isLightMode,
double? rounding,
}) {
final leftRow = Row(children: left);
@@ -50,6 +52,7 @@ class FirkaCard extends StatelessWidget {
height: height,
shadow: shadow,
isLightMode: isLightMode,
rounding: rounding,
child: extra == null ? alignedRow : Column(children: [alignedRow, extra]),
);
}
@@ -64,13 +67,14 @@ class FirkaCard extends StatelessWidget {
this.height,
this.width,
this.isLightMode,
this.rounding,
required this.child,
super.key,
});
@override
Widget build(BuildContext context) {
final defaultRounding = 16.0;
final defaultRounding = rounding ?? 16.0;
final attachedRounding = 8.0;
final isLight =
isLightMode ?? Theme.of(context).brightness == Brightness.light;

View File

@@ -1,67 +0,0 @@
part of "../core_theme.dart";
const butcherVanityCore = CoreTheme(
id: "butcher_vanity",
light: CoreThemeColors(
background: Color(0xFFF2F2F2),
backgroundAmoled: Colors.black,
background0p: Color(0x00F2F2F2),
success: Color(0xFF92EA3B),
shadowBlur: 2,
textPrimary: Color(0xFF0D0D0D),
textSecondary: Color(0xCC0D0D0D),
textTertiary: Color(0x800D0D0D),
textTeritary: Color(0xFFF23838),
textPrimaryLight: Color(0xFF0D0D0D),
textSecondaryLight: Color(0xCC0D0D0D),
textTertiaryLight: Color(0x800D0D0D),
card: Color(0xFFE8E8E8),
cardTranslucent: Color(0x80E8E8E8),
buttonSecondaryFill: Color(0xFFFFFFFF),
buttonDisabledIcon: Color(0xFFC2C2C2),
accent: Color(0xFFF2E205),
secondary: Color(0xFFF2CB05),
shadowColor: Color(0x330D0D0D),
a10p: Color(0x1AF2E205),
a15p: Color(0x26F2E205),
warningAccent: Color(0xFFF28D1F),
warningText: Color(0xFF8F4A0C),
warning15p: Color(0x26F28D1F),
warningCard: Color(0xFFFAE6D4),
errorAccent: Color(0xFFF23838),
errorText: Color(0xFF8F1B1B),
error15p: Color(0x26F23838),
errorCard: Color(0xFFFADCDC),
),
dark: CoreThemeColors(
background: Color(0xFF0D0D0D),
backgroundAmoled: Colors.black,
background0p: Color(0x00F2F2F2),
success: Color(0xFF92EA3B),
shadowBlur: 0,
textPrimary: Color(0xFFF2F2F2),
textSecondary: Color(0xB3F2F2F2),
textTertiary: Color(0x80F2F2F2),
textTeritary: Color(0xFFF23838),
textPrimaryLight: Color(0xFF0D0D0D),
textSecondaryLight: Color(0xCC0D0D0D),
textTertiaryLight: Color(0x800D0D0D),
card: Color(0xFF171717),
cardTranslucent: Color(0x80171717),
buttonSecondaryFill: Color(0xFF222222),
buttonDisabledIcon: Color(0xFF4A4A4A),
accent: Color(0xFFF2E205),
secondary: Color(0xFFF2CB05),
shadowColor: Color(0x26F2CB05),
a10p: Color(0x1AF2E205),
a15p: Color(0x26F2E205),
warningAccent: Color(0xFFF28D1F),
warningText: Color(0xFFF0B36A),
warning15p: Color(0x26F28D1F),
warningCard: Color(0xFF201403),
errorAccent: Color(0xFFF23838),
errorText: Color(0xFFF59E9E),
error15p: Color(0x26F23838),
errorCard: Color(0xFF1E0303),
),
);

View File

@@ -1,67 +0,0 @@
part of "../core_theme.dart";
const refilcCore = CoreTheme(
id: "refilc",
light: CoreThemeColors(
background: Color(0xFFD9E4F6),
backgroundAmoled: Colors.black,
background0p: Color(0x00D9E4F6),
success: Color(0xFF34C759),
shadowBlur: 2,
textPrimary: Color(0xFF0B121F),
textSecondary: Color(0xCC0B121F),
textTertiary: Color(0x800B121F),
textTeritary: Color(0xFF545C68),
textPrimaryLight: Color(0xFF0B121F),
textSecondaryLight: Color(0xCC0B121F),
textTertiaryLight: Color(0x800B121F),
card: Color(0xFFEDF3FF),
cardTranslucent: Color(0x80EDF3FF),
buttonSecondaryFill: Color(0xFFFFFFFF),
buttonDisabledIcon: Color(0xFFBCC7DA),
accent: Color(0xFF3C5AF5),
secondary: Color(0xFF2436A8),
shadowColor: Color(0x330B121F),
a10p: Color(0x1A3C5AF5),
a15p: Color(0x263C5AF5),
warningAccent: Color(0xFFFFA046),
warningText: Color(0xFF8F531B),
warning15p: Color(0x26FFA046),
warningCard: Color(0xFFFAEBDC),
errorAccent: Color(0xFFFF54A1),
errorText: Color(0xFF8F1B4F),
error15p: Color(0x26FF54A1),
errorCard: Color(0xFFFADCE9),
),
dark: CoreThemeColors(
background: Color(0xFF000000),
backgroundAmoled: Colors.black,
background0p: Color(0x00D9E4F6),
success: Color(0xFF32D74B),
shadowBlur: 0,
textPrimary: Color(0xFFF5F6FA),
textSecondary: Color(0xB3F5F6FA),
textTertiary: Color(0x80F5F6FA),
textTeritary: Color(0xFF9D9FA0),
textPrimaryLight: Color(0xFF0B121F),
textSecondaryLight: Color(0xCC0B121F),
textTertiaryLight: Color(0x800B121F),
card: Color(0xFF121619),
cardTranslucent: Color(0x80121619),
buttonSecondaryFill: Color(0xFF1C2228),
buttonDisabledIcon: Color(0xFF3A424D),
accent: Color(0xFF3C5AF5),
secondary: Color(0xFF8BA3FF),
shadowColor: Color(0x263C5AF5),
a10p: Color(0x1A3C5AF5),
a15p: Color(0x263C5AF5),
warningAccent: Color(0xFFFFA046),
warningText: Color(0xFFF0B37A),
warning15p: Color(0x26FFA046),
warningCard: Color(0xFF201203),
errorAccent: Color(0xFFFF54A1),
errorText: Color(0xFFF59EC5),
error15p: Color(0x26FF54A1),
errorCard: Color(0xFF1E030F),
),
);

View File

@@ -1,13 +1,9 @@
import "package:flutter/material.dart";
part "core/butcher_vanity.dart";
part "core/firka.dart";
part "core/refilc.dart";
const Map<String, CoreTheme> coreThemes = {
"firka": firkaCore,
"refilc": refilcCore,
"butcher_vanity": butcherVanityCore,
};
/// App chrome colors (everything except grade colors)

View File

@@ -1,25 +0,0 @@
part of "../grade_theme.dart";
GradeThemeColors _materialShades(MaterialColor color) {
return GradeThemeColors(
grade5: color.shade500,
grade4: color.shade400,
grade3: color.shade300,
grade2: color.shade200,
grade1: color.shade100,
);
}
GradeTheme _materialRainbowGrade(String id, MaterialColor color) {
final colors = _materialShades(color);
return GradeTheme(id: id, light: colors, dark: colors);
}
final redGrade = _materialRainbowGrade("red", Colors.red);
final orangeGrade = _materialRainbowGrade("orange", Colors.orange);
final yellowGrade = _materialRainbowGrade("yellow", Colors.yellow);
final greenGrade = _materialRainbowGrade("green", Colors.green);
final blueGrade = _materialRainbowGrade("blue", Colors.blue);
final indigoGrade = _materialRainbowGrade("indigo", Colors.indigo);
final pinkGrade = _materialRainbowGrade("pink", Colors.pink);
final purpleGrade = _materialRainbowGrade("purple", Colors.purple);

View File

@@ -1,7 +1,6 @@
import "package:flutter/material.dart";
part "grade/firka.dart";
part "grade/rainbow.dart";
class GradeThemeColors {
final Color grade5;
@@ -33,16 +32,8 @@ class GradeTheme {
GradeThemeColors forBrightness(bool isLight) => isLight ? light : dark;
}
final Map<String, GradeTheme> gradeThemes = {
const Map<String, GradeTheme> gradeThemes = {
"firka": firkaGrade,
"red": redGrade,
"orange": orangeGrade,
"yellow": yellowGrade,
"green": greenGrade,
"blue": blueGrade,
"indigo": indigoGrade,
"pink": pinkGrade,
"purple": purpleGrade,
};
GradeTheme resolveGrade(String id) => gradeThemes[id] ?? firkaGrade;

View File

@@ -1,47 +0,0 @@
{
description = "Firka — development environment";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
android-nixpkgs = {
url = "github:tadfisher/android-nixpkgs";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, flake-utils, android-nixpkgs }:
flake-utils.lib.eachSystem [ "aarch64-darwin" "x86_64-darwin" "x86_64-linux" ] (system:
let
pkgs = nixpkgs.legacyPackages.${system};
androidSdk = android-nixpkgs.sdk.${system} (sdkPkgs: with sdkPkgs; [
cmdline-tools-latest
build-tools-34-0-0
build-tools-35-0-0
build-tools-36-1-0
platform-tools
platforms-android-34
platforms-android-35
platforms-android-36
ndk-28-2-13676358
cmake-3-22-1
]);
in
{
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
flutter
git
jq
jdk17
androidSdk
];
shellHook = ''
export GRADLE_OPTS="-Dorg.gradle.project.android.aapt2FromMavenOverride=$ANDROID_HOME/build-tools/36.1.0/aapt2"
flutter --version | head -1
dart --version
'';
};
});
}

View File

@@ -53,7 +53,7 @@ class Grade extends UidObj {
mode: json.nameUidDesc('Mod'),
valueType: json.nameUidDesc('ErtekFajta')!,
teacher: json['ErtekeloTanarNeve'],
kind: json['Kind'],
kind: json['Jelleg'],
numericValue: json['SzamErtek'],
strValue: json['SzovegesErtek'],
weightPercentage: json['SulySzazalekErteke'],
@@ -75,7 +75,7 @@ class Grade extends UidObj {
'Mod': mode?.toJson(),
'ErtekFajta': valueType.toJson(),
'ErtekeloTanarNeve': teacher,
'Kind': kind,
'Jelleg': kind,
'SzamErtek': numericValue,
'SzovegesErtek': strValue,
'SulySzazalekErteke': weightPercentage,