Compare commits
23 Commits
cleanup/re
...
feat/themi
| Author | SHA1 | Date | |
|---|---|---|---|
| e865df27ca | |||
| 57037357c1 | |||
| d2b26f3152 | |||
| 511fd18363 | |||
| 3dc28b7f2d | |||
| dd3ffa3fd4 | |||
| 2118884905 | |||
| 55318d738a | |||
| 8062024e1c | |||
|
|
5e757d9afd | ||
|
|
fff41d95d7 | ||
|
|
93b1d78fd2 | ||
|
|
717b4b27aa | ||
| a097c80516 | |||
| ec2b22c825 | |||
| d8ee1d8073 | |||
| 280b5142a5 | |||
| 31b9d86ed9 | |||
| ff297bf4b8 | |||
| 0f0b7c0c8b | |||
| 394b7bfd70 | |||
| 95b6af52c2 | |||
| fcf6a08e79 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -100,9 +100,12 @@ firka/debug-info/
|
||||
**/.env*
|
||||
**/*.dart.js
|
||||
**/*.info.json
|
||||
**/*.g.dart
|
||||
**/.codegen-cache.yaml
|
||||
|
||||
# tools.py logs
|
||||
tool_logs/build/*.log
|
||||
tool_logs/d8dx_fix/*.log
|
||||
tool_logs/pub_fix/*.log
|
||||
secrets/upload_certificate.pem
|
||||
secrets (2)/upload_certificate.pem
|
||||
|
||||
101
.woodpecker.yml
101
.woodpecker.yml
@@ -28,6 +28,7 @@ steps:
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- flutter pub get
|
||||
|
||||
- name: codegen
|
||||
@@ -37,30 +38,113 @@ steps:
|
||||
- cd firka
|
||||
- dart run scripts/codegen.dart
|
||||
|
||||
- name: clone-mock-kreta-server
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
environment:
|
||||
GITEA_USERNAME:
|
||||
from_secret: gitea_username
|
||||
GITEA_TOKEN:
|
||||
from_secret: gitea_token
|
||||
commands:
|
||||
- pwd
|
||||
# The heredoc uses a quoted delimiter so $GITEA_USERNAME/$GITEA_TOKEN
|
||||
# are written to the script literally, not expanded here -- keeps the
|
||||
# secret values out of this (traced) command's expanded output.
|
||||
- |
|
||||
cat > /tmp/write_netrc.sh <<'NETRC_SCRIPT'
|
||||
printf 'machine git.firka.app\nlogin %s\npassword %s\n' "$GITEA_USERNAME" "$GITEA_TOKEN" > "$HOME/.netrc"
|
||||
chmod 600 "$HOME/.netrc"
|
||||
NETRC_SCRIPT
|
||||
# Runs as an untraced child shell, so the expansion above never hits the log.
|
||||
- sh /tmp/write_netrc.sh
|
||||
- git clone --depth 1 https://git.firka.app/firka/mock_kreta_server.git mock_kreta_server
|
||||
- rm -f /tmp/write_netrc.sh "$HOME/.netrc"
|
||||
|
||||
- name: build-mock-kreta-server
|
||||
image: golang:1.26
|
||||
commands:
|
||||
- cd mock_kreta_server
|
||||
- go build -o ../mock_kreta_server_bin .
|
||||
|
||||
# Runs the mock server in the background and exercises kreta_api's DTOs
|
||||
# against its real wire format, catching drift between the two repos.
|
||||
- name: kreta-api-mock-server-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- cd kreta_api
|
||||
- dart pub get
|
||||
- MOCK_KRETA_SERVER_URL=http://127.0.0.1:8090 dart test
|
||||
|
||||
- name: firka-e2e-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- cp $(find "$PUB_CACHE" -name libisar.so | grep linux | head -n 1) libisar.so 2>/dev/null || true
|
||||
- flutter test test/data/widget_test.dart test/e2e/screenshot_widget_test.dart test/e2e/notification_diff_test.dart
|
||||
|
||||
- name: firka-integration-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
privileged: true
|
||||
volumes:
|
||||
- /dev/kvm:/dev/kvm
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- 'grep -q "::1" /etc/hosts || echo "::1 localhost ip6-localhost ip6-loopback" >> /etc/hosts 2>/dev/null || true'
|
||||
- sysctl -w net.ipv6.conf.all.disable_ipv6=0 2>/dev/null || true
|
||||
- sed -i 's/TIMEOUT=60/TIMEOUT=300/' /opt/bin/start-emulator.sh
|
||||
- sed -i 's/-snapshot default_boot/-no-snapshot-load/' /opt/bin/start-emulator.sh
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- /opt/bin/start-emulator.sh
|
||||
- adb reverse tcp:8090 tcp:8090
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- flutter test integration_test/widget_e2e_test.dart
|
||||
|
||||
- name: build-release
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch: main
|
||||
- branch: [main, staging]
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build appbundle --release
|
||||
- '[ -f "$(git rev-parse --git-dir)/shallow" ] && git fetch --unshallow 2>/dev/null || true'
|
||||
- SHA=$(git rev-parse --short HEAD)
|
||||
- COMMIT_COUNT=$(git rev-list --count HEAD)
|
||||
- 'BASE_VERSION=$(grep "^version:" pubspec.yaml | cut -d: -f2 | cut -d+ -f1 | tr -d " ")'
|
||||
- BUILD_NAME="$BASE_VERSION-$SHA"
|
||||
- VERSION_CODE=$((2000 + COMMIT_COUNT))
|
||||
- flutter build appbundle --release --build-name="$BUILD_NAME" --build-number="$VERSION_CODE"
|
||||
|
||||
- name: build-debug
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
exclude: [main, staging]
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build apk --debug --split-per-abi
|
||||
- '[ -f "$(git rev-parse --git-dir)/shallow" ] && git fetch --unshallow 2>/dev/null || true'
|
||||
- SHA=$(git rev-parse --short HEAD)
|
||||
- COMMIT_COUNT=$(git rev-list --count HEAD)
|
||||
- 'BASE_VERSION=$(grep "^version:" pubspec.yaml | cut -d: -f2 | cut -d+ -f1 | tr -d " ")'
|
||||
- BUILD_NAME="$BASE_VERSION-$SHA"
|
||||
- VERSION_CODE=$((2000 + COMMIT_COUNT))
|
||||
- flutter build apk --debug --split-per-abi --build-name="$BUILD_NAME" --build-number="$VERSION_CODE"
|
||||
|
||||
|
||||
- name: publish-release
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch: main
|
||||
- branch: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
@@ -78,7 +162,7 @@ steps:
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
@@ -96,7 +180,7 @@ steps:
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
@@ -114,7 +198,7 @@ steps:
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
@@ -126,3 +210,4 @@ steps:
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-x86_64-debug.apk
|
||||
file_name: app-x86_64-debug.apk
|
||||
update: 'true'
|
||||
|
||||
|
||||
3
firka/.gitignore
vendored
3
firka/.gitignore
vendored
@@ -52,4 +52,5 @@ app.*.map.json
|
||||
coverage
|
||||
|
||||
# Generated files
|
||||
*.g.dart
|
||||
*.g.dart
|
||||
libisar.so
|
||||
@@ -7,6 +7,10 @@
|
||||
|
||||
# The following line activates a set of recommended lints for Flutter apps,
|
||||
# packages, and plugins designed to encourage good coding practices.
|
||||
analyzer:
|
||||
exclude:
|
||||
- build/**
|
||||
- android/**
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
|
||||
@@ -12,7 +12,7 @@ plugins {
|
||||
}
|
||||
android {
|
||||
namespace = "app.firka.naplo"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
compileSdk = 37
|
||||
ndkVersion = flutter.ndkVersion
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
@@ -59,7 +59,7 @@ android {
|
||||
if (config != null) {
|
||||
signingConfig = config
|
||||
}
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
proguardFiles("proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,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")
|
||||
implementation("com.google.android.gms:play-services-base:18.5.0")
|
||||
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
|
||||
}
|
||||
// Ensure .env exists before Flutter bundles assets (copy from .env.example if missing)
|
||||
@@ -93,6 +94,26 @@ tasks.register("ensureEnv") {
|
||||
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
|
||||
dependsOn("ensureEnv")
|
||||
}
|
||||
|
||||
// Ensure default ProGuard files exist at the projectDir location expected by AGP/R8 when build directory is relocated
|
||||
val defaultProguardDir = file("${project.projectDir}/build/intermediates/default_proguard_files/global")
|
||||
defaultProguardDir.mkdirs()
|
||||
val defaultProguardOptimize = File(defaultProguardDir, "proguard-android-optimize.txt-9.2.0")
|
||||
if (!defaultProguardOptimize.exists()) {
|
||||
defaultProguardOptimize.writeText("-allowaccessmodification\n")
|
||||
}
|
||||
tasks.register("ensureProguardFiles") {
|
||||
doLast {
|
||||
defaultProguardDir.mkdirs()
|
||||
if (!defaultProguardOptimize.exists()) {
|
||||
defaultProguardOptimize.writeText("-allowaccessmodification\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
tasks.matching { it.name.startsWith("compile") || it.name.contains("minify", ignoreCase = true) || it.name.contains("r8", ignoreCase = true) }.configureEach {
|
||||
dependsOn("ensureProguardFiles")
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
76
firka/android/app/proguard-rules.pro
vendored
76
firka/android/app/proguard-rules.pro
vendored
@@ -1 +1,75 @@
|
||||
-keep class app.firka.naplo.glance.** { *; }
|
||||
# Firka custom keep rules
|
||||
-keep class app.firka.naplo.glance.** { *; }
|
||||
|
||||
# Android optimize rules (-allowaccessmodification)
|
||||
-allowaccessmodification
|
||||
|
||||
# Android common keep rules
|
||||
-keepattributes AnnotationDefault,
|
||||
EnclosingMethod,
|
||||
InnerClasses,
|
||||
RuntimeVisibleAnnotations,
|
||||
RuntimeVisibleParameterAnnotations,
|
||||
RuntimeVisibleTypeAnnotations,
|
||||
Signature
|
||||
|
||||
-keep public class com.google.vending.licensing.ILicensingService
|
||||
-keep public class com.android.vending.licensing.ILicensingService
|
||||
-keep public class com.google.android.vending.licensing.ILicensingService
|
||||
-dontnote com.android.vending.licensing.ILicensingService
|
||||
-dontnote com.google.vending.licensing.ILicensingService
|
||||
-dontnote com.google.android.vending.licensing.ILicensingService
|
||||
|
||||
# Native methods
|
||||
-keepclasseswithmembernames,includedescriptorclasses class * {
|
||||
native <methods>;
|
||||
}
|
||||
|
||||
# Keep setters in Views so that animations can still work.
|
||||
-keepclassmembers public class * extends android.view.View {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
# We want to keep methods in Activity that could be used in the XML attribute onClick.
|
||||
-keepclassmembers class * extends android.app.Activity {
|
||||
public void *(android.view.View);
|
||||
}
|
||||
|
||||
# For enumeration classes
|
||||
-keepclassmembers enum * {
|
||||
public static **[] values();
|
||||
public static ** valueOf(java.lang.String);
|
||||
}
|
||||
|
||||
-keepclassmembers class * implements android.os.Parcelable {
|
||||
public static final ** CREATOR;
|
||||
}
|
||||
|
||||
# Preserve annotated Javascript interface methods.
|
||||
-keepclassmembers class * {
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
|
||||
# The support libraries contains references to newer platform versions.
|
||||
-dontnote android.support.**
|
||||
-dontnote androidx.**
|
||||
-dontwarn android.support.**
|
||||
-dontwarn androidx.**
|
||||
|
||||
# Understand the @Keep support annotation.
|
||||
-keep class android.support.annotation.Keep
|
||||
-keep @android.support.annotation.Keep class * {*;}
|
||||
-keepclasseswithmembers class * {
|
||||
@android.support.annotation.Keep <methods>;
|
||||
}
|
||||
-keepclasseswithmembers class * {
|
||||
@android.support.annotation.Keep <fields>;
|
||||
}
|
||||
-keepclasseswithmembers class * {
|
||||
@android.support.annotation.Keep <init>(...);
|
||||
}
|
||||
|
||||
-dontnote org.apache.http.**
|
||||
-dontnote android.net.http.**
|
||||
-dontnote java.lang.invoke.**
|
||||
@@ -3,9 +3,11 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
<application
|
||||
android:name=".AppMain"
|
||||
@@ -669,6 +671,7 @@
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
<action android:name="app.firka.naplo.ACTION_REFRESH_WIDGET" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
|
||||
@@ -10,6 +10,8 @@ import android.util.Log
|
||||
import androidx.glance.appwidget.updateAll
|
||||
import app.firka.naplo.glance.TimetableWidget
|
||||
import app.firka.naplo.glance.TimetableWidgetReceiver
|
||||
import com.google.android.gms.common.ConnectionResult
|
||||
import com.google.android.gms.common.GoogleApiAvailability
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
@@ -163,17 +165,10 @@ class MainActivity : FlutterActivity() {
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
val appContext = context.applicationContext
|
||||
val appWidgetManager = AppWidgetManager.getInstance(appContext)
|
||||
val componentName = ComponentName(appContext, TimetableWidgetReceiver::class.java)
|
||||
val ids = appWidgetManager.getAppWidgetIds(componentName)
|
||||
if (ids.isNotEmpty()) {
|
||||
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
|
||||
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
|
||||
}
|
||||
appContext.sendBroadcast(intent)
|
||||
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
action = TimetableWidgetReceiver.ACTION_REFRESH_WIDGET
|
||||
}
|
||||
appContext.sendBroadcast(intent)
|
||||
TimetableWidget().updateAll(appContext)
|
||||
result.success(true)
|
||||
} catch (e: Exception) {
|
||||
@@ -181,6 +176,15 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
"isGmsAvailable" -> {
|
||||
try {
|
||||
val availability = GoogleApiAvailability.getInstance()
|
||||
val resultCode = availability.isGooglePlayServicesAvailable(context)
|
||||
result.success(resultCode == ConnectionResult.SUCCESS)
|
||||
} catch (e: Exception) {
|
||||
result.success(false)
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
result.notImplemented()
|
||||
}
|
||||
@@ -190,6 +194,29 @@ class MainActivity : FlutterActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
private fun handleIntent(intent: Intent?) {
|
||||
val action = intent?.getStringExtra("action")
|
||||
if (action == "pin_widget") {
|
||||
val appWidgetManager = AppWidgetManager.getInstance(this)
|
||||
val myProvider = ComponentName(this, TimetableWidgetReceiver::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && appWidgetManager.isRequestPinAppWidgetSupported) {
|
||||
appWidgetManager.requestPinAppWidget(myProvider, null, null)
|
||||
}
|
||||
} else if (action == "refresh_widget") {
|
||||
val appContext = applicationContext
|
||||
val refreshIntent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
this.action = TimetableWidgetReceiver.ACTION_REFRESH_WIDGET
|
||||
}
|
||||
appContext.sendBroadcast(refreshIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,31 +54,35 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
}
|
||||
|
||||
private fun loadWidgetData(context: Context): WidgetData? {
|
||||
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
|
||||
val widgetStateFile = File(appFlutter, "widget_state.json")
|
||||
if (!widgetStateFile.exists()) return null
|
||||
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
|
||||
val colors = Colors(widgetState)
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
val lessons = mutableListOf<WidgetLesson>()
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(WidgetLesson(tt.getJSONObject(i)))
|
||||
}
|
||||
val displayDateStr = widgetState.optString("displayDate", "")
|
||||
val targetDate = if (displayDateStr.isNotEmpty()) {
|
||||
try {
|
||||
LocalDate.parse(displayDateStr)
|
||||
} catch (_: Exception) {
|
||||
try {
|
||||
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
|
||||
val widgetStateFile = File(appFlutter, "widget_state.json")
|
||||
if (!widgetStateFile.exists()) return null
|
||||
val text = widgetStateFile.readText(Charsets.UTF_8)
|
||||
val widgetState = JSONObject(text)
|
||||
val colors = Colors(widgetState)
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
val lessons = mutableListOf<WidgetLesson>()
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(WidgetLesson(tt.getJSONObject(i)))
|
||||
}
|
||||
val displayDateStr = widgetState.optString("displayDate", "")
|
||||
val targetDate = if (displayDateStr.isNotEmpty()) {
|
||||
try {
|
||||
LocalDate.parse(displayDateStr)
|
||||
} catch (_: Exception) {
|
||||
LocalDate.now()
|
||||
}
|
||||
} else {
|
||||
LocalDate.now()
|
||||
}
|
||||
} else {
|
||||
LocalDate.now()
|
||||
val filtered = lessons.filter { it.start.toLocalDate() == targetDate }
|
||||
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
|
||||
return WidgetData(colors, headerText, filtered)
|
||||
} catch (e: Throwable) {
|
||||
android.util.Log.e("TimetableWidget", "Error in loadWidgetData", e)
|
||||
return null
|
||||
}
|
||||
val start = LocalDateTime.of(targetDate.year, targetDate.month, targetDate.dayOfMonth, 0, 0)
|
||||
val end = start.plusHours(23)
|
||||
val filtered = lessons.filter { it.start.isAfter(start) && it.end.isBefore(end) }
|
||||
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
|
||||
return WidgetData(colors, headerText, filtered)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -7,9 +7,37 @@ import HomeWidgetGlanceWidgetReceiver
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.glance.appwidget.updateAll
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>() {
|
||||
override val glanceAppWidget = TimetableWidget()
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
super.onReceive(context, intent)
|
||||
val action = intent.action
|
||||
if (action == ACTION_REFRESH_WIDGET ||
|
||||
action == AppWidgetManager.ACTION_APPWIDGET_UPDATE ||
|
||||
action == Intent.ACTION_BOOT_COMPLETED ||
|
||||
action == Intent.ACTION_MY_PACKAGE_REPLACED) {
|
||||
val pendingResult = goAsync()
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
glanceAppWidget.updateAll(context)
|
||||
} catch (e: Exception) {
|
||||
Log.e("TimetableWidget", "Failed glanceAppWidget.updateAll from onReceive", e)
|
||||
} finally {
|
||||
pendingResult?.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAppWidgetOptionsChanged(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
@@ -17,9 +45,18 @@ class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>(
|
||||
newOptions: Bundle,
|
||||
) {
|
||||
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
|
||||
runBlocking {
|
||||
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
|
||||
glanceAppWidget.update(context, glanceId)
|
||||
val pendingResult = goAsync()
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
|
||||
glanceAppWidget.update(context, glanceId)
|
||||
} finally {
|
||||
pendingResult?.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_REFRESH_WIDGET = "app.firka.naplo.ACTION_REFRESH_WIDGET"
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,43 @@ import app.firka.naplo.getIntOrNull
|
||||
import app.firka.naplo.getStringOrNull
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
import java.time.temporal.ChronoField
|
||||
|
||||
class WidgetLesson(data: JSONObject) {
|
||||
val formatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
|
||||
.optionalStart()
|
||||
.appendLiteral('Z')
|
||||
.optionalEnd()
|
||||
.toFormatter()
|
||||
companion object {
|
||||
private val formatter: DateTimeFormatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
|
||||
.optionalStart()
|
||||
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
|
||||
.optionalEnd()
|
||||
.optionalStart()
|
||||
.appendLiteral('Z')
|
||||
.optionalEnd()
|
||||
.optionalStart()
|
||||
.appendOffset("+HH:MM", "+00:00")
|
||||
.optionalEnd()
|
||||
.toFormatter()
|
||||
|
||||
val name: String = data.getString("Nev")
|
||||
val start: LocalDateTime = LocalDateTime.parse(data.getString("KezdetIdopont"), formatter)
|
||||
val end: LocalDateTime = LocalDateTime.parse(data.getString("VegIdopont"), formatter)
|
||||
val lessonNumber: Int? = data.getIntOrNull("Oraszam")
|
||||
val roomName: String? = data.getStringOrNull("TeremNeve")
|
||||
val substituteTeacher: String? = data.getStringOrNull("HelyettesTanarNeve")
|
||||
fun parseDateTime(raw: String): LocalDateTime {
|
||||
return try {
|
||||
LocalDateTime.parse(raw, formatter)
|
||||
} catch (_: Exception) {
|
||||
try {
|
||||
OffsetDateTime.parse(raw).toLocalDateTime()
|
||||
} catch (_: Exception) {
|
||||
LocalDateTime.parse(raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val name: String = data.optString("name", data.optString("Nev", ""))
|
||||
val start: LocalDateTime = parseDateTime(data.optString("start", data.optString("KezdetIdopont", "")))
|
||||
val end: LocalDateTime = parseDateTime(data.optString("end", data.optString("VegIdopont", "")))
|
||||
val lessonNumber: Int? = data.getIntOrNull("dailyNth") ?: data.getIntOrNull("Oraszam")
|
||||
val roomName: String? = data.getStringOrNull("roomName") ?: data.getStringOrNull("TeremNeve")
|
||||
val substituteTeacher: String? = data.getStringOrNull("substituteTeacher") ?: data.getStringOrNull("HelyettesTanarNeve")
|
||||
}
|
||||
|
||||
@@ -13,25 +13,27 @@ rootProject.layout.buildDirectory.value(newBuildDir)
|
||||
|
||||
subprojects {
|
||||
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
|
||||
afterEvaluate {
|
||||
if (plugins.hasPlugin("com.android.application")) {
|
||||
extensions.configure<ApplicationExtension> {
|
||||
compileSdk = 37
|
||||
defaultConfig {
|
||||
// buildToolsVersion can be set here if needed
|
||||
if (project.name != "app") {
|
||||
project.evaluationDependsOn(":app")
|
||||
|
||||
// android_alarm_manager_plus 5.1.1's own build.gradle.kts only applies
|
||||
// org.jetbrains.kotlin.android when AGP < 9, then unconditionally
|
||||
// configures KotlinAndroidProjectExtension - which doesn't exist here
|
||||
// on AGP 9+ unless we apply the plugin ourselves first.
|
||||
if (project.name == "android_alarm_manager_plus") {
|
||||
pluginManager.apply("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
if (plugins.hasPlugin("com.android.library")) {
|
||||
extensions.configure<LibraryExtension> {
|
||||
compileSdk = 37
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (plugins.hasPlugin("com.android.library")) {
|
||||
extensions.configure<LibraryExtension> {
|
||||
compileSdk = 37
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
}
|
||||
|
||||
tasks.register<Delete>("clean") {
|
||||
|
||||
@@ -15,3 +15,6 @@ kotlin.incremental.useClasspathSnapshot=true
|
||||
android.builtInKotlin=false
|
||||
|
||||
android.newDsl=false
|
||||
|
||||
# Prevent AGP 9.0+ build failures due to relocated build directory ProGuard path mismatches
|
||||
android.proguard.failOnMissingFiles=false
|
||||
|
||||
@@ -1,22 +1,10 @@
|
||||
icons:
|
||||
"flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1"
|
||||
"pubspec.yaml": "5d40f014d654e257bc58e8ebfb2468a5ed7f75d913a67fb89314b9fda1c257a6"
|
||||
"flutter_launcher_icons.yaml": "993c1cd3a99db70747299601e556d19ec959b0a16fd9ff2dbf2386cb6f2a640d"
|
||||
"pubspec.yaml": "97e478fd72968c34de0c0ad4421daa9b2e2531d60bb28a893d7d3b5a9a90116c"
|
||||
"assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983"
|
||||
"assets/images/logos/monochrome_logo.png": "188d2b0a64c70323b09bcee721663d6698fb557066f20ddaec97bba6869c1c6c"
|
||||
"assets/images/logos/monochrome_logo.png": "c269a5e689622484d800a4fda5927591a0bf99d34790a4f146b93cf6edabd455"
|
||||
"assets/images/logos/colored_logo_without_mustache.png": "d11cff9f38985885873bfdd2d84e61f8fab03803eada94d4caac1545ef3685f3"
|
||||
"assets/images/logos/colored_logo_only_mustache.png": "bad6220c11bdfb1dfe04e5173bd2ebedd3999689d4b3a68fc63dc520c96dd33b"
|
||||
l10n:
|
||||
"l10n.yml": "a57bc304cac4a2b0235593586f17f400a5165d67fc9aadeaa11893cfa36ee082"
|
||||
"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"
|
||||
"lib/data/models/homework_cache_model.dart": "45789970b27d5790cdc54c292ef2f5feaa5f4e293b8a8862fd676d5eb3e25d29"
|
||||
"lib/data/models/generic_cache_model.dart": "62003ec1fd73a0fa6786d337acdef42b9a6eb9efaa78d17eaf4fe091504b8490"
|
||||
"lib/data/models/timetable_cache_model.dart": "b972bf51e399f8d20d4f9ad660082d4cc4a9798df9ac9d6ec9ef6ac640205572"
|
||||
splash:
|
||||
"flutter_native_splash.yaml": "0fd4a85d6f950d97298e99916927649940ffcfdadfc136ceee126fed0dbaa9f2"
|
||||
"flutter_native_splash.yaml": "f1bddb74798b1539c4e9213ca9ae305d625ebb0ac5bcbe079b523437e0abc2c4"
|
||||
"assets/images/logos/splash.png": "88fbebc3d686cb9095bcce362029b69978b1b14270e465e91d962b1425db1152"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
flutter_launcher_icons:
|
||||
generate: true
|
||||
android: "launcher_icon"
|
||||
ios: false
|
||||
image_path: "assets/images/logos/colored_logo.webp"
|
||||
adaptive_icon_monochrome: "assets/images/logos/monochrome_logo.png"
|
||||
adaptive_icon_background: "assets/images/logos/colored_logo_without_mustache.png"
|
||||
|
||||
@@ -17,4 +17,6 @@ flutter_native_splash:
|
||||
icon_background_color: "#7ca120"
|
||||
icon_background_color_dark: "#7ca120"
|
||||
|
||||
android: true
|
||||
ios: false
|
||||
web: false
|
||||
|
||||
173
firka/integration_test/widget_e2e_test.dart
Normal file
173
firka/integration_test/widget_e2e_test.dart
Normal file
@@ -0,0 +1,173 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/services/notification_diff_service.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(HttpClient httpClient) async {
|
||||
final loginReq = await httpClient.getUrl(Uri.parse('$_mockServerUrl/Account/Login'));
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception('Failed to extract code from mock server login: $loginBody');
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/connect/token'));
|
||||
tokenReq.headers.contentType = ContentType('application', 'x-www-form-urlencoded');
|
||||
tokenReq.write('grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}');
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception('Token request failed (${tokenResp.statusCode}): $tokenBody');
|
||||
}
|
||||
return TokenGrantResponse.fromJson(jsonDecode(tokenBody) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _getMockLessons(HttpClient httpClient) async {
|
||||
final req = await httpClient.getUrl(Uri.parse('$_mockServerUrl/admin/api/lessons'));
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
final list = jsonDecode(body) as List;
|
||||
return list.cast<Map<String, dynamic>>();
|
||||
}
|
||||
|
||||
Future<void> _putMockLessons(HttpClient httpClient, List<Map<String, dynamic>> lessons) async {
|
||||
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl/admin/api/lessons'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(lessons));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to update mock lessons (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
logger = Logger("FirkaTest");
|
||||
dio.options.connectTimeout = const Duration(seconds: 5);
|
||||
dio.options.receiveTimeout = const Duration(seconds: 3);
|
||||
dio.options.validateStatus = (status) => status != null && status < 500;
|
||||
|
||||
group('Widget End-to-End Test with Mock Kreta Server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
httpClient = HttpClient();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Opening app updates widget with timetable and FCM wakeup syncs timetable changes', (tester) async {
|
||||
// 1. Initialize DB and authenticate with mock_kreta_server
|
||||
final isar = await initDB();
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
// Configure mock backend settings and enable notifications
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
await Settings.notifyAll.set(true);
|
||||
|
||||
final originalLessons = await _getMockLessons(httpClient);
|
||||
final today = DateTime.now();
|
||||
final seededLessons = originalLessons.indexed.map((entry) {
|
||||
final (i, l) = entry;
|
||||
final m = Map<String, dynamic>.from(l);
|
||||
m['KezdetIdopont'] = DateTime(today.year, today.month, today.day, 8 + i, 0).toIso8601String();
|
||||
m['VegIdopont'] = DateTime(today.year, today.month, today.day, 8 + i, 45).toIso8601String();
|
||||
return m;
|
||||
}).toList();
|
||||
await _putMockLessons(httpClient, seededLessons);
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
// 2. Initialize app (simulates opening the app)
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
if (initData.client != null) {
|
||||
await initData.client!.init();
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
}
|
||||
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, 'widget_state.json'));
|
||||
|
||||
// Verify that widget_state.json was created on app opening
|
||||
expect(widgetFile.existsSync(), isTrue, reason: 'widget_state.json must exist after opening app');
|
||||
|
||||
final initialContent = jsonDecode(widgetFile.readAsStringSync()) as Map<String, dynamic>;
|
||||
expect(initialContent.containsKey('colors'), isTrue);
|
||||
expect(initialContent.containsKey('timetable'), isTrue);
|
||||
|
||||
final initialTimetable = (initialContent['timetable'] as List).cast<Map<String, dynamic>>();
|
||||
expect(initialTimetable.isNotEmpty, isTrue, reason: 'Timetable in widget must not be empty');
|
||||
|
||||
final firstLessonName = initialTimetable.first['name'];
|
||||
expect(firstLessonName, isNotNull);
|
||||
expect(initialTimetable.first.containsKey('dailyNth'), isTrue);
|
||||
expect(initialTimetable.first.containsKey('start'), isTrue);
|
||||
expect(initialTimetable.first.containsKey('end'), isTrue);
|
||||
|
||||
// 3. Simulate timetable change on mock server
|
||||
final currentMockLessons = await _getMockLessons(httpClient);
|
||||
expect(currentMockLessons.isNotEmpty, isTrue);
|
||||
|
||||
// Mutate the target lesson: change room and assign a substitute teacher
|
||||
final modifiedLessons = List<Map<String, dynamic>>.from(currentMockLessons);
|
||||
final targetIndex = modifiedLessons.indexWhere((l) => l['Nev'] == firstLessonName);
|
||||
expect(targetIndex != -1, isTrue);
|
||||
final updatedLesson = Map<String, dynamic>.from(modifiedLessons[targetIndex]);
|
||||
updatedLesson['TeremNeve'] = 'LAB-999';
|
||||
updatedLesson['HelyettesTanarNeve'] = 'Prof. E2E Teszt';
|
||||
modifiedLessons[targetIndex] = updatedLesson;
|
||||
|
||||
await _putMockLessons(httpClient, modifiedLessons);
|
||||
|
||||
// 4. Trigger FCM wakeup processing
|
||||
await NotificationDiffService.checkAll();
|
||||
|
||||
// 5. Verify widget_state.json was updated with modified timetable
|
||||
final updatedContent = jsonDecode(widgetFile.readAsStringSync()) as Map<String, dynamic>;
|
||||
final updatedTimetable = (updatedContent['timetable'] as List).cast<Map<String, dynamic>>();
|
||||
|
||||
final updatedMatch = updatedTimetable.firstWhere(
|
||||
(l) => l['name'] == firstLessonName,
|
||||
orElse: () => <String, dynamic>{},
|
||||
);
|
||||
expect(updatedMatch.isNotEmpty, isTrue);
|
||||
expect(updatedMatch['roomName'], equals('LAB-999'), reason: 'Widget state should have updated room name');
|
||||
expect(updatedMatch['substituteTeacher'], equals('Prof. E2E Teszt'), reason: 'Widget state should have updated substitute teacher');
|
||||
|
||||
// Revert mock server lessons back to original
|
||||
await _putMockLessons(httpClient, originalLessons);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -456,10 +456,21 @@ class KretaClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upserts [caches]. Deletes stale rows in [staleScope].
|
||||
Future<List<C>> _save<C extends GenericCacheModel<I>, I extends Identifiable>(
|
||||
List<C> caches,
|
||||
) async {
|
||||
List<C> caches, [
|
||||
QueryBuilder<C, C, QAfterFilterCondition>? staleScope,
|
||||
]) async {
|
||||
isarInit.writeTxnSync(() {
|
||||
if (staleScope != null) {
|
||||
final freshKeys = caches.map((c) => c.cacheKey).toSet();
|
||||
final staleIds = staleScope
|
||||
.findAllSync()
|
||||
.map((c) => c.cacheKey)
|
||||
.where((key) => !freshKeys.contains(key))
|
||||
.toList();
|
||||
isarInit.collection<C>().deleteAllSync(staleIds);
|
||||
}
|
||||
isarInit.collection<C>().putAllSync(caches);
|
||||
});
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
@@ -520,7 +531,7 @@ class KretaClient {
|
||||
KretaEndpoints.getGrades(cache.token.iss),
|
||||
GradeCacheModel.new,
|
||||
(json) => Grade.fromJson(json),
|
||||
).then(_save);
|
||||
).then((caches) => _save(caches, cache.getGrades()));
|
||||
}
|
||||
|
||||
Future<List<HomeworkCacheModel>> getHomework({
|
||||
@@ -534,17 +545,22 @@ class KretaClient {
|
||||
KretaEndpoints.getHomework(cache.token.iss, from, to),
|
||||
HomeworkCacheModel.new,
|
||||
(item) => Homework.fromJson(item),
|
||||
).then(_save);
|
||||
).then((caches) => _save(caches, cache.getHomeworks()));
|
||||
}
|
||||
|
||||
/// Automatically aligns requests to start at Monday and end at Sunday
|
||||
Future<List<LessonCacheModel>> getLessons(DateTime from, DateTime to) async {
|
||||
assert(from.difference(to).inDays < 30);
|
||||
return (await _renewCache(
|
||||
KretaEndpoints.getTimeTable(cache.token.iss, from, to),
|
||||
LessonCacheModel.new,
|
||||
(json) => Lesson.fromJson(json),
|
||||
).then(resolveDailyNth).then(_save))
|
||||
KretaEndpoints.getTimeTable(cache.token.iss, from, to),
|
||||
LessonCacheModel.new,
|
||||
(json) => Lesson.fromJson(json),
|
||||
)
|
||||
.then(resolveDailyNth)
|
||||
.then(
|
||||
(caches) =>
|
||||
_save(caches, cache.getTimeTable().and().between(from, to)),
|
||||
))
|
||||
..sort((a, b) => a.start.compareTo(b.start));
|
||||
}
|
||||
|
||||
@@ -553,15 +569,28 @@ class KretaClient {
|
||||
KretaEndpoints.getTests(cache.token.iss, from, to),
|
||||
TestCacheModel.new,
|
||||
(item) => Test.fromJson(item),
|
||||
).then(_save);
|
||||
).then(
|
||||
(caches) => _save(
|
||||
caches,
|
||||
isarInit.testCacheModels.filter().classGroup(cache.isCurrentClassGroup),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<OmissionCacheModel>> getOmissions() async {
|
||||
return (await _renewCache(
|
||||
KretaEndpoints.getOmissions(cache.token.iss),
|
||||
OmissionCacheModel.new,
|
||||
(item) => Omission.fromJson(item),
|
||||
).then(_save))..sort((a, b) => a.createdAt.compareTo(b.createdAt));
|
||||
KretaEndpoints.getOmissions(cache.token.iss),
|
||||
OmissionCacheModel.new,
|
||||
(item) => Omission.fromJson(item),
|
||||
).then(
|
||||
(caches) => _save(
|
||||
caches,
|
||||
isarInit.omissionCacheModels.filter().classGroup(
|
||||
cache.isCurrentClassGroup,
|
||||
),
|
||||
),
|
||||
))
|
||||
..sort((a, b) => a.createdAt.compareTo(b.createdAt));
|
||||
}
|
||||
|
||||
Future<List<SubjectCacheModel>> getSubjects() async {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/notification_delivery_service.dart";
|
||||
import "package:firka_common/data/models/token_model.dart";
|
||||
import "package:kreta_api/kreta_api.dart";
|
||||
|
||||
@@ -18,9 +18,8 @@ Future<void> completeLogin(
|
||||
await initializeApp();
|
||||
|
||||
if (data.client != null) {
|
||||
await FcmService.onUserLogin(
|
||||
await NotificationDeliveryService.onUserLogin(
|
||||
client: data.client!,
|
||||
settingsStore: data.settings,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ 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/notification_delivery_service.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings/settings_effects.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
@@ -19,6 +21,7 @@ import 'package:firka/l10n/app_localizations_hu.dart';
|
||||
import 'package:firka/core/swear_generator.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka_common/ui/theme/core_theme.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -53,12 +56,15 @@ Future<void> initLang(AppInitialization data) async {
|
||||
}
|
||||
}
|
||||
|
||||
void initTheme(AppInitialization data) {
|
||||
final themeCubit = data.themeCubit;
|
||||
|
||||
final brightness =
|
||||
SchedulerBinding.instance.platformDispatcher.platformBrightness;
|
||||
|
||||
/// Builds a full style for an explicit brightness, applying all custom color
|
||||
/// overrides — independent of the device's/app's actual current brightness.
|
||||
/// Used by [initTheme] itself, and by screens (like the theme editor) that
|
||||
/// need to preview a brightness other than the one currently on screen.
|
||||
FirkaStyle buildStyleForBrightness(
|
||||
bool isLight, {
|
||||
bool? isCustomTheme,
|
||||
bool forceCustomColors = false,
|
||||
}) {
|
||||
final titleFont = Settings.titleFont.value;
|
||||
final titleWeight = Settings.titleWeight.value;
|
||||
final fonts = buildAppFonts(
|
||||
@@ -66,6 +72,28 @@ void initTheme(AppInitialization data) {
|
||||
headingWeight: titleWeight,
|
||||
supportsWeight: titleFont.supportsWeight,
|
||||
);
|
||||
final coreId = Settings.selectedCoreThemeId.value;
|
||||
final gradeId = Settings.selectedGradeThemeId.value;
|
||||
|
||||
final style = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: isLight,
|
||||
fonts: fonts,
|
||||
);
|
||||
_applyCustomColors(
|
||||
style,
|
||||
isCustomTheme: isCustomTheme,
|
||||
force: forceCustomColors,
|
||||
);
|
||||
return style;
|
||||
}
|
||||
|
||||
void initTheme(AppInitialization data) {
|
||||
final themeCubit = data.themeCubit;
|
||||
|
||||
final brightness =
|
||||
SchedulerBinding.instance.platformDispatcher.platformBrightness;
|
||||
|
||||
appHeadingTextCase = switch (Settings.titleCapitalization.value) {
|
||||
TitleCapitalization.lower => HeadingTextCase.lower,
|
||||
@@ -73,50 +101,209 @@ void initTheme(AppInitialization data) {
|
||||
TitleCapitalization.normal => HeadingTextCase.normal,
|
||||
};
|
||||
|
||||
FirkaStyle baseStyle;
|
||||
final coreId = Settings.selectedCoreThemeId.value;
|
||||
final gradeId = Settings.selectedGradeThemeId.value;
|
||||
switch (Settings.themeBrightness.value) {
|
||||
case ThemeBrightness.light:
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: true,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(true);
|
||||
break;
|
||||
case ThemeBrightness.dark:
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: false,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(false);
|
||||
break;
|
||||
case ThemeBrightness.auto:
|
||||
if (brightness == Brightness.dark) {
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: false,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(false);
|
||||
} else {
|
||||
baseStyle = styleFor(
|
||||
coreId: coreId,
|
||||
gradeId: gradeId,
|
||||
isLight: true,
|
||||
fonts: fonts,
|
||||
);
|
||||
themeCubit.setLightMode(true);
|
||||
}
|
||||
final isLight = switch (Settings.themeBrightness.value) {
|
||||
ThemeBrightness.light => true,
|
||||
ThemeBrightness.dark => false,
|
||||
ThemeBrightness.auto => brightness != Brightness.dark,
|
||||
};
|
||||
themeCubit.setLightMode(isLight);
|
||||
appStyle = buildStyleForBrightness(isLight);
|
||||
}
|
||||
|
||||
void _applyCustomColors(
|
||||
FirkaStyle style, {
|
||||
bool? isCustomTheme,
|
||||
bool force = false,
|
||||
}) {
|
||||
final colors = style.colors;
|
||||
|
||||
colors.grade5 = Settings.customGradeColor5.value.toColorFromHexSetting();
|
||||
colors.grade4 = Settings.customGradeColor4.value.toColorFromHexSetting();
|
||||
colors.grade3 = Settings.customGradeColor3.value.toColorFromHexSetting();
|
||||
colors.grade2 = Settings.customGradeColor2.value.toColorFromHexSetting();
|
||||
colors.grade1 = Settings.customGradeColor1.value.toColorFromHexSetting();
|
||||
|
||||
final customActive =
|
||||
isCustomTheme ?? !isBuiltinThemeId(Settings.selectedThemeId.value);
|
||||
if (!force && !customActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
appStyle = baseStyle;
|
||||
final isLight = style.isLight;
|
||||
|
||||
colors.accent =
|
||||
(isLight
|
||||
? Settings.customAccentColorLight
|
||||
: Settings.customAccentColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.a10p = colors.accent.withAlpha(0x1a);
|
||||
colors.a15p = colors.accent.withAlpha(0x26);
|
||||
|
||||
final bgGrad = (isLight
|
||||
? Settings.customBackgroundGradientLight
|
||||
: Settings.customBackgroundGradientDark)
|
||||
.value
|
||||
.toColorListFromHexSetting();
|
||||
|
||||
if (bgGrad.isNotEmpty) {
|
||||
colors.backgroundGradient = bgGrad;
|
||||
colors.background = bgGrad.first;
|
||||
} else {
|
||||
colors.background =
|
||||
(isLight
|
||||
? Settings.customBackgroundColorLight
|
||||
: Settings.customBackgroundColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.backgroundGradient = null;
|
||||
}
|
||||
colors.background0p = colors.background.withAlpha(0);
|
||||
|
||||
colors.card =
|
||||
(isLight
|
||||
? Settings.customCardColorLight
|
||||
: Settings.customCardColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.cardTranslucent = colors.card.withAlpha(0x80);
|
||||
|
||||
colors.buttonSecondaryFill =
|
||||
(isLight
|
||||
? Settings.customButtonColorLight
|
||||
: Settings.customButtonColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.secondary =
|
||||
(isLight
|
||||
? Settings.customSecondaryColorLight
|
||||
: Settings.customSecondaryColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.buttonDisabledIcon = colors.secondary.withAlpha(0x80);
|
||||
|
||||
final customTextLight = Settings.customTextColorLight.value;
|
||||
final customTextDark = Settings.customTextColorDark.value;
|
||||
final isCustomTextLight =
|
||||
customTextLight != SettingsRegistry.customTextColorLight.defaultValue;
|
||||
final isCustomTextDark =
|
||||
customTextDark != SettingsRegistry.customTextColorDark.defaultValue;
|
||||
|
||||
final textLight = customTextLight.toColorFromHexSetting();
|
||||
final textDark = customTextDark.toColorFromHexSetting();
|
||||
colors.textPrimary = isLight ? textLight : textDark;
|
||||
|
||||
final customSecLight = Settings.customTextSecondaryColorLight.value;
|
||||
final customSecDark = Settings.customTextSecondaryColorDark.value;
|
||||
final isCustomSecLight = customSecLight !=
|
||||
SettingsRegistry.customTextSecondaryColorLight.defaultValue;
|
||||
final isCustomSecDark = customSecDark !=
|
||||
SettingsRegistry.customTextSecondaryColorDark.defaultValue;
|
||||
|
||||
colors.textSecondary = isLight
|
||||
? (isCustomSecLight
|
||||
? customSecLight.toColorFromHexSetting()
|
||||
: (isCustomTextLight
|
||||
? textLight.withAlpha(0xCC)
|
||||
: customSecLight.toColorFromHexSetting()))
|
||||
: (isCustomSecDark
|
||||
? customSecDark.toColorFromHexSetting()
|
||||
: (isCustomTextDark
|
||||
? textDark.withAlpha(0xB3)
|
||||
: customSecDark.toColorFromHexSetting()));
|
||||
|
||||
final customTertLight = Settings.customTextTertiaryColorLight.value;
|
||||
final customTertDark = Settings.customTextTertiaryColorDark.value;
|
||||
final isCustomTertLight = customTertLight !=
|
||||
SettingsRegistry.customTextTertiaryColorLight.defaultValue;
|
||||
final isCustomTertDark = customTertDark !=
|
||||
SettingsRegistry.customTextTertiaryColorDark.defaultValue;
|
||||
|
||||
colors.textTertiary = isLight
|
||||
? (isCustomTertLight
|
||||
? customTertLight.toColorFromHexSetting()
|
||||
: (isCustomTextLight
|
||||
? textLight.withAlpha(0x80)
|
||||
: customTertLight.toColorFromHexSetting()))
|
||||
: (isCustomTertDark
|
||||
? customTertDark.toColorFromHexSetting()
|
||||
: (isCustomTextDark
|
||||
? textDark.withAlpha(0x80)
|
||||
: customTertDark.toColorFromHexSetting()));
|
||||
colors.textTeritary = colors.textTertiary;
|
||||
|
||||
colors.textPrimaryLight = textLight;
|
||||
colors.textSecondaryLight = isCustomSecLight
|
||||
? customSecLight.toColorFromHexSetting()
|
||||
: (isCustomTextLight
|
||||
? textLight.withAlpha(0xCC)
|
||||
: customSecLight.toColorFromHexSetting());
|
||||
colors.textTertiaryLight = isCustomTertLight
|
||||
? customTertLight.toColorFromHexSetting()
|
||||
: (isCustomTextLight
|
||||
? textLight.withAlpha(0x80)
|
||||
: customTertLight.toColorFromHexSetting());
|
||||
|
||||
colors.shadowColor =
|
||||
(isLight
|
||||
? Settings.customShadowColorLight
|
||||
: Settings.customShadowColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.success =
|
||||
(isLight
|
||||
? Settings.customSuccessColorLight
|
||||
: Settings.customSuccessColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.warningAccent =
|
||||
(isLight
|
||||
? Settings.customWarningAccentColorLight
|
||||
: Settings.customWarningAccentColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.warning15p = colors.warningAccent.withAlpha(0x26);
|
||||
|
||||
colors.warningText =
|
||||
(isLight
|
||||
? Settings.customWarningTextColorLight
|
||||
: Settings.customWarningTextColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.warningCard =
|
||||
(isLight
|
||||
? Settings.customWarningCardColorLight
|
||||
: Settings.customWarningCardColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.errorAccent =
|
||||
(isLight
|
||||
? Settings.customErrorAccentColorLight
|
||||
: Settings.customErrorAccentColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
colors.error15p = colors.errorAccent.withAlpha(0x26);
|
||||
|
||||
colors.errorText =
|
||||
(isLight
|
||||
? Settings.customErrorTextColorLight
|
||||
: Settings.customErrorTextColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
|
||||
colors.errorCard =
|
||||
(isLight
|
||||
? Settings.customErrorCardColorLight
|
||||
: Settings.customErrorCardColorDark)
|
||||
.value
|
||||
.toColorFromHexSetting();
|
||||
}
|
||||
|
||||
Future<void> _initData(AppInitialization init) async {
|
||||
await init.settings.loadAll();
|
||||
final selectedThemeId = Settings.selectedThemeId.value;
|
||||
@@ -125,11 +312,13 @@ Future<void> _initData(AppInitialization init) async {
|
||||
await Settings.selectedThemeId.set(normalized);
|
||||
}
|
||||
await initLang(init);
|
||||
await regenerateM3eTheme();
|
||||
initTheme(init);
|
||||
|
||||
var dispatcher = SchedulerBinding.instance.platformDispatcher;
|
||||
|
||||
dispatcher.onPlatformBrightnessChanged = () {
|
||||
dispatcher.onPlatformBrightnessChanged = () async {
|
||||
await regenerateM3eTheme();
|
||||
initTheme(init);
|
||||
};
|
||||
|
||||
@@ -166,7 +355,10 @@ Future<void> _initData(AppInitialization init) async {
|
||||
// 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!));
|
||||
unawaited(NotificationDeliveryService.onUserLogin(client: init.client!));
|
||||
|
||||
// Immediately refresh widget state from cached Isar lessons so widget is up to date
|
||||
unawaited(WidgetCacheHelper.updateWidgetCacheFromIsar());
|
||||
|
||||
// Don't block first paint on the network: render whatever is already
|
||||
// cached, then stream in student/timetable/grades/etc. as they arrive.
|
||||
@@ -182,6 +374,7 @@ Future<void> _initData(AppInitialization init) async {
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
|
||||
await init.client!.renewCache(reInit: false);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
}());
|
||||
|
||||
@@ -239,14 +432,21 @@ Future<void> initializeApp() async {
|
||||
);
|
||||
initData.settings.cubit = initData.settingsCubit;
|
||||
Settings = initData.settings;
|
||||
await Settings.loadAll();
|
||||
registerSettingsEffects(initData.settings, initData);
|
||||
|
||||
try {
|
||||
await FcmService.initialize().timeout(const Duration(seconds: 8));
|
||||
await NotificationDeliveryService.initialize().timeout(
|
||||
const Duration(seconds: 8),
|
||||
);
|
||||
} on TimeoutException catch (e, st) {
|
||||
logger.warning('FcmService init timed out: $e', e, st);
|
||||
logger.warning('NotificationDeliveryService init timed out: $e', e, st);
|
||||
} catch (e, st) {
|
||||
logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
logger.severe(
|
||||
'Failed to initialize NotificationDeliveryService: $e',
|
||||
e,
|
||||
st,
|
||||
);
|
||||
}
|
||||
|
||||
await _initData(initData);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
@@ -284,18 +288,48 @@ extension LessonExtension on List<Lesson> {
|
||||
}
|
||||
}
|
||||
|
||||
extension RandomColorExtension on Random {
|
||||
HSVColor nextVividHSVColor() {
|
||||
final hue = nextDouble() * 360;
|
||||
final saturation = 0.55 + nextDouble() * 0.45;
|
||||
final value = 0.7 + nextDouble() * 0.3;
|
||||
return HSVColor.fromAHSV(1.0, hue, saturation, value);
|
||||
}
|
||||
}
|
||||
|
||||
extension ColorHexExtension on Color {
|
||||
String toHexSetting() =>
|
||||
"0x${toARGB32().toRadixString(16).toUpperCase().padLeft(8, '0')}";
|
||||
}
|
||||
|
||||
extension HexSettingExtension on String {
|
||||
Color toColorFromHexSetting() => Color(int.tryParse(this) ?? 0xFFFFFFFF);
|
||||
|
||||
List<Color> toColorListFromHexSetting() {
|
||||
try {
|
||||
final decoded = jsonDecode(this);
|
||||
if (decoded is List) {
|
||||
return decoded
|
||||
.map((e) => e.toString().toColorFromHexSetting())
|
||||
.toList();
|
||||
}
|
||||
} catch (_) {}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
extension ColorListHexExtension on List<Color> {
|
||||
String toHexSettingJson() {
|
||||
return jsonEncode(map((c) => c.toHexSetting()).toList());
|
||||
}
|
||||
}
|
||||
|
||||
extension StringExtension on String {
|
||||
bool isNumeric() {
|
||||
final regex = RegExp(r'^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$');
|
||||
return regex.hasMatch(trim());
|
||||
}
|
||||
|
||||
String firstUpper() {
|
||||
if (isEmpty) return this;
|
||||
if (length == 1) this[0].toUpperCase();
|
||||
return this[0].toUpperCase() + substring(1, length);
|
||||
}
|
||||
|
||||
String shortenName([int start = 0]) {
|
||||
if (length <= 16 || start >= length) {
|
||||
return this;
|
||||
|
||||
@@ -293,6 +293,12 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
|
||||
SettingsRegistry.notifyAll,
|
||||
always,
|
||||
),
|
||||
SettingsUiHeaderSmall(l10n.s_notif_delivery_method_header, isPushNotificationsEnabled),
|
||||
SettingsUiEnum(SettingsRegistry.notificationDeliveryMethod, [
|
||||
l10n.s_notif_delivery_auto,
|
||||
l10n.s_notif_delivery_fcm,
|
||||
l10n.s_notif_delivery_alarm,
|
||||
], isPushNotificationsEnabled),
|
||||
SettingsUiHeaderSmall(l10n.s_notif_wakeup_interval_header, isPushNotificationsEnabled),
|
||||
SettingsUiEnum(SettingsRegistry.notifyWakeupInterval, [
|
||||
l10n.s_notif_wakeup_hourly,
|
||||
|
||||
@@ -5,7 +5,10 @@ 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/notification_delivery_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
|
||||
import "package:firka_common/ui/theme/core_theme.dart";
|
||||
|
||||
import "settings_repository.dart";
|
||||
import "settings_schema.dart";
|
||||
@@ -22,6 +25,9 @@ void registerSettingsEffects(
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.themeBrightness, (_) async {
|
||||
if (Settings.selectedCoreThemeId.value == "m3e") {
|
||||
await regenerateM3eTheme();
|
||||
}
|
||||
initTheme(initData);
|
||||
initData.themeCubit.refresh();
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
@@ -37,6 +43,78 @@ void registerSettingsEffects(
|
||||
repo.onChange(SettingsRegistry.titleWeight, refreshTitleStyle);
|
||||
repo.onChange(SettingsRegistry.titleCapitalization, refreshTitleStyle);
|
||||
|
||||
Future<void> refreshPresetTheme(_) async {
|
||||
if (Settings.selectedCoreThemeId.value == "m3e") {
|
||||
await regenerateM3eTheme();
|
||||
}
|
||||
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.selectedThemeId, refreshPresetTheme);
|
||||
|
||||
Future<void> refreshCustomColors(_) async {
|
||||
initTheme(initData);
|
||||
initData.themeCubit.refresh();
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
}
|
||||
|
||||
for (final setting in [
|
||||
SettingsRegistry.customGradeColor5,
|
||||
SettingsRegistry.customGradeColor4,
|
||||
SettingsRegistry.customGradeColor3,
|
||||
SettingsRegistry.customGradeColor2,
|
||||
SettingsRegistry.customGradeColor1,
|
||||
SettingsRegistry.customAccentColorLight,
|
||||
SettingsRegistry.customAccentColorDark,
|
||||
SettingsRegistry.customBackgroundColorLight,
|
||||
SettingsRegistry.customBackgroundColorDark,
|
||||
SettingsRegistry.customCardColorLight,
|
||||
SettingsRegistry.customCardColorDark,
|
||||
SettingsRegistry.customButtonColorLight,
|
||||
SettingsRegistry.customButtonColorDark,
|
||||
SettingsRegistry.customSecondaryColorLight,
|
||||
SettingsRegistry.customSecondaryColorDark,
|
||||
SettingsRegistry.customTextColorLight,
|
||||
SettingsRegistry.customTextColorDark,
|
||||
SettingsRegistry.customTextSecondaryColorLight,
|
||||
SettingsRegistry.customTextSecondaryColorDark,
|
||||
SettingsRegistry.customTextTertiaryColorLight,
|
||||
SettingsRegistry.customTextTertiaryColorDark,
|
||||
SettingsRegistry.customShadowColorLight,
|
||||
SettingsRegistry.customShadowColorDark,
|
||||
SettingsRegistry.customSuccessColorLight,
|
||||
SettingsRegistry.customSuccessColorDark,
|
||||
SettingsRegistry.customWarningAccentColorLight,
|
||||
SettingsRegistry.customWarningAccentColorDark,
|
||||
SettingsRegistry.customWarningTextColorLight,
|
||||
SettingsRegistry.customWarningTextColorDark,
|
||||
SettingsRegistry.customWarningCardColorLight,
|
||||
SettingsRegistry.customWarningCardColorDark,
|
||||
SettingsRegistry.customErrorAccentColorLight,
|
||||
SettingsRegistry.customErrorAccentColorDark,
|
||||
SettingsRegistry.customErrorTextColorLight,
|
||||
SettingsRegistry.customErrorTextColorDark,
|
||||
SettingsRegistry.customErrorCardColorLight,
|
||||
SettingsRegistry.customErrorCardColorDark,
|
||||
SettingsRegistry.customBackgroundGradientLight,
|
||||
SettingsRegistry.customBackgroundGradientDark,
|
||||
]) {
|
||||
repo.onChange(setting, refreshCustomColors);
|
||||
}
|
||||
|
||||
repo.onChange(SettingsRegistry.wearOsSupport, (enabled) async {
|
||||
if (!Platform.isAndroid) return;
|
||||
if (enabled && initDone) {
|
||||
@@ -53,12 +131,16 @@ void registerSettingsEffects(
|
||||
}
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyAll, (enabled) async {
|
||||
await FcmService.handleEnabledChange(enabled);
|
||||
repo.onChange(SettingsRegistry.notifyAll, (_) async {
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
|
||||
await FcmService.handleWakeupIntervalChange();
|
||||
await NotificationDeliveryService.handleWakeupIntervalChange();
|
||||
});
|
||||
|
||||
for (final setting in [
|
||||
|
||||
@@ -24,6 +24,8 @@ enum TitleCapitalization { lower, normal, upper }
|
||||
/// `wakeup-2hourly` sent by the `fcm-notifier` backend service.
|
||||
enum NotifyWakeupInterval { hourly, twoHourly }
|
||||
|
||||
enum NotificationDeliveryMethod { auto, fcm, alarm }
|
||||
|
||||
abstract class SettingsSchema {
|
||||
@DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120)
|
||||
double get bellDelay;
|
||||
@@ -177,4 +179,138 @@ abstract class SettingsSchema {
|
||||
|
||||
@BoolSetting(id: 1046, defaultValue: false)
|
||||
bool get fcmDebugNotifyOnMessage;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1047,
|
||||
defaultValue: NotificationDeliveryMethod.auto,
|
||||
values: NotificationDeliveryMethod.values,
|
||||
)
|
||||
NotificationDeliveryMethod get notificationDeliveryMethod;
|
||||
|
||||
// Custom grade colors stored as 0xAARRGGBB hex strings.
|
||||
// Defaults match the firka grade theme.
|
||||
@StringSetting(id: 1048, defaultValue: "0xFF22CCAD")
|
||||
String get customGradeColor5;
|
||||
|
||||
@StringSetting(id: 1049, defaultValue: "0xFF92EA3B")
|
||||
String get customGradeColor4;
|
||||
|
||||
@StringSetting(id: 1050, defaultValue: "0xFFF9CF00")
|
||||
String get customGradeColor3;
|
||||
|
||||
@StringSetting(id: 1051, defaultValue: "0xFFFFA046")
|
||||
String get customGradeColor2;
|
||||
|
||||
@StringSetting(id: 1052, defaultValue: "0xFFFF54A1")
|
||||
String get customGradeColor1;
|
||||
|
||||
// Custom theme colors stored as 0xAARRGGBB hex strings.
|
||||
// Defaults match the firka core theme.
|
||||
@StringSetting(id: 1053, defaultValue: "0xFFA7DC22")
|
||||
String get customAccentColorLight;
|
||||
|
||||
@StringSetting(id: 1054, defaultValue: "0xFFA7DC22")
|
||||
String get customAccentColorDark;
|
||||
|
||||
@StringSetting(id: 1055, defaultValue: "0xFFFAFFF0")
|
||||
String get customBackgroundColorLight;
|
||||
|
||||
@StringSetting(id: 1056, defaultValue: "0xFF0D1202")
|
||||
String get customBackgroundColorDark;
|
||||
|
||||
@StringSetting(id: 1057, defaultValue: "0xFFF3FBDE")
|
||||
String get customCardColorLight;
|
||||
|
||||
@StringSetting(id: 1058, defaultValue: "0xFF141905")
|
||||
String get customCardColorDark;
|
||||
|
||||
@StringSetting(id: 1059, defaultValue: "0xFFFEFFFD")
|
||||
String get customButtonColorLight;
|
||||
|
||||
@StringSetting(id: 1060, defaultValue: "0xFF20290B")
|
||||
String get customButtonColorDark;
|
||||
|
||||
@StringSetting(id: 1061, defaultValue: "0xFF6E8F1B")
|
||||
String get customSecondaryColorLight;
|
||||
|
||||
@StringSetting(id: 1062, defaultValue: "0xFFCBEE71")
|
||||
String get customSecondaryColorDark;
|
||||
|
||||
@StringSetting(id: 1063, defaultValue: "0xFF394C0A")
|
||||
String get customTextColorLight;
|
||||
|
||||
@StringSetting(id: 1064, defaultValue: "0xFFEAF7CC")
|
||||
String get customTextColorDark;
|
||||
|
||||
@StringSetting(id: 1065, defaultValue: "0xCC394C0A")
|
||||
String get customTextSecondaryColorLight;
|
||||
|
||||
@StringSetting(id: 1066, defaultValue: "0xB3EAF7CC")
|
||||
String get customTextSecondaryColorDark;
|
||||
|
||||
@StringSetting(id: 1067, defaultValue: "0x80394C0A")
|
||||
String get customTextTertiaryColorLight;
|
||||
|
||||
@StringSetting(id: 1068, defaultValue: "0x80EAF7CC")
|
||||
String get customTextTertiaryColorDark;
|
||||
|
||||
@StringSetting(id: 1069, defaultValue: "0x33647E22")
|
||||
String get customShadowColorLight;
|
||||
|
||||
@StringSetting(id: 1070, defaultValue: "0x26CBEE71")
|
||||
String get customShadowColorDark;
|
||||
|
||||
@StringSetting(id: 1071, defaultValue: "0xFF92EA3B")
|
||||
String get customSuccessColorLight;
|
||||
|
||||
@StringSetting(id: 1072, defaultValue: "0xFF92EA3B")
|
||||
String get customSuccessColorDark;
|
||||
|
||||
@StringSetting(id: 1073, defaultValue: "0xFFFFA046")
|
||||
String get customWarningAccentColorLight;
|
||||
|
||||
@StringSetting(id: 1074, defaultValue: "0xFFFFA046")
|
||||
String get customWarningAccentColorDark;
|
||||
|
||||
@StringSetting(id: 1075, defaultValue: "0xFF8F531B")
|
||||
String get customWarningTextColorLight;
|
||||
|
||||
@StringSetting(id: 1076, defaultValue: "0xFFF0B37A")
|
||||
String get customWarningTextColorDark;
|
||||
|
||||
@StringSetting(id: 1077, defaultValue: "0xFFFAEBDC")
|
||||
String get customWarningCardColorLight;
|
||||
|
||||
@StringSetting(id: 1078, defaultValue: "0xFF201203")
|
||||
String get customWarningCardColorDark;
|
||||
|
||||
@StringSetting(id: 1079, defaultValue: "0xFFFF54A1")
|
||||
String get customErrorAccentColorLight;
|
||||
|
||||
@StringSetting(id: 1080, defaultValue: "0xFFFF54A1")
|
||||
String get customErrorAccentColorDark;
|
||||
|
||||
@StringSetting(id: 1081, defaultValue: "0xFF8F1B4F")
|
||||
String get customErrorTextColorLight;
|
||||
|
||||
@StringSetting(id: 1082, defaultValue: "0xFFF59EC5")
|
||||
String get customErrorTextColorDark;
|
||||
|
||||
@StringSetting(id: 1083, defaultValue: "0xFFFADCE9")
|
||||
String get customErrorCardColorLight;
|
||||
|
||||
@StringSetting(id: 1084, defaultValue: "0xFF1E030F")
|
||||
String get customErrorCardColorDark;
|
||||
|
||||
@StringSetting(
|
||||
id: 1085,
|
||||
defaultValue: "[\"0xFFFAFFF0\",\"0xFFE8F7C8\"]",
|
||||
)
|
||||
String get customBackgroundGradientLight;
|
||||
|
||||
@StringSetting(
|
||||
id: 1086,
|
||||
defaultValue: "[\"0xFF0D1202\",\"0xFF1A2405\"]",
|
||||
)
|
||||
String get customBackgroundGradientDark;
|
||||
}
|
||||
|
||||
@@ -44,9 +44,49 @@ class SettingsRegistry {
|
||||
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 notificationDeliveryMethod = EnumSetting(id: 1047, defaultValue: NotificationDeliveryMethod.auto, values: NotificationDeliveryMethod.values);
|
||||
static const customGradeColor5 = StringSetting(id: 1048, defaultValue: "0xFF22CCAD");
|
||||
static const customGradeColor4 = StringSetting(id: 1049, defaultValue: "0xFF92EA3B");
|
||||
static const customGradeColor3 = StringSetting(id: 1050, defaultValue: "0xFFF9CF00");
|
||||
static const customGradeColor2 = StringSetting(id: 1051, defaultValue: "0xFFFFA046");
|
||||
static const customGradeColor1 = StringSetting(id: 1052, defaultValue: "0xFFFF54A1");
|
||||
static const customAccentColorLight = StringSetting(id: 1053, defaultValue: "0xFFA7DC22");
|
||||
static const customAccentColorDark = StringSetting(id: 1054, defaultValue: "0xFFA7DC22");
|
||||
static const customBackgroundColorLight = StringSetting(id: 1055, defaultValue: "0xFFFAFFF0");
|
||||
static const customBackgroundColorDark = StringSetting(id: 1056, defaultValue: "0xFF0D1202");
|
||||
static const customCardColorLight = StringSetting(id: 1057, defaultValue: "0xFFF3FBDE");
|
||||
static const customCardColorDark = StringSetting(id: 1058, defaultValue: "0xFF141905");
|
||||
static const customButtonColorLight = StringSetting(id: 1059, defaultValue: "0xFFFEFFFD");
|
||||
static const customButtonColorDark = StringSetting(id: 1060, defaultValue: "0xFF20290B");
|
||||
static const customSecondaryColorLight = StringSetting(id: 1061, defaultValue: "0xFF6E8F1B");
|
||||
static const customSecondaryColorDark = StringSetting(id: 1062, defaultValue: "0xFFCBEE71");
|
||||
static const customTextColorLight = StringSetting(id: 1063, defaultValue: "0xFF394C0A");
|
||||
static const customTextColorDark = StringSetting(id: 1064, defaultValue: "0xFFEAF7CC");
|
||||
static const customTextSecondaryColorLight = StringSetting(id: 1065, defaultValue: "0xCC394C0A");
|
||||
static const customTextSecondaryColorDark = StringSetting(id: 1066, defaultValue: "0xB3EAF7CC");
|
||||
static const customTextTertiaryColorLight = StringSetting(id: 1067, defaultValue: "0x80394C0A");
|
||||
static const customTextTertiaryColorDark = StringSetting(id: 1068, defaultValue: "0x80EAF7CC");
|
||||
static const customShadowColorLight = StringSetting(id: 1069, defaultValue: "0x33647E22");
|
||||
static const customShadowColorDark = StringSetting(id: 1070, defaultValue: "0x26CBEE71");
|
||||
static const customSuccessColorLight = StringSetting(id: 1071, defaultValue: "0xFF92EA3B");
|
||||
static const customSuccessColorDark = StringSetting(id: 1072, defaultValue: "0xFF92EA3B");
|
||||
static const customWarningAccentColorLight = StringSetting(id: 1073, defaultValue: "0xFFFFA046");
|
||||
static const customWarningAccentColorDark = StringSetting(id: 1074, defaultValue: "0xFFFFA046");
|
||||
static const customWarningTextColorLight = StringSetting(id: 1075, defaultValue: "0xFF8F531B");
|
||||
static const customWarningTextColorDark = StringSetting(id: 1076, defaultValue: "0xFFF0B37A");
|
||||
static const customWarningCardColorLight = StringSetting(id: 1077, defaultValue: "0xFFFAEBDC");
|
||||
static const customWarningCardColorDark = StringSetting(id: 1078, defaultValue: "0xFF201203");
|
||||
static const customErrorAccentColorLight = StringSetting(id: 1079, defaultValue: "0xFFFF54A1");
|
||||
static const customErrorAccentColorDark = StringSetting(id: 1080, defaultValue: "0xFFFF54A1");
|
||||
static const customErrorTextColorLight = StringSetting(id: 1081, defaultValue: "0xFF8F1B4F");
|
||||
static const customErrorTextColorDark = StringSetting(id: 1082, defaultValue: "0xFFF59EC5");
|
||||
static const customErrorCardColorLight = StringSetting(id: 1083, defaultValue: "0xFFFADCE9");
|
||||
static const customErrorCardColorDark = StringSetting(id: 1084, defaultValue: "0xFF1E030F");
|
||||
static const customBackgroundGradientLight = StringSetting(id: 1085, defaultValue: "[\"0xFFFAFFF0\",\"0xFFE8F7C8\"]");
|
||||
static const customBackgroundGradientDark = StringSetting(id: 1086, defaultValue: "[\"0xFF0D1202\",\"0xFF1A2405\"]");
|
||||
|
||||
static const all = <Setting>[
|
||||
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage,
|
||||
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod, customGradeColor5, customGradeColor4, customGradeColor3, customGradeColor2, customGradeColor1, customAccentColorLight, customAccentColorDark, customBackgroundColorLight, customBackgroundColorDark, customCardColorLight, customCardColorDark, customButtonColorLight, customButtonColorDark, customSecondaryColorLight, customSecondaryColorDark, customTextColorLight, customTextColorDark, customTextSecondaryColorLight, customTextSecondaryColorDark, customTextTertiaryColorLight, customTextTertiaryColorDark, customShadowColorLight, customShadowColorDark, customSuccessColorLight, customSuccessColorDark, customWarningAccentColorLight, customWarningAccentColorDark, customWarningTextColorLight, customWarningTextColorDark, customWarningCardColorLight, customWarningCardColorDark, customErrorAccentColorLight, customErrorAccentColorDark, customErrorTextColorLight, customErrorTextColorDark, customErrorCardColorLight, customErrorCardColorDark, customBackgroundGradientLight, customBackgroundGradientDark,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -92,4 +132,44 @@ extension SettingsAccessors on SettingsRepository {
|
||||
SilentlySettable<String> get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
|
||||
SilentlySettable<NotifyWakeupInterval> get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
|
||||
SilentlySettable<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
|
||||
SilentlySettable<NotificationDeliveryMethod> get notificationDeliveryMethod => SilentlySettable(this, SettingsRegistry.notificationDeliveryMethod);
|
||||
SilentlySettable<String> get customGradeColor5 => SilentlySettable(this, SettingsRegistry.customGradeColor5);
|
||||
SilentlySettable<String> get customGradeColor4 => SilentlySettable(this, SettingsRegistry.customGradeColor4);
|
||||
SilentlySettable<String> get customGradeColor3 => SilentlySettable(this, SettingsRegistry.customGradeColor3);
|
||||
SilentlySettable<String> get customGradeColor2 => SilentlySettable(this, SettingsRegistry.customGradeColor2);
|
||||
SilentlySettable<String> get customGradeColor1 => SilentlySettable(this, SettingsRegistry.customGradeColor1);
|
||||
SilentlySettable<String> get customAccentColorLight => SilentlySettable(this, SettingsRegistry.customAccentColorLight);
|
||||
SilentlySettable<String> get customAccentColorDark => SilentlySettable(this, SettingsRegistry.customAccentColorDark);
|
||||
SilentlySettable<String> get customBackgroundColorLight => SilentlySettable(this, SettingsRegistry.customBackgroundColorLight);
|
||||
SilentlySettable<String> get customBackgroundColorDark => SilentlySettable(this, SettingsRegistry.customBackgroundColorDark);
|
||||
SilentlySettable<String> get customCardColorLight => SilentlySettable(this, SettingsRegistry.customCardColorLight);
|
||||
SilentlySettable<String> get customCardColorDark => SilentlySettable(this, SettingsRegistry.customCardColorDark);
|
||||
SilentlySettable<String> get customButtonColorLight => SilentlySettable(this, SettingsRegistry.customButtonColorLight);
|
||||
SilentlySettable<String> get customButtonColorDark => SilentlySettable(this, SettingsRegistry.customButtonColorDark);
|
||||
SilentlySettable<String> get customSecondaryColorLight => SilentlySettable(this, SettingsRegistry.customSecondaryColorLight);
|
||||
SilentlySettable<String> get customSecondaryColorDark => SilentlySettable(this, SettingsRegistry.customSecondaryColorDark);
|
||||
SilentlySettable<String> get customTextColorLight => SilentlySettable(this, SettingsRegistry.customTextColorLight);
|
||||
SilentlySettable<String> get customTextColorDark => SilentlySettable(this, SettingsRegistry.customTextColorDark);
|
||||
SilentlySettable<String> get customTextSecondaryColorLight => SilentlySettable(this, SettingsRegistry.customTextSecondaryColorLight);
|
||||
SilentlySettable<String> get customTextSecondaryColorDark => SilentlySettable(this, SettingsRegistry.customTextSecondaryColorDark);
|
||||
SilentlySettable<String> get customTextTertiaryColorLight => SilentlySettable(this, SettingsRegistry.customTextTertiaryColorLight);
|
||||
SilentlySettable<String> get customTextTertiaryColorDark => SilentlySettable(this, SettingsRegistry.customTextTertiaryColorDark);
|
||||
SilentlySettable<String> get customShadowColorLight => SilentlySettable(this, SettingsRegistry.customShadowColorLight);
|
||||
SilentlySettable<String> get customShadowColorDark => SilentlySettable(this, SettingsRegistry.customShadowColorDark);
|
||||
SilentlySettable<String> get customSuccessColorLight => SilentlySettable(this, SettingsRegistry.customSuccessColorLight);
|
||||
SilentlySettable<String> get customSuccessColorDark => SilentlySettable(this, SettingsRegistry.customSuccessColorDark);
|
||||
SilentlySettable<String> get customWarningAccentColorLight => SilentlySettable(this, SettingsRegistry.customWarningAccentColorLight);
|
||||
SilentlySettable<String> get customWarningAccentColorDark => SilentlySettable(this, SettingsRegistry.customWarningAccentColorDark);
|
||||
SilentlySettable<String> get customWarningTextColorLight => SilentlySettable(this, SettingsRegistry.customWarningTextColorLight);
|
||||
SilentlySettable<String> get customWarningTextColorDark => SilentlySettable(this, SettingsRegistry.customWarningTextColorDark);
|
||||
SilentlySettable<String> get customWarningCardColorLight => SilentlySettable(this, SettingsRegistry.customWarningCardColorLight);
|
||||
SilentlySettable<String> get customWarningCardColorDark => SilentlySettable(this, SettingsRegistry.customWarningCardColorDark);
|
||||
SilentlySettable<String> get customErrorAccentColorLight => SilentlySettable(this, SettingsRegistry.customErrorAccentColorLight);
|
||||
SilentlySettable<String> get customErrorAccentColorDark => SilentlySettable(this, SettingsRegistry.customErrorAccentColorDark);
|
||||
SilentlySettable<String> get customErrorTextColorLight => SilentlySettable(this, SettingsRegistry.customErrorTextColorLight);
|
||||
SilentlySettable<String> get customErrorTextColorDark => SilentlySettable(this, SettingsRegistry.customErrorTextColorDark);
|
||||
SilentlySettable<String> get customErrorCardColorLight => SilentlySettable(this, SettingsRegistry.customErrorCardColorLight);
|
||||
SilentlySettable<String> get customErrorCardColorDark => SilentlySettable(this, SettingsRegistry.customErrorCardColorDark);
|
||||
SilentlySettable<String> get customBackgroundGradientLight => SilentlySettable(this, SettingsRegistry.customBackgroundGradientLight);
|
||||
SilentlySettable<String> get customBackgroundGradientDark => SilentlySettable(this, SettingsRegistry.customBackgroundGradientDark);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,12 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -11,13 +16,39 @@ import 'package:path_provider/path_provider.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class WidgetCacheHelper {
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle style,
|
||||
List<LessonCacheModel> timetable,
|
||||
) {
|
||||
List<Map<String, dynamic>> timetableJson = [];
|
||||
static Map<String, dynamic> lessonToJson(LessonCacheModel lesson) {
|
||||
return {
|
||||
'name': lesson.name,
|
||||
'start': lesson.start.toIso8601String(),
|
||||
'end': lesson.end.toIso8601String(),
|
||||
'dailyNth': lesson.dailyNth,
|
||||
'yearlyNth': lesson.yearlyNth,
|
||||
'roomName': lesson.roomName,
|
||||
'substituteTeacher': lesson.substituteTeacher,
|
||||
'teacher': lesson.teacher,
|
||||
'topic': lesson.topic,
|
||||
'state': lesson.state,
|
||||
'type': lesson.type,
|
||||
// Backward-compatibility aliases for legacy receivers
|
||||
'Nev': lesson.name,
|
||||
'KezdetIdopont': lesson.start.toIso8601String(),
|
||||
'VegIdopont': lesson.end.toIso8601String(),
|
||||
'Oraszam': lesson.dailyNth,
|
||||
'TeremNeve': lesson.roomName,
|
||||
'HelyettesTanarNeve': lesson.substituteTeacher,
|
||||
};
|
||||
}
|
||||
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle? style,
|
||||
List<LessonCacheModel> timetable, {
|
||||
Map<String, dynamic>? existingColors,
|
||||
}) {
|
||||
final timetableJson = timetable.map(lessonToJson).toList();
|
||||
final colors = style != null
|
||||
? _colorsMap(style)
|
||||
: (existingColors ?? _defaultColors());
|
||||
return {'colors': colors, 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> toAndroidWidgetJson(
|
||||
@@ -27,6 +58,12 @@ class WidgetCacheHelper {
|
||||
final timetableJson = <Map<String, dynamic>>[];
|
||||
for (var lesson in timetable) {
|
||||
timetableJson.add({
|
||||
'name': lesson.name,
|
||||
'start': lesson.start.toUtc().toIso8601String(),
|
||||
'end': lesson.end.toUtc().toIso8601String(),
|
||||
'dailyNth': lesson.lessonNumber,
|
||||
'roomName': lesson.roomName,
|
||||
'substituteTeacher': lesson.substituteTeacher,
|
||||
'Nev': lesson.name,
|
||||
'KezdetIdopont': lesson.start.toUtc().toIso8601String(),
|
||||
'VegIdopont': lesson.end.toUtc().toIso8601String(),
|
||||
@@ -38,6 +75,38 @@ class WidgetCacheHelper {
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _defaultColors() {
|
||||
return {
|
||||
'background': 0xFFFAFFF0,
|
||||
'backgroundAmoled': 0xFF000000,
|
||||
'background0p': 0x00000000,
|
||||
'success': 0xFF2E7D32,
|
||||
'textPrimary': 0xFF1B1C18,
|
||||
'textSecondary': 0xFF45483D,
|
||||
'textTertiary': 0xFF76786B,
|
||||
'card': 0xFFEFF4E3,
|
||||
'cardTranslucent': 0xDDEFF4E3,
|
||||
'buttonSecondaryFill': 0xFFE0E5D4,
|
||||
'accent': 0xFF4C662B,
|
||||
'secondary': 0xFF586249,
|
||||
'shadowColor': 0x1A000000,
|
||||
'a15p': 0x264C662B,
|
||||
'warningAccent': 0xFFE65100,
|
||||
'warningText': 0xFFBF360C,
|
||||
'warning15p': 0x26E65100,
|
||||
'warningCard': 0xFFFFE0B2,
|
||||
'errorAccent': 0xFFBA1A1A,
|
||||
'errorText': 0xFFBA1A1A,
|
||||
'error15p': 0x26BA1A1A,
|
||||
'errorCard': 0xFFFFDAD6,
|
||||
'grade5': 0xFF4C662B,
|
||||
'grade4': 0xFF688837,
|
||||
'grade3': 0xFFE6A000,
|
||||
'grade2': 0xFFE66A00,
|
||||
'grade1': 0xFFBA1A1A,
|
||||
};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _colorsMap(FirkaStyle style) {
|
||||
return {
|
||||
'background': style.colors.background.toARGB32(),
|
||||
@@ -70,23 +139,84 @@ class WidgetCacheHelper {
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> refreshWidget() async {
|
||||
if (!Platform.isAndroid) return;
|
||||
try {
|
||||
await HomeWidget.updateWidget(
|
||||
name: 'TimetableWidget',
|
||||
qualifiedAndroidName: 'app.firka.naplo.glance.TimetableWidgetReceiver',
|
||||
);
|
||||
try {
|
||||
const channel = MethodChannel("firka.app/main");
|
||||
await channel.invokeMethod<void>('refreshTimetableWidget');
|
||||
} catch (_) {}
|
||||
} catch (e) {
|
||||
debugPrint('Error refreshing timetable widget: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCacheFromLessons(
|
||||
List<LessonCacheModel> lessons, {
|
||||
FirkaStyle? style,
|
||||
String? displayDate,
|
||||
}) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
Map<String, dynamic>? existingColors;
|
||||
if (style == null && await widgetFile.exists()) {
|
||||
try {
|
||||
final content = jsonDecode(await widgetFile.readAsString());
|
||||
if (content is Map && content['colors'] is Map) {
|
||||
existingColors = Map<String, dynamic>.from(content['colors']);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final data = toJson(style, lessons, existingColors: existingColors);
|
||||
if (displayDate != null) {
|
||||
data['displayDate'] = displayDate;
|
||||
}
|
||||
|
||||
await widgetFile.writeAsString(jsonEncode(data));
|
||||
await refreshWidget();
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCacheFromIsar({
|
||||
FirkaStyle? style,
|
||||
String? displayDate,
|
||||
}) async {
|
||||
try {
|
||||
final now = timeNow();
|
||||
final start = now.subtract(const Duration(days: 7));
|
||||
final end = now.add(const Duration(days: 14));
|
||||
var lessons = await isarInit.lessonCacheModels
|
||||
.filter()
|
||||
.startBetween(start, end)
|
||||
.sortByStart()
|
||||
.findAll();
|
||||
if (lessons.isEmpty) {
|
||||
lessons = await isarInit.lessonCacheModels.where().sortByStart().findAll();
|
||||
}
|
||||
await updateWidgetCacheFromLessons(
|
||||
lessons,
|
||||
style: style,
|
||||
displayDate: displayDate,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Error updating widget cache from Isar: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCache(
|
||||
FirkaStyle style,
|
||||
KretaClient client,
|
||||
) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
|
||||
final now = timeNow();
|
||||
|
||||
final start = now.subtract(Duration(days: 7));
|
||||
final end = now.add(Duration(days: 14));
|
||||
final start = now.subtract(const Duration(days: 7));
|
||||
final end = now.add(const Duration(days: 14));
|
||||
final lessons = await client.getLessons(start, end);
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons)),
|
||||
);
|
||||
await updateWidgetCacheFromLessons(lessons, style: style);
|
||||
}
|
||||
|
||||
static Future<void> generateWidgetStateForDate(
|
||||
@@ -94,13 +224,16 @@ class WidgetCacheHelper {
|
||||
FirkaStyle style,
|
||||
KretaClient client,
|
||||
) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
|
||||
final json = toJson(style, []);
|
||||
json['displayDate'] =
|
||||
final dayStart = DateTime(date.year, date.month, date.day);
|
||||
final dayEnd = dayStart.add(const Duration(hours: 23, minutes: 59));
|
||||
final lessons = await client.getLessons(dayStart, dayEnd);
|
||||
final displayDate =
|
||||
'${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
await widgetFile.writeAsString(jsonEncode(json));
|
||||
await updateWidgetCacheFromLessons(
|
||||
lessons,
|
||||
style: style,
|
||||
displayDate: displayDate,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Submodule firka/lib/l10n updated: b80df466d2...44801bea9c
@@ -20,6 +20,8 @@ import 'package:firka/ui/phone/screens/login/login_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/message/message_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/home/home_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/settings/settings_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/grade_colors/grade_colors_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/theme_editor/theme_editor_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/theme_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/themes_screen.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
|
||||
@@ -115,6 +117,20 @@ GoRouter createAppRouter() {
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/grade-colors',
|
||||
builder: (context, state) => DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: GradeColorsScreen(initData, key: state.pageKey),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/theme-editor',
|
||||
builder: (context, state) => DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: ThemeEditorScreen(initData, key: state.pageKey),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/message',
|
||||
builder: (context, state) {
|
||||
|
||||
@@ -22,17 +22,28 @@ class ShellWithNavBar extends StatelessWidget {
|
||||
final data = initData;
|
||||
final currentIndex = navigationShell.currentIndex;
|
||||
|
||||
final bottomBg =
|
||||
appStyle.colors.backgroundGradient?.last ?? appStyle.colors.background;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: child,
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.backgroundLinearGradient == null
|
||||
? appStyle.colors.background
|
||||
: null,
|
||||
gradient: appStyle.colors.backgroundLinearGradient,
|
||||
),
|
||||
child: child,
|
||||
),
|
||||
bottomNavigationBar: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
colors: [
|
||||
appStyle.colors.background,
|
||||
appStyle.colors.background.withValues(alpha: 0.0),
|
||||
bottomBg,
|
||||
bottomBg.withValues(alpha: 0.0),
|
||||
],
|
||||
stops: const [0.0, 1.0],
|
||||
),
|
||||
|
||||
86
firka/lib/services/alarm_notification_service.dart
Normal file
86
firka/lib/services/alarm_notification_service.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/notification_diff_service.dart';
|
||||
|
||||
const int _alarmNotificationSyncId = 910001;
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> alarmNotificationWakeupCallback() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await NotificationDiffService.checkAll();
|
||||
}
|
||||
|
||||
class AlarmNotificationService {
|
||||
static final Logger _logger = Logger('AlarmNotificationService');
|
||||
static bool _isInitialized = false;
|
||||
|
||||
@visibleForTesting
|
||||
static bool? isAndroidOverride;
|
||||
|
||||
static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
|
||||
|
||||
@visibleForTesting
|
||||
static void resetForTesting() {
|
||||
_isInitialized = false;
|
||||
isAndroidOverride = null;
|
||||
}
|
||||
|
||||
static bool get isInitialized => _isInitialized;
|
||||
|
||||
static Future<void> initialize() async {
|
||||
if (_isInitialized || !_isAndroid) return;
|
||||
try {
|
||||
await AndroidAlarmManager.initialize();
|
||||
_isInitialized = true;
|
||||
_logger.info('AlarmNotificationService initialized');
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to initialize AlarmNotificationService: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Duration _durationFor(NotifyWakeupInterval interval) {
|
||||
switch (interval) {
|
||||
case NotifyWakeupInterval.hourly:
|
||||
return const Duration(hours: 1);
|
||||
case NotifyWakeupInterval.twoHourly:
|
||||
return const Duration(hours: 2);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> schedule() async {
|
||||
if (!_isAndroid) return;
|
||||
try {
|
||||
await initialize();
|
||||
final interval = _durationFor(Settings.notifyWakeupInterval.value);
|
||||
await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
|
||||
await AndroidAlarmManager.periodic(
|
||||
interval,
|
||||
_alarmNotificationSyncId,
|
||||
alarmNotificationWakeupCallback,
|
||||
exact: false,
|
||||
wakeup: true,
|
||||
rescheduleOnReboot: true,
|
||||
);
|
||||
_logger.info('Scheduled periodic alarm every ${interval.inHours}h');
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to schedule alarm: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> cancel() async {
|
||||
if (!_isAndroid) return;
|
||||
try {
|
||||
await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
|
||||
_logger.info('Cancelled periodic alarm');
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to cancel alarm: $e', e, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,11 +151,29 @@ class FcmService {
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool>? _pendingPermissionRequest;
|
||||
|
||||
static Future<bool> _requestPermission() async {
|
||||
if (_pendingPermissionRequest != null) {
|
||||
return await _pendingPermissionRequest!;
|
||||
}
|
||||
final status = await Permission.notification.status;
|
||||
if (status.isGranted) return true;
|
||||
final result = await Permission.notification.request();
|
||||
return result.isGranted;
|
||||
|
||||
final future = () async {
|
||||
try {
|
||||
final result = await Permission.notification.request();
|
||||
return result.isGranted;
|
||||
} catch (e) {
|
||||
_logger.warning('Failed to request notification permission: $e');
|
||||
return false;
|
||||
} finally {
|
||||
_pendingPermissionRequest = null;
|
||||
}
|
||||
}();
|
||||
|
||||
_pendingPermissionRequest = future;
|
||||
return await future;
|
||||
}
|
||||
|
||||
static String? _currentStudentId(KretaClient? client) {
|
||||
|
||||
@@ -15,6 +15,8 @@ class LocalNotificationService {
|
||||
FlutterLocalNotificationsPlugin();
|
||||
static bool _initialized = false;
|
||||
|
||||
static final List<({int id, String title, String body})> postedNotifications = [];
|
||||
|
||||
static Future<void> init() async {
|
||||
if (_initialized) return;
|
||||
|
||||
@@ -38,6 +40,12 @@ class LocalNotificationService {
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/// Returns active notifications currently shown in the system status bar (Android 6.0+).
|
||||
static Future<List<ActiveNotification>> getActiveNotifications() async {
|
||||
await init();
|
||||
return await _plugin.getActiveNotifications();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -46,6 +54,8 @@ class LocalNotificationService {
|
||||
required String title,
|
||||
required String body,
|
||||
}) async {
|
||||
postedNotifications.add((id: id, title: title, body: body));
|
||||
|
||||
await init();
|
||||
await _plugin.show(
|
||||
id,
|
||||
|
||||
150
firka/lib/services/notification_delivery_service.dart
Normal file
150
firka/lib/services/notification_delivery_service.dart
Normal file
@@ -0,0 +1,150 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/alarm_notification_service.dart';
|
||||
import 'package:firka/services/fcm_service.dart';
|
||||
|
||||
class NotificationDeliveryService {
|
||||
static final Logger _logger = Logger('NotificationDeliveryService');
|
||||
static const MethodChannel _mainChannel = MethodChannel('firka.app/main');
|
||||
|
||||
static bool? _cachedGmsAvailable;
|
||||
|
||||
@visibleForTesting
|
||||
static bool? gmsAvailabilityOverride;
|
||||
|
||||
@visibleForTesting
|
||||
static bool? isAndroidOverride;
|
||||
|
||||
static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
|
||||
|
||||
@visibleForTesting
|
||||
static void resetForTesting() {
|
||||
_cachedGmsAvailable = null;
|
||||
gmsAvailabilityOverride = null;
|
||||
isAndroidOverride = null;
|
||||
}
|
||||
|
||||
static Future<bool> isGmsAvailable({bool forceRefresh = false}) async {
|
||||
if (gmsAvailabilityOverride != null) {
|
||||
return gmsAvailabilityOverride!;
|
||||
}
|
||||
if (!_isAndroid) return false;
|
||||
if (_cachedGmsAvailable != null && !forceRefresh) {
|
||||
return _cachedGmsAvailable!;
|
||||
}
|
||||
try {
|
||||
final available = await _mainChannel.invokeMethod<bool>('isGmsAvailable');
|
||||
_cachedGmsAvailable = available ?? false;
|
||||
return _cachedGmsAvailable!;
|
||||
} catch (e) {
|
||||
_logger.warning('Error checking GMS availability: $e');
|
||||
_cachedGmsAvailable = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<NotificationDeliveryMethod> getEffectiveMethod() async {
|
||||
final configured = Settings.notificationDeliveryMethod.value;
|
||||
if (configured != NotificationDeliveryMethod.auto) {
|
||||
return configured;
|
||||
}
|
||||
final gms = await isGmsAvailable();
|
||||
return gms ? NotificationDeliveryMethod.fcm : NotificationDeliveryMethod.alarm;
|
||||
}
|
||||
|
||||
static Future<void> initialize() async {
|
||||
if (!_isAndroid) return;
|
||||
|
||||
final gms = await isGmsAvailable();
|
||||
_logger.info('Initializing NotificationDeliveryService (GMS available: $gms)');
|
||||
|
||||
await AlarmNotificationService.initialize();
|
||||
|
||||
if (gms) {
|
||||
await FcmService.initialize();
|
||||
}
|
||||
|
||||
await syncDeliveryBackend();
|
||||
}
|
||||
|
||||
static Future<void> syncDeliveryBackend() async {
|
||||
if (!_isAndroid) return;
|
||||
|
||||
try {
|
||||
if (!Settings.notifyAll.value) {
|
||||
_logger.info('Push notifications disabled, tearing down delivery backends');
|
||||
await FcmService.handleEnabledChange(false);
|
||||
await AlarmNotificationService.cancel();
|
||||
return;
|
||||
}
|
||||
|
||||
final effectiveMethod = await getEffectiveMethod();
|
||||
_logger.info('Syncing delivery backend for effective method: $effectiveMethod');
|
||||
|
||||
switch (effectiveMethod) {
|
||||
case NotificationDeliveryMethod.fcm:
|
||||
await AlarmNotificationService.cancel();
|
||||
await FcmService.handleEnabledChange(true);
|
||||
break;
|
||||
case NotificationDeliveryMethod.alarm:
|
||||
await FcmService.handleEnabledChange(false);
|
||||
await AlarmNotificationService.schedule();
|
||||
break;
|
||||
case NotificationDeliveryMethod.auto:
|
||||
break;
|
||||
}
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to sync delivery backend: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> handleWakeupIntervalChange() async {
|
||||
if (!Settings.notifyAll.value) return;
|
||||
|
||||
final effectiveMethod = await getEffectiveMethod();
|
||||
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
|
||||
await FcmService.handleWakeupIntervalChange();
|
||||
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
|
||||
await AlarmNotificationService.schedule();
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> onUserLogin({required KretaClient client}) async {
|
||||
if (!_isAndroid) return;
|
||||
|
||||
try {
|
||||
final effectiveMethod = await getEffectiveMethod();
|
||||
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
|
||||
await FcmService.onUserLogin(client: client);
|
||||
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
|
||||
await AlarmNotificationService.schedule();
|
||||
}
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to process onUserLogin: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> onUserLogout() async {
|
||||
if (!_isAndroid) return;
|
||||
|
||||
final effectiveMethod = await getEffectiveMethod();
|
||||
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
|
||||
await FcmService.onUserLogout();
|
||||
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
|
||||
final tokenCount = await isarInit.tokenModels.count();
|
||||
if (tokenCount == 0) {
|
||||
await AlarmNotificationService.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/last_seen.dart';
|
||||
@@ -13,6 +16,7 @@ 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/data/widget.dart';
|
||||
import 'package:firka/services/fcm_headless_bootstrap.dart';
|
||||
import 'package:firka/services/local_notification_service.dart';
|
||||
|
||||
@@ -96,10 +100,16 @@ class NotificationDiffService {
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyLessons.value) {
|
||||
final now = DateTime.now();
|
||||
final lessons = await client.getLessons(now, now.add(const Duration(days: 7)));
|
||||
final now = DateTime.now();
|
||||
final lessons = await client.getLessons(now, now.add(const Duration(days: 7)));
|
||||
|
||||
final selectedToken = Settings.getSelectedToken();
|
||||
final isActiveAccount = selectedToken == null || selectedToken.key == accountKey;
|
||||
if (isActiveAccount) {
|
||||
await _checkAndUpdateWidget(lessons);
|
||||
}
|
||||
|
||||
if (Settings.notifyLessons.value) {
|
||||
final cancelled = lessons.where(_isCancelledLesson).toList();
|
||||
final substituted = lessons
|
||||
.where((l) => !_isCancelledLesson(l) && l.substituteTeacher != null)
|
||||
@@ -198,6 +208,12 @@ class NotificationDiffService {
|
||||
body: body(newItems),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// First run: seed baseline silently without spamming backlog.
|
||||
// If there are no items yet, record current time so subsequent items notify.
|
||||
final baseline = LastSeen.newestOf(items) ?? LastSeen(DateTime.now(), 0);
|
||||
await LastSeenHelper.set(accountKey, kind, baseline);
|
||||
return;
|
||||
}
|
||||
|
||||
final newest = LastSeen.newestOf(items);
|
||||
@@ -230,6 +246,45 @@ class NotificationDiffService {
|
||||
static int _notificationId(int accountKey, String kind) =>
|
||||
Object.hash(accountKey, kind) & 0x7fffffff;
|
||||
|
||||
static Future<void> _checkAndUpdateWidget(List<LessonCacheModel> lessons) async {
|
||||
try {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
if (_hasTimetableChanged(lessons, widgetFile)) {
|
||||
_logger.info('Timetable changed during FCM sync, updating widget');
|
||||
await WidgetCacheHelper.updateWidgetCacheFromLessons(lessons);
|
||||
}
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to update widget during FCM sync: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static bool _hasTimetableChanged(List<LessonCacheModel> lessons, File widgetFile) {
|
||||
if (!widgetFile.existsSync()) return true;
|
||||
try {
|
||||
final content = jsonDecode(widgetFile.readAsStringSync());
|
||||
final cachedTt = content['timetable'] as List?;
|
||||
if (cachedTt == null) return true;
|
||||
if (cachedTt.length != lessons.length) return true;
|
||||
for (int i = 0; i < lessons.length; i++) {
|
||||
final l = lessons[i];
|
||||
final c = cachedTt[i] as Map?;
|
||||
if (c == null) return true;
|
||||
if (c['name'] != l.name ||
|
||||
c['start'] != l.start.toIso8601String() ||
|
||||
c['end'] != l.end.toIso8601String() ||
|
||||
c['dailyNth'] != l.dailyNth ||
|
||||
c['roomName'] != l.roomName ||
|
||||
c['substituteTeacher'] != l.substituteTeacher) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (_) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
87
firka/lib/ui/components/color_slider.dart
Normal file
87
firka/lib/ui/components/color_slider.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import "package:flutter/material.dart";
|
||||
import "package:firka/ui/theme/style.dart";
|
||||
import "package:firka_common/ui/components/firka_card.dart";
|
||||
|
||||
class ColorSlider extends StatelessWidget {
|
||||
final double value;
|
||||
final LinearGradient trackGradient;
|
||||
final Color thumbColor;
|
||||
final ValueChanged<double> onChanged;
|
||||
|
||||
const ColorSlider({
|
||||
required this.value,
|
||||
required this.trackGradient,
|
||||
required this.thumbColor,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
static const _trackHeight = 52.0;
|
||||
static const _thumbSize = 28.0;
|
||||
static const _thumbRadius = _thumbSize / 2;
|
||||
static const _edgePad = 16.0;
|
||||
|
||||
void _setFromLocalX(double localX, double width) {
|
||||
final start = _edgePad + _thumbRadius;
|
||||
final end = width - _edgePad - _thumbRadius;
|
||||
if (end <= start) return;
|
||||
final t = ((localX - start) / (end - start)).clamp(0.0, 1.0);
|
||||
onChanged(t);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FirkaCard.single(
|
||||
width: double.infinity,
|
||||
height: _trackHeight,
|
||||
padding: EdgeInsets.zero,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final start = _edgePad + _thumbRadius;
|
||||
final end = width - _edgePad - _thumbRadius;
|
||||
final thumbLeft = start + value * (end - start) - _thumbRadius;
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTapDown: (d) => _setFromLocalX(d.localPosition.dx, width),
|
||||
onHorizontalDragUpdate: (d) =>
|
||||
_setFromLocalX(d.localPosition.dx, width),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Container(decoration: BoxDecoration(gradient: trackGradient)),
|
||||
Positioned(
|
||||
left: thumbLeft,
|
||||
top: (_trackHeight - _thumbSize) / 2,
|
||||
child: Container(
|
||||
width: _thumbSize,
|
||||
height: _thumbSize,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: thumbColor,
|
||||
border: Border.all(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
width: 3,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
offset: const Offset(0, 1),
|
||||
blurRadius: appStyle.isLight ? 3 : 0,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ Future<void> showLessonBottomSheet(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/timetable/subject', extra: lesson.subject);
|
||||
context.go('/timetable/subject', extra: lesson.subject.loadAndGet()!);
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:firka/core/image_preloader.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/core/swear_generator.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
|
||||
class ErrorPage extends StatelessWidget {
|
||||
final String exception;
|
||||
@@ -22,20 +23,9 @@ class ErrorPage extends StatelessWidget {
|
||||
Column(
|
||||
children: [
|
||||
SizedBox(height: 48),
|
||||
Container(
|
||||
const DaveMascot.error(
|
||||
width: 50,
|
||||
height: 50,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: ShapeDecoration(
|
||||
image: DecorationImage(
|
||||
image: PreloadedImageProvider(
|
||||
FirkaBundle(),
|
||||
('assets/images/logos/dave_error.png'),
|
||||
),
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
shape: ContinuousRectangleBorder(),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
|
||||
@@ -10,10 +10,10 @@ import 'package:firka/ui/components/firka_icon_button.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_chart.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
@@ -163,8 +163,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/images/logos/dave.svg",
|
||||
const DaveMascot(
|
||||
width: 48,
|
||||
height: 48,
|
||||
),
|
||||
|
||||
@@ -146,6 +146,7 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
|
||||
final todayLesson = widget.data.client!.cache
|
||||
.getClassLessons()
|
||||
.on(now)
|
||||
.sortByStart()
|
||||
.findAllSync();
|
||||
|
||||
for (final item in infoItems) {
|
||||
|
||||
@@ -26,6 +26,7 @@ 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';
|
||||
@@ -428,6 +429,16 @@ 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(
|
||||
@@ -471,3 +482,70 @@ 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(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
531
firka/lib/ui/phone/screens/grade_colors/grade_colors_screen.dart
Normal file
531
firka/lib/ui/phone/screens/grade_colors/grade_colors_screen.dart
Normal file
@@ -0,0 +1,531 @@
|
||||
import "dart:math" as math;
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/core/bloc/theme_cubit.dart";
|
||||
import "package:firka/core/extensions.dart";
|
||||
import "package:firka/core/settings/setting.dart";
|
||||
import "package:firka/core/settings/settings_repository.dart";
|
||||
import "package:firka/core/settings/settings_schema.dart";
|
||||
import "package:firka/ui/components/color_slider.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:firka_common/ui/components/firka_card.dart";
|
||||
import "package:firka_common/ui/theme/style.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:flutter/services.dart";
|
||||
import "package:flutter_bloc/flutter_bloc.dart";
|
||||
import "package:go_router/go_router.dart";
|
||||
import "package:majesticons_flutter/majesticons_flutter.dart";
|
||||
|
||||
class GradeColorsScreen extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
|
||||
const GradeColorsScreen(this.data, {super.key});
|
||||
|
||||
@override
|
||||
State<GradeColorsScreen> createState() => _GradeColorsScreenState();
|
||||
}
|
||||
|
||||
StringSetting _settingFor(int grade) {
|
||||
switch (grade) {
|
||||
case 5:
|
||||
return SettingsRegistry.customGradeColor5;
|
||||
case 4:
|
||||
return SettingsRegistry.customGradeColor4;
|
||||
case 3:
|
||||
return SettingsRegistry.customGradeColor3;
|
||||
case 2:
|
||||
return SettingsRegistry.customGradeColor2;
|
||||
default:
|
||||
return SettingsRegistry.customGradeColor1;
|
||||
}
|
||||
}
|
||||
|
||||
Color _defaultFor(int grade) {
|
||||
switch (grade) {
|
||||
case 5:
|
||||
return const Color(0xFF22CCAD);
|
||||
case 4:
|
||||
return const Color(0xFF92EA3B);
|
||||
case 3:
|
||||
return const Color(0xFFF9CF00);
|
||||
case 2:
|
||||
return const Color(0xFFFFA046);
|
||||
default:
|
||||
return const Color(0xFFFF54A1);
|
||||
}
|
||||
}
|
||||
|
||||
class _GradeColorsScreenState extends State<GradeColorsScreen>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late int _selectedGrade;
|
||||
late HSVColor _hsv;
|
||||
|
||||
final _hexController = TextEditingController();
|
||||
bool _hexFocused = false;
|
||||
|
||||
late final AnimationController _ringController;
|
||||
Tween<double> _ringTween = Tween<double>(begin: 0, end: 0);
|
||||
double _ringRotation = 0;
|
||||
|
||||
SettingsRepository get _settings => widget.data.settings;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_selectedGrade = 5;
|
||||
_hsv = HSVColor.fromColor(_currentColor(_selectedGrade));
|
||||
_syncHexField();
|
||||
_ringController = AnimationController(vsync: this)
|
||||
..addListener(() {
|
||||
setState(() {
|
||||
_ringRotation = _ringTween.transform(
|
||||
Curves.easeInOutCubic.transform(_ringController.value),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hexController.dispose();
|
||||
_ringController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Color _currentColor(int grade) {
|
||||
final raw = _settings.get(_settingFor(grade));
|
||||
return raw.toColorFromHexSetting();
|
||||
}
|
||||
|
||||
void _syncHexField() {
|
||||
if (!_hexFocused) {
|
||||
final hex = _hsv.toColor().toHexSetting().substring(4);
|
||||
_hexController.text = hex.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _applyHsv(HSVColor hsv) async {
|
||||
setState(() => _hsv = hsv);
|
||||
_syncHexField();
|
||||
await _settings.set(
|
||||
_settingFor(_selectedGrade),
|
||||
hsv.toColor().toHexSetting(),
|
||||
);
|
||||
if (!mounted) return;
|
||||
context.read<ThemeCubit>().refresh();
|
||||
}
|
||||
|
||||
Future<void> _selectGrade(int grade) async {
|
||||
final hubIndex = _roleOrder.indexOf("hub");
|
||||
final targetMod = (hubIndex - _ring.indexOf(grade)) % _ring.length;
|
||||
var delta = (targetMod - _ringRotation) % _ring.length;
|
||||
if (delta > _ring.length / 2) delta -= _ring.length;
|
||||
final target = _ringRotation + delta;
|
||||
|
||||
_ringTween = Tween<double>(begin: _ringRotation, end: target);
|
||||
|
||||
_ringController
|
||||
..duration = Duration(
|
||||
milliseconds: (150 * delta.abs()).clamp(180, 420).round(),
|
||||
)
|
||||
..forward(from: 0);
|
||||
|
||||
setState(() {
|
||||
_selectedGrade = grade;
|
||||
_hsv = HSVColor.fromColor(_currentColor(grade));
|
||||
});
|
||||
_syncHexField();
|
||||
}
|
||||
|
||||
Future<void> _reset() async {
|
||||
final defaultColor = _defaultFor(_selectedGrade);
|
||||
await _applyHsv(HSVColor.fromColor(defaultColor));
|
||||
}
|
||||
|
||||
Future<void> _randomize() async {
|
||||
await _applyHsv(math.Random().nextVividHSVColor());
|
||||
}
|
||||
|
||||
void _onHexSubmit(String value) {
|
||||
final cleaned = value.replaceAll("#", "").trim();
|
||||
if (cleaned.length != 6) return;
|
||||
final parsed = int.tryParse("0xFF$cleaned");
|
||||
if (parsed == null) return;
|
||||
_applyHsv(HSVColor.fromColor(Color(parsed)));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider<ThemeCubit>.value(
|
||||
value: widget.data.themeCubit,
|
||||
child: BlocBuilder<ThemeCubit, ThemeState>(
|
||||
builder: (context, _) {
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_header(context),
|
||||
const SizedBox(height: 24),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_gradeBubbles(),
|
||||
const SizedBox(height: 28),
|
||||
_hueSlider(),
|
||||
const SizedBox(height: 8),
|
||||
_saturationSlider(),
|
||||
const SizedBox(height: 8),
|
||||
_valueSlider(),
|
||||
const SizedBox(height: 20),
|
||||
_hexRow(),
|
||||
const SizedBox(height: 12),
|
||||
_gradeTabBar(),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _header(BuildContext context) {
|
||||
final l10n = widget.data.l10n;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 0),
|
||||
child: GestureDetector(
|
||||
onTap: () => context.pop(),
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.chevronLeftLine,
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
l10n.s_customization,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
headingText(l10n.s_c_grade_colors_header),
|
||||
style: appStyle.fonts.H_H1.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static const _roleSlots = <String, (double dx, double dy, double sizeFactor)>{
|
||||
"topLeft": (0.39, 0.22, 0.82),
|
||||
"topRight": (0.625, 0.22, 0.82),
|
||||
"midRight": (0.80, 0.46, 0.76),
|
||||
"hub": (0.505, 0.66, 1.0),
|
||||
"midLeft": (0.22, 0.46, 0.76),
|
||||
};
|
||||
static const _roleOrder = [
|
||||
"topLeft",
|
||||
"topRight",
|
||||
"midRight",
|
||||
"hub",
|
||||
"midLeft",
|
||||
];
|
||||
|
||||
static const _ring = [2, 3, 4, 5, 1];
|
||||
|
||||
Widget _gradeBubbles() {
|
||||
const maxCenterSize = 88.0;
|
||||
const clusterHeight = 190.0;
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final centerSize = math.min(maxCenterSize, width * 0.24);
|
||||
|
||||
return SizedBox(
|
||||
height: clusterHeight,
|
||||
width: width,
|
||||
child: Stack(
|
||||
children: [
|
||||
for (final grade in _ring)
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final u = _ring.indexOf(grade) + _ringRotation;
|
||||
final idx0 = u.floor();
|
||||
final frac = u - idx0;
|
||||
final slotA = _roleSlots[_roleOrder[idx0 % _ring.length]]!;
|
||||
final slotB =
|
||||
_roleSlots[_roleOrder[(idx0 + 1) % _ring.length]]!;
|
||||
final dx = slotA.$1 + (slotB.$1 - slotA.$1) * frac;
|
||||
final dy = slotA.$2 + (slotB.$2 - slotA.$2) * frac;
|
||||
final sizeFactor = slotA.$3 + (slotB.$3 - slotA.$3) * frac;
|
||||
final size = centerSize * sizeFactor;
|
||||
|
||||
return Positioned(
|
||||
left: dx * width - size / 2,
|
||||
top: dy * clusterHeight - size / 2,
|
||||
child: _gradeBubble(grade, size: size),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _gradeBubble(int grade, {required double size}) {
|
||||
final isSelected = grade == _selectedGrade;
|
||||
final color = isSelected ? _hsv.toColor() : _currentColor(grade);
|
||||
final pastel = Color.alphaBlend(color.withAlpha(38), appStyle.colors.card);
|
||||
const ringWidth = 4.0;
|
||||
|
||||
final circle = FilledCircle(
|
||||
diameter: isSelected ? size - ringWidth * 2 : size,
|
||||
color: pastel,
|
||||
child: Text(
|
||||
"$grade",
|
||||
style: appStyle.fonts.H_H1.copyWith(color: color, fontSize: size * 0.4),
|
||||
),
|
||||
);
|
||||
|
||||
return GestureDetector(
|
||||
onTap: isSelected ? null : () => _selectGrade(grade),
|
||||
child: Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: isSelected
|
||||
? Border.all(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
width: ringWidth,
|
||||
)
|
||||
: null,
|
||||
boxShadow: isSelected && appStyle.isLight
|
||||
? [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
]
|
||||
: null,
|
||||
),
|
||||
child: Center(child: circle),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _hueSlider() {
|
||||
return ColorSlider(
|
||||
value: _hsv.hue / 360,
|
||||
trackGradient: const LinearGradient(
|
||||
colors: [
|
||||
Color(0xFFFF0000),
|
||||
Color(0xFFFFFF00),
|
||||
Color(0xFF00FF00),
|
||||
Color(0xFF00FFFF),
|
||||
Color(0xFF0000FF),
|
||||
Color(0xFFFF00FF),
|
||||
Color(0xFFFF0000),
|
||||
],
|
||||
),
|
||||
thumbColor: _hsv.toColor(),
|
||||
onChanged: (t) => _applyHsv(_hsv.withHue(t * 360)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _saturationSlider() {
|
||||
final fullSat = _hsv.withSaturation(1).withValue(1).toColor();
|
||||
return ColorSlider(
|
||||
value: _hsv.saturation,
|
||||
trackGradient: LinearGradient(colors: [Colors.white, fullSat]),
|
||||
thumbColor: _hsv.withValue(1).toColor(),
|
||||
onChanged: (t) => _applyHsv(_hsv.withSaturation(t)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _valueSlider() {
|
||||
final fullV = _hsv.withValue(1).toColor();
|
||||
return ColorSlider(
|
||||
value: _hsv.value,
|
||||
trackGradient: LinearGradient(colors: [Colors.black, fullV]),
|
||||
thumbColor: _hsv.toColor(),
|
||||
onChanged: (t) => _applyHsv(_hsv.withValue(t)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _hexRow() {
|
||||
return FirkaCard(
|
||||
left: [
|
||||
_iconCircle(icon: Majesticon.reloadLine, onTap: _reset, faded: true),
|
||||
const SizedBox(width: 12),
|
||||
Container(
|
||||
width: 28,
|
||||
height: 28,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: _hsv.toColor(),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
blurRadius: appStyle.isLight ? 3 : 0,
|
||||
offset: const Offset(0, 1),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
"HEX",
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 96,
|
||||
child: Focus(
|
||||
onFocusChange: (focused) => setState(() => _hexFocused = focused),
|
||||
child: TextField(
|
||||
controller: _hexController,
|
||||
keyboardType: TextInputType.text,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
maxLength: 6,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[0-9a-fA-F]')),
|
||||
],
|
||||
onSubmitted: _onHexSubmit,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
counterText: "",
|
||||
border: InputBorder.none,
|
||||
isDense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
hintText: "FFFFFF",
|
||||
hintStyle: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textTertiary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
_iconCircle(
|
||||
icon: Majesticon.repeatCircleLine,
|
||||
onTap: _randomize,
|
||||
accent: true,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _iconCircle({
|
||||
required Object icon,
|
||||
required VoidCallback onTap,
|
||||
bool faded = false,
|
||||
bool accent = false,
|
||||
}) {
|
||||
final bgColor = accent
|
||||
? appStyle.colors.accent
|
||||
: appStyle.colors.buttonSecondaryFill;
|
||||
final iconColor = accent
|
||||
? appStyle.colors.textPrimary
|
||||
: appStyle.colors.textSecondary;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: bgColor,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
blurRadius: appStyle.isLight ? 2 : 0,
|
||||
offset: const Offset(0, 1),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
icon,
|
||||
size: 18,
|
||||
color: iconColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _gradeTabBar() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
for (final grade in [1, 2, 3, 4, 5]) ...[
|
||||
if (grade != 1) const SizedBox(width: 8),
|
||||
_gradeTab(grade),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _gradeTab(int grade) {
|
||||
final isSelected = grade == _selectedGrade;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: isSelected ? null : () => _selectGrade(grade),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 180),
|
||||
curve: Curves.easeOut,
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isSelected ? appStyle.colors.accent : appStyle.colors.card,
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
"$grade",
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: isSelected
|
||||
? appStyle.colors.textPrimary
|
||||
: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
|
||||
import 'package:firka/core/bloc/profile_picture_cubit.dart';
|
||||
import 'package:firka/core/bloc/settings_cubit.dart';
|
||||
@@ -67,10 +67,7 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
await initData.client!.renewCache(reInit: true);
|
||||
|
||||
if (Platform.isAndroid) {
|
||||
await HomeWidget.updateWidget(
|
||||
qualifiedAndroidName:
|
||||
"app.firka.naplo.glance.TimetableWidgetReceiver",
|
||||
);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
}
|
||||
} catch (e) {
|
||||
if (_disposed) return;
|
||||
@@ -130,15 +127,23 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: SafeArea(
|
||||
child: SizedBox(
|
||||
height: MediaQuery.of(context).size.height,
|
||||
child: Stack(
|
||||
children: [
|
||||
widget.child,
|
||||
?(_toastOverlay(context)),
|
||||
],
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.backgroundLinearGradient == null
|
||||
? appStyle.colors.background
|
||||
: null,
|
||||
gradient: appStyle.colors.backgroundLinearGradient,
|
||||
),
|
||||
child: SafeArea(
|
||||
child: SizedBox(
|
||||
height: MediaQuery.of(context).size.height,
|
||||
child: Stack(
|
||||
children: [
|
||||
widget.child,
|
||||
?(_toastOverlay(context)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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/notification_delivery_service.dart";
|
||||
import "package:firka/ui/shared/firka_icon.dart";
|
||||
import "package:firka/ui/theme/style.dart";
|
||||
import "package:firka/ui/phone/widgets/login_webview.dart";
|
||||
@@ -137,15 +137,14 @@ class SettingsAccountPickerView extends StatelessWidget {
|
||||
return;
|
||||
}
|
||||
|
||||
await FcmService.onUserLogout();
|
||||
await NotificationDeliveryService.onUserLogout();
|
||||
|
||||
await data.settings.setSelectedAccountKey(token.key);
|
||||
await initializeApp();
|
||||
|
||||
if (data.client != null) {
|
||||
await FcmService.onUserLogin(
|
||||
await NotificationDeliveryService.onUserLogin(
|
||||
client: data.client!,
|
||||
settingsStore: data.settings,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -157,7 +156,7 @@ class SettingsAccountPickerView extends StatelessWidget {
|
||||
|
||||
Future<void> _logout(BuildContext context) async {
|
||||
try {
|
||||
await FcmService.onUserLogout();
|
||||
await NotificationDeliveryService.onUserLogout();
|
||||
|
||||
final active = data.client!.cache.token.key;
|
||||
|
||||
|
||||
@@ -7,9 +7,12 @@ import "package:firka/core/settings/settings_schema.dart";
|
||||
import "package:firka/core/settings/settings_ui.dart";
|
||||
import "package:firka/core/settings/title_font.dart";
|
||||
import "package:firka/l10n/app_localizations.dart";
|
||||
import "package:firka/ui/phone/screens/themes/builtin_theme_id.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";
|
||||
@@ -43,14 +46,20 @@ class _SettingsPersonalizationViewState
|
||||
|
||||
Color get _selectedSurface => appStyle.colors.buttonSecondaryFill;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
regenerateM3eTheme().then((_) {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
Widget _sectionLabel(String text) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 4, bottom: 8, top: 16),
|
||||
child: Text(
|
||||
text,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -76,29 +85,20 @@ class _SettingsPersonalizationViewState
|
||||
final left = <Widget>[];
|
||||
if (iconType != null && iconData != null) {
|
||||
left.add(
|
||||
FirkaIconWidget(
|
||||
iconType,
|
||||
iconData,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
FirkaIconWidget(iconType, iconData, color: appStyle.colors.accent),
|
||||
);
|
||||
left.add(const SizedBox(width: 8));
|
||||
}
|
||||
left.add(
|
||||
Text(
|
||||
title,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
);
|
||||
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: FirkaCard(
|
||||
left: left,
|
||||
right: [_externalArrow()],
|
||||
),
|
||||
child: FirkaCard(left: left, right: [_externalArrow()]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -125,36 +125,98 @@ class _SettingsPersonalizationViewState
|
||||
);
|
||||
}
|
||||
|
||||
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)),
|
||||
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 isCustomTheme =
|
||||
!isBuiltinThemeId(_settings.get(SettingsRegistry.selectedThemeId));
|
||||
|
||||
if (isCustomTheme) {
|
||||
return IgnorePointer(
|
||||
child: _PresetSwatchPager(
|
||||
key: const ValueKey("core-themes-custom"),
|
||||
swatches: [
|
||||
[
|
||||
appStyle.colors.secondary,
|
||||
appStyle.colors.accent,
|
||||
appStyle.colors.background,
|
||||
appStyle.colors.card,
|
||||
],
|
||||
),
|
||||
],
|
||||
selectedIndex: 0,
|
||||
onSelected: (_) {},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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 _stubCustomizeButton() {
|
||||
return FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
_l10n.s_c_customize,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
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 _customizeButton({required String route}) {
|
||||
return GestureDetector(
|
||||
onTap: () => context.push(route),
|
||||
child: FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
_l10n.s_c_customize,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -180,9 +242,7 @@ class _SettingsPersonalizationViewState
|
||||
left: [
|
||||
Text(
|
||||
label,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
],
|
||||
right: selected
|
||||
@@ -220,12 +280,8 @@ class _SettingsPersonalizationViewState
|
||||
},
|
||||
child: FirkaCard(
|
||||
color: selected ? _selectedSurface : _mutedCardColor,
|
||||
left: [
|
||||
Text(font.displayName, style: style),
|
||||
],
|
||||
right: selected
|
||||
? [_checkMark(), const SizedBox(width: 8)]
|
||||
: const [],
|
||||
left: [Text(font.displayName, style: style)],
|
||||
right: selected ? [_checkMark(), const SizedBox(width: 8)] : const [],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -261,10 +317,7 @@ class _SettingsPersonalizationViewState
|
||||
Widget _fontPicker(TitleFont selected) {
|
||||
if (!_fontPickerExpanded) {
|
||||
return Column(
|
||||
children: [
|
||||
_fontCard(selected, selected: true),
|
||||
_changeRow(),
|
||||
],
|
||||
children: [_fontCard(selected, selected: true), _changeRow()],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -386,7 +439,8 @@ class _SettingsPersonalizationViewState
|
||||
final thickLeft = thickRight - thickWidth;
|
||||
|
||||
final showThin = thumbRight < thinLeft || thumbLeft > thinRight;
|
||||
final showThick = thumbRight < thickLeft || thumbLeft > thickRight;
|
||||
final showThick =
|
||||
thumbRight < thickLeft || thumbLeft > thickRight;
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
@@ -560,33 +614,25 @@ class _SettingsPersonalizationViewState
|
||||
_shortcutRow(
|
||||
title: _l10n.s_c_change_app_icon,
|
||||
onTap: () {
|
||||
context.push("/settings", extra: [
|
||||
SettingsUiBackHeader(_l10n.s_customization, () => true),
|
||||
...widget.item.appIconPickerChildren,
|
||||
]);
|
||||
context.push(
|
||||
"/settings",
|
||||
extra: [
|
||||
SettingsUiBackHeader(_l10n.s_customization, () => true),
|
||||
...widget.item.appIconPickerChildren,
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
_sectionLabel(_l10n.s_c_colors_header),
|
||||
_swatchPreview([
|
||||
appStyle.colors.secondary,
|
||||
appStyle.colors.accent,
|
||||
appStyle.colors.background,
|
||||
appStyle.colors.card,
|
||||
]),
|
||||
_stubCustomizeButton(),
|
||||
_coreThemePager(),
|
||||
_customizeButton(route: "/theme-editor"),
|
||||
_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),
|
||||
_swatchPreview([
|
||||
appStyle.colors.grade5,
|
||||
appStyle.colors.grade4,
|
||||
appStyle.colors.grade3,
|
||||
appStyle.colors.grade2,
|
||||
appStyle.colors.grade1,
|
||||
]),
|
||||
_stubCustomizeButton(),
|
||||
_gradeThemePager(),
|
||||
_customizeButton(route: "/grade-colors"),
|
||||
_sectionLabel(_l10n.s_c_title_style_header),
|
||||
_fontPicker(selectedFont),
|
||||
_weightSlider(),
|
||||
@@ -599,3 +645,161 @@ 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),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
1145
firka/lib/ui/phone/screens/theme_editor/theme_editor_screen.dart
Normal file
1145
firka/lib/ui/phone/screens/theme_editor/theme_editor_screen.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -30,7 +30,10 @@ class ThemePagePreview extends StatelessWidget {
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.background,
|
||||
color: appStyle.colors.backgroundLinearGradient == null
|
||||
? appStyle.colors.background
|
||||
: null,
|
||||
gradient: appStyle.colors.backgroundLinearGradient,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
@@ -59,8 +62,13 @@ class ThemePagePreview extends StatelessWidget {
|
||||
child: IgnorePointer(
|
||||
child: DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: ColoredBox(
|
||||
color: appStyle.colors.background,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.backgroundLinearGradient == null
|
||||
? appStyle.colors.background
|
||||
: null,
|
||||
gradient: appStyle.colors.backgroundLinearGradient,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
_PreviewStatusBar(),
|
||||
@@ -169,8 +177,11 @@ class _PreviewBottomNav extends StatelessWidget {
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
colors: [
|
||||
appStyle.colors.background,
|
||||
appStyle.colors.background.withValues(alpha: 0.0),
|
||||
appStyle.colors.backgroundGradient?.last ??
|
||||
appStyle.colors.background,
|
||||
(appStyle.colors.backgroundGradient?.last ??
|
||||
appStyle.colors.background)
|
||||
.withValues(alpha: 0.0),
|
||||
],
|
||||
stops: const [0.0, 1.0],
|
||||
),
|
||||
|
||||
@@ -19,6 +19,7 @@ class ThemePreviewData {
|
||||
required this.messages,
|
||||
required this.tests,
|
||||
required this.grades,
|
||||
required this.chartGrades,
|
||||
required this.omissions,
|
||||
required this.omissionBarSegments,
|
||||
required this.omissionExcusedCount,
|
||||
@@ -38,6 +39,7 @@ 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;
|
||||
@@ -143,6 +145,7 @@ class ThemePreviewData {
|
||||
start: ttBase.add(const Duration(minutes: 55)),
|
||||
end: ttBase.add(const Duration(minutes: 100)),
|
||||
roomName: "123",
|
||||
type: "UresOra",
|
||||
test: testLektion,
|
||||
),
|
||||
_lesson(
|
||||
@@ -207,6 +210,31 @@ 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,
|
||||
@@ -317,6 +345,7 @@ class ThemePreviewData {
|
||||
messages: messages,
|
||||
tests: [homeTest],
|
||||
grades: grades,
|
||||
chartGrades: chartGrades,
|
||||
omissions: omissions,
|
||||
omissionBarSegments: omissionBarSegments,
|
||||
omissionExcusedCount: 2,
|
||||
@@ -346,6 +375,7 @@ class ThemePreviewData {
|
||||
required DateTime end,
|
||||
required String roomName,
|
||||
String? substituteTeacher,
|
||||
String type = "OrarendiOra",
|
||||
TestCacheModel? test,
|
||||
}) {
|
||||
final lesson = LessonCacheModel()
|
||||
@@ -358,7 +388,7 @@ class ThemePreviewData {
|
||||
..name = subject.name
|
||||
..roomName = roomName
|
||||
..state = "Naplozott"
|
||||
..type = "OrarendiOra"
|
||||
..type = type
|
||||
..teacher = "Tanár"
|
||||
..substituteTeacher = substituteTeacher;
|
||||
lesson.subject.value = subject;
|
||||
@@ -378,8 +408,9 @@ class ThemePreviewData {
|
||||
int id,
|
||||
SubjectCacheModel subject,
|
||||
int value,
|
||||
DateTime at,
|
||||
) {
|
||||
DateTime at, {
|
||||
int? weightPercentage = 100,
|
||||
}) {
|
||||
final grade = GradeCacheModel()
|
||||
..cacheKey = id
|
||||
..createdAt = at
|
||||
@@ -389,7 +420,7 @@ class ThemePreviewData {
|
||||
..valueType = "Osztalyzat"
|
||||
..writtenAt = at
|
||||
..numericValue = value
|
||||
..weightPercentage = 100
|
||||
..weightPercentage = weightPercentage
|
||||
..textValue = value.toString()
|
||||
..teacherName = "Tanár";
|
||||
grade.subject.value = subject;
|
||||
|
||||
@@ -167,9 +167,9 @@ class ThemePreviewHomeGrades extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
GradeChart(grades: allGrades),
|
||||
GradeChart(grades: preview.chartGrades, plotRawValues: true),
|
||||
const SizedBox(height: 10),
|
||||
GradeSummaryBar(grades: allGrades, l10n: data.l10n),
|
||||
GradeSummaryBar(grades: preview.chartGrades, l10n: data.l10n),
|
||||
const SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
import "dart:io";
|
||||
import "dart:ui" as ui;
|
||||
import "package:flutter/material.dart";
|
||||
import "package:flutter/rendering.dart";
|
||||
import "package:flutter/services.dart";
|
||||
import "package:go_router/go_router.dart";
|
||||
import "package:image_picker/image_picker.dart";
|
||||
import "package:majesticons_flutter/majesticons_flutter.dart";
|
||||
import "package:mobile_scanner/mobile_scanner.dart";
|
||||
import "package:path_provider/path_provider.dart";
|
||||
import "package:share_plus/share_plus.dart";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/core/snowflake.dart";
|
||||
import "package:firka/l10n/app_localizations.dart";
|
||||
import "package:firka/ui/phone/screens/themes/user_theme.dart";
|
||||
import "package:firka/ui/phone/screens/themes/widgets/theme_qr_card.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/theme_binary_format.dart";
|
||||
|
||||
Future<String?> showThemeNameSheet(
|
||||
BuildContext context,
|
||||
@@ -49,6 +62,783 @@ Future<bool> showThemeDeleteSheet(
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
String buildThemeShareUrl(UserTheme theme) => theme.shareUrl;
|
||||
|
||||
Future<void> showThemeShareSheet(
|
||||
BuildContext context, {
|
||||
required UserTheme theme,
|
||||
required AppInitialization data,
|
||||
}) {
|
||||
return showModalBottomSheet<void>(
|
||||
context: context,
|
||||
elevation: 100,
|
||||
isScrollControlled: true,
|
||||
enableDrag: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
barrierColor: appStyle.colors.a15p,
|
||||
builder: (context) {
|
||||
return _ThemeShareSheet(
|
||||
theme: theme,
|
||||
shareUrl: theme.shareUrl,
|
||||
l10n: data.l10n,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> showThemeImportSheet(
|
||||
BuildContext context, {
|
||||
required AppInitialization data,
|
||||
required Future<void> Function(UserTheme theme) onImport,
|
||||
}) {
|
||||
return showModalBottomSheet<void>(
|
||||
context: context,
|
||||
elevation: 100,
|
||||
isScrollControlled: true,
|
||||
enableDrag: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
barrierColor: appStyle.colors.a15p,
|
||||
builder: (context) {
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.viewInsetsOf(context).bottom,
|
||||
),
|
||||
child: _ThemeImportSheet(
|
||||
l10n: data.l10n,
|
||||
onImport: onImport,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _ThemeShareSheet extends StatefulWidget {
|
||||
final UserTheme theme;
|
||||
final String shareUrl;
|
||||
final AppLocalizations l10n;
|
||||
|
||||
const _ThemeShareSheet({
|
||||
required this.theme,
|
||||
required this.shareUrl,
|
||||
required this.l10n,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_ThemeShareSheet> createState() => _ThemeShareSheetState();
|
||||
}
|
||||
|
||||
class _ThemeShareSheetState extends State<_ThemeShareSheet> {
|
||||
final GlobalKey _cardKey = GlobalKey();
|
||||
bool _copied = false;
|
||||
bool _isSharing = false;
|
||||
|
||||
Future<void> _copy() async {
|
||||
await Clipboard.setData(ClipboardData(text: widget.shareUrl));
|
||||
if (!mounted) return;
|
||||
setState(() => _copied = true);
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
if (mounted) setState(() => _copied = false);
|
||||
}
|
||||
|
||||
Future<void> _share() async {
|
||||
if (_isSharing) return;
|
||||
setState(() => _isSharing = true);
|
||||
|
||||
try {
|
||||
final boundary = _cardKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
|
||||
if (boundary == null) {
|
||||
throw Exception("RenderRepaintBoundary not found");
|
||||
}
|
||||
|
||||
final image = await boundary.toImage(pixelRatio: 3.0);
|
||||
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
if (byteData == null) {
|
||||
throw Exception("Could not encode image to PNG");
|
||||
}
|
||||
|
||||
final pngBytes = byteData.buffer.asUint8List();
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final sanitizedName = widget.theme.name.replaceAll(RegExp(r'[^\w\s-]'), '').trim();
|
||||
final safeName = sanitizedName.isEmpty ? 'firka' : sanitizedName;
|
||||
final file = File('${tempDir.path}/firka_theme_$safeName.png');
|
||||
await file.writeAsBytes(pngBytes);
|
||||
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
files: [XFile(file.path)],
|
||||
subject: widget.theme.name,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
text: widget.shareUrl,
|
||||
subject: widget.theme.name,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isSharing = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _ThemeSheetShell(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
RepaintBoundary(
|
||||
key: _cardKey,
|
||||
child: ThemeQrCard(
|
||||
theme: widget.theme,
|
||||
shareData: widget.shareUrl,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_sheetButton(
|
||||
label: _copied ? widget.l10n.copied : "Kód másolása",
|
||||
color: appStyle.colors.accent,
|
||||
onTap: _copy,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_sheetButton(
|
||||
label: _isSharing ? "Kép generálása..." : "Megosztás",
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
onTap: _isSharing ? () {} : _share,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _ImportMode { camera, image, text }
|
||||
|
||||
class _ThemeImportSheet extends StatefulWidget {
|
||||
final AppLocalizations l10n;
|
||||
final Future<void> Function(UserTheme theme) onImport;
|
||||
|
||||
const _ThemeImportSheet({
|
||||
required this.l10n,
|
||||
required this.onImport,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_ThemeImportSheet> createState() => _ThemeImportSheetState();
|
||||
}
|
||||
|
||||
class _ThemeImportSheetState extends State<_ThemeImportSheet> {
|
||||
_ImportMode _mode = _ImportMode.camera;
|
||||
final _controller = TextEditingController();
|
||||
ThemeBinaryData? _previewData;
|
||||
String? _extractedName;
|
||||
String? _error;
|
||||
bool _isAnalyzingImage = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.addListener(_onTextChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool _processImportString(String raw, {bool silent = false}) {
|
||||
final trimmed = raw.trim();
|
||||
if (trimmed.isEmpty) return false;
|
||||
|
||||
final payload = trimmed.parseThemeSharePayload();
|
||||
final decoded = payload.code.tryDecodeThemeData();
|
||||
|
||||
if (decoded != null) {
|
||||
setState(() {
|
||||
_controller.text = trimmed;
|
||||
_previewData = decoded;
|
||||
_extractedName = payload.name;
|
||||
_error = null;
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
if (!silent) {
|
||||
setState(() {
|
||||
_error = "Érvénytelen témakód";
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _onTextChanged() {
|
||||
final raw = _controller.text.trim();
|
||||
if (raw.isEmpty) {
|
||||
setState(() {
|
||||
_previewData = null;
|
||||
_extractedName = null;
|
||||
_error = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
_processImportString(raw, silent: true);
|
||||
}
|
||||
|
||||
Future<void> _paste() async {
|
||||
final data = await Clipboard.getData(Clipboard.kTextPlain);
|
||||
if (data?.text != null && data!.text!.isNotEmpty) {
|
||||
_controller.text = data.text!;
|
||||
_processImportString(data.text!);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickImageAndScan() async {
|
||||
setState(() {
|
||||
_isAnalyzingImage = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final picker = ImagePicker();
|
||||
final picked = await picker.pickImage(source: ImageSource.gallery);
|
||||
if (picked == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final capture = await MobileScannerPlatform.instance.analyzeImage(picked.path);
|
||||
if (capture != null && capture.barcodes.isNotEmpty) {
|
||||
bool found = false;
|
||||
for (final barcode in capture.barcodes) {
|
||||
final raw = barcode.rawValue;
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
if (_processImportString(raw)) {
|
||||
found = true;
|
||||
HapticFeedback.mediumImpact();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
setState(() {
|
||||
_error = "A képen nem található érvényes téma QR kód.";
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setState(() {
|
||||
_error = "Nem található QR kód a kiválasztott képen.";
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_error = "Hiba a kép beolvasásakor: $e";
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isAnalyzingImage = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _import() async {
|
||||
final preview = _previewData;
|
||||
if (preview == null) return;
|
||||
|
||||
final themeName = _extractedName != null && _extractedName!.isNotEmpty
|
||||
? _extractedName!
|
||||
: widget.l10n.s_c_themes_imported_label;
|
||||
|
||||
final List<Color> swatch;
|
||||
if (preview.isFullTheme) {
|
||||
swatch = [
|
||||
preview.lightSlot(ThemeColorSlot.accent) ?? appStyle.colors.accent,
|
||||
preview.lightSlot(ThemeColorSlot.textPrimary) ?? appStyle.colors.textPrimary,
|
||||
preview.lightSlot(ThemeColorSlot.background) ?? appStyle.colors.background,
|
||||
];
|
||||
} else {
|
||||
swatch = preview.colors.length >= 3
|
||||
? preview.colors.take(3).toList()
|
||||
: (preview.colors.isNotEmpty
|
||||
? preview.colors
|
||||
: [appStyle.colors.accent, appStyle.colors.textPrimary, appStyle.colors.background]);
|
||||
}
|
||||
|
||||
final theme = UserTheme(
|
||||
id: Snowflake.nextId(),
|
||||
name: themeName,
|
||||
origin: ThemeOrigin.downloaded,
|
||||
swatch: swatch,
|
||||
);
|
||||
|
||||
await widget.onImport(theme);
|
||||
if (!mounted) return;
|
||||
context.pop();
|
||||
}
|
||||
|
||||
Widget _modeTab({
|
||||
required String label,
|
||||
required Object icon,
|
||||
required bool selected,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: selected
|
||||
? appStyle.colors.accent.withValues(alpha: 0.15)
|
||||
: appStyle.colors.card,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: selected
|
||||
? appStyle.colors.accent
|
||||
: Colors.transparent,
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Majesticon(
|
||||
icon as Uint8List,
|
||||
color: selected
|
||||
? appStyle.colors.accent
|
||||
: appStyle.colors.textSecondary,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: appStyle.fonts.B_12R.copyWith(
|
||||
fontFamily: 'Figtree',
|
||||
color: selected
|
||||
? appStyle.colors.accent
|
||||
: appStyle.colors.textSecondary,
|
||||
fontWeight: selected ? FontWeight.bold : FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _ThemeSheetShell(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_sheetIcon(Majesticon.arrowDownCircleLine),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
widget.l10n.s_c_themes_import,
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
if (_previewData != null) ...[
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.card,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: appStyle.colors.accent.withValues(alpha: 0.4),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_extractedName != null && _extractedName!.isNotEmpty
|
||||
? _extractedName!
|
||||
: widget.l10n.s_c_themes_imported_label,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontFamily: 'Figtree',
|
||||
color: appStyle.colors.textPrimary,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
for (final color in (_previewData!.isFullTheme
|
||||
? [
|
||||
_previewData!.lightSlot(ThemeColorSlot.accent) ?? appStyle.colors.accent,
|
||||
_previewData!.lightSlot(ThemeColorSlot.textPrimary) ?? appStyle.colors.textPrimary,
|
||||
_previewData!.lightSlot(ThemeColorSlot.background) ?? appStyle.colors.background,
|
||||
]
|
||||
: _previewData!.colors.take(4)))
|
||||
Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: 20,
|
||||
height: 20,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: appStyle.colors.textPrimary.withValues(alpha: 0.25),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_previewData!.isFullTheme
|
||||
? "Teljes téma (32 szín)"
|
||||
: "${_previewData!.colors.length} szín",
|
||||
style: appStyle.fonts.B_12R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_sheetButton(
|
||||
label: widget.l10n.s_c_themes_import,
|
||||
color: appStyle.colors.accent,
|
||||
onTap: _import,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_sheetButton(
|
||||
label: "Másik beolvasása",
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_previewData = null;
|
||||
_extractedName = null;
|
||||
_controller.clear();
|
||||
_error = null;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
] else ...[
|
||||
Row(
|
||||
children: [
|
||||
_modeTab(
|
||||
label: "Kamera",
|
||||
icon: Majesticon.cameraLine,
|
||||
selected: _mode == _ImportMode.camera,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_mode = _ImportMode.camera;
|
||||
_error = null;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_modeTab(
|
||||
label: "Kép",
|
||||
icon: Majesticon.imageLine,
|
||||
selected: _mode == _ImportMode.image,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_mode = _ImportMode.image;
|
||||
_error = null;
|
||||
});
|
||||
_pickImageAndScan();
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_modeTab(
|
||||
label: "Szöveg",
|
||||
icon: Majesticon.textboxLine,
|
||||
selected: _mode == _ImportMode.text,
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_mode = _ImportMode.text;
|
||||
_error = null;
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
if (_mode == _ImportMode.camera) ...[
|
||||
_CameraScannerView(
|
||||
onScanned: (raw) {
|
||||
if (_previewData != null) return;
|
||||
if (_processImportString(raw)) {
|
||||
HapticFeedback.mediumImpact();
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
"Irányítsd a kamerát egy téma QR kódra",
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.B_12R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
] else if (_mode == _ImportMode.image) ...[
|
||||
GestureDetector(
|
||||
onTap: _isAnalyzingImage ? null : _pickImageAndScan,
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
height: 180,
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.card,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: appStyle.colors.accent.withValues(alpha: 0.3),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: _isAnalyzingImage
|
||||
? Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
"Kép elemzése...",
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.accent.withValues(alpha: 0.15),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Majesticon(
|
||||
Majesticon.imageLine,
|
||||
color: appStyle.colors.accent,
|
||||
size: 32,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
"Koppints a kép kiválasztásához",
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"Válassz QR kódot tartalmazó képet a galériából",
|
||||
style: appStyle.fonts.B_12R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
] else if (_mode == _ImportMode.text) ...[
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.card,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _controller,
|
||||
textAlign: TextAlign.start,
|
||||
textInputAction: TextInputAction.done,
|
||||
cursorColor: appStyle.colors.accent,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
hintText: "Témakód vagy link...",
|
||||
hintStyle: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textTertiary,
|
||||
),
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.paste, size: 18),
|
||||
color: appStyle.colors.accent,
|
||||
onPressed: _paste,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_sheetButton(
|
||||
label: "Beillesztés a vágólapról",
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
onTap: _paste,
|
||||
),
|
||||
],
|
||||
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_error!,
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.errorAccent,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 12),
|
||||
_sheetButton(
|
||||
label: widget.l10n.cancel,
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
onTap: () => context.pop(),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CameraScannerView extends StatefulWidget {
|
||||
final ValueChanged<String> onScanned;
|
||||
|
||||
const _CameraScannerView({required this.onScanned});
|
||||
|
||||
@override
|
||||
State<_CameraScannerView> createState() => _CameraScannerViewState();
|
||||
}
|
||||
|
||||
class _CameraScannerViewState extends State<_CameraScannerView> {
|
||||
final MobileScannerController _controller = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: SizedBox(
|
||||
height: 220,
|
||||
width: double.infinity,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: (capture) {
|
||||
for (final barcode in capture.barcodes) {
|
||||
final raw = barcode.rawValue;
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
widget.onScanned(raw);
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
errorBuilder: (context, error) {
|
||||
return Container(
|
||||
color: appStyle.colors.card,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Majesticon(
|
||||
Majesticon.cameraOffLine,
|
||||
color: appStyle.colors.textSecondary,
|
||||
size: 32,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
"Kamera nem elérhető",
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"Használd a Kép vagy Szöveg opciót.",
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.B_12R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Container(
|
||||
width: 150,
|
||||
height: 150,
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: appStyle.colors.accent.withValues(alpha: 0.8),
|
||||
width: 2,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 8,
|
||||
right: 8,
|
||||
child: IconButton(
|
||||
icon: Majesticon(
|
||||
Majesticon.lightningBoltSolid,
|
||||
color: Colors.white,
|
||||
size: 18,
|
||||
),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Colors.black.withValues(alpha: 0.45),
|
||||
),
|
||||
onPressed: () => _controller.toggleTorch(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _showCenteredInputSheet({
|
||||
required BuildContext context,
|
||||
required AppLocalizations l10n,
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import "package:carousel_slider/carousel_slider.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:flutter_bloc/flutter_bloc.dart";
|
||||
import "package:go_router/go_router.dart";
|
||||
import "package:majesticons_flutter/majesticons_flutter.dart";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/core/bloc/theme_cubit.dart";
|
||||
import "package:firka/ui/components/firka_icon_button.dart";
|
||||
import "package:firka/ui/phone/screens/themes/preview/theme_preview_data.dart";
|
||||
import "package:firka/ui/phone/screens/themes/preview/theme_preview_pages.dart";
|
||||
@@ -34,6 +37,16 @@ class _ThemeScreenState extends State<ThemeScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_preview = ThemePreviewData.build();
|
||||
appStyle = buildStyleForBrightness(
|
||||
appStyle.isLight,
|
||||
isCustomTheme: !_theme.isBuiltin,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
initTheme(widget.data);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String get _originLabel {
|
||||
@@ -60,92 +73,118 @@ class _ThemeScreenState extends State<ThemeScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = widget.data.l10n;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 0),
|
||||
child: GestureDetector(
|
||||
onTap: () => context.pop(),
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.chevronLeftLine,
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 1),
|
||||
child: Text(
|
||||
l10n.s_c_theme_header,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
return BlocBuilder<ThemeCubit, ThemeState>(
|
||||
bloc: widget.data.themeCubit,
|
||||
builder: (context, _) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: appStyle.colors.backgroundLinearGradient == null
|
||||
? appStyle.colors.background
|
||||
: null,
|
||||
gradient: appStyle.colors.backgroundLinearGradient,
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ThemeSwatchIcon(swatch: _theme.swatch, size: 48),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ThemeNameLabel(
|
||||
name: _theme.name,
|
||||
editable: _theme.canRename,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
onChanged: (value) {
|
||||
setState(() => _theme.name = value);
|
||||
widget.args.onChanged();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_originLabel,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
Row(
|
||||
children: [
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 0),
|
||||
child: GestureDetector(
|
||||
onTap: () => context.pop(),
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.chevronLeftLine,
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 1),
|
||||
child: Text(
|
||||
l10n.s_c_theme_header,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
spacing: 8,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (_theme.isOwn) ...[
|
||||
FirkaIconButton(
|
||||
onTap: () {},
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.editPen4Line,
|
||||
size: 18,
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
ThemeSwatchIcon(swatch: _theme.swatch, size: 48),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ThemeNameLabel(
|
||||
name: _theme.name,
|
||||
editable: _theme.canRename,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
onChanged: (value) {
|
||||
setState(() => _theme.name = value);
|
||||
widget.args.onChanged();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_originLabel,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaIconButton(
|
||||
onTap: () {},
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.shareLine,
|
||||
size: 18,
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
spacing: 8,
|
||||
children: [
|
||||
if (_theme.isOwn) ...[
|
||||
FirkaIconButton(
|
||||
onTap: () async {
|
||||
await context.push("/theme-editor");
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_theme.swatch =
|
||||
UserTheme.swatchFromAppStyle();
|
||||
appStyle = buildStyleForBrightness(
|
||||
appStyle.isLight,
|
||||
isCustomTheme: true,
|
||||
);
|
||||
});
|
||||
widget.args.onChanged();
|
||||
},
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.editPen4Line,
|
||||
size: 18,
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
FirkaIconButton(
|
||||
onTap: () => showThemeShareSheet(
|
||||
context,
|
||||
theme: _theme,
|
||||
data: widget.data,
|
||||
),
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.shareLine,
|
||||
size: 18,
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (_theme.canDelete)
|
||||
FirkaIconButton(
|
||||
onTap: _delete,
|
||||
@@ -202,6 +241,9 @@ class _ThemeScreenState extends State<ThemeScreen> {
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +143,19 @@ class _ThemesScreenState extends State<ThemesScreen> {
|
||||
await _openTheme(theme);
|
||||
}
|
||||
|
||||
Future<void> _importTheme() async {
|
||||
await showThemeImportSheet(
|
||||
context,
|
||||
data: widget.data,
|
||||
onImport: (theme) async {
|
||||
await _persistTheme(theme);
|
||||
if (!mounted) return;
|
||||
setState(() => _storedThemes.add(theme));
|
||||
await _openTheme(theme);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _renameTheme(UserTheme theme, String name) async {
|
||||
setState(() => theme.name = name);
|
||||
await _persistTheme(theme);
|
||||
@@ -303,7 +316,11 @@ class _ThemesScreenState extends State<ThemesScreen> {
|
||||
),
|
||||
),
|
||||
FirkaIconButton(
|
||||
onTap: () {},
|
||||
onTap: () => showThemeShareSheet(
|
||||
context,
|
||||
theme: _selected,
|
||||
data: widget.data,
|
||||
),
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.shareLine,
|
||||
@@ -312,7 +329,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
|
||||
),
|
||||
),
|
||||
FirkaIconButton(
|
||||
onTap: () {},
|
||||
onTap: _importTheme,
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.arrowDownCircleLine,
|
||||
@@ -335,9 +352,17 @@ class _ThemesScreenState extends State<ThemesScreen> {
|
||||
_actionRow(
|
||||
icon: Majesticon.shareLine,
|
||||
label: l10n.s_c_themes_share_current,
|
||||
onTap: () {},
|
||||
onTap: () => showThemeShareSheet(
|
||||
context,
|
||||
theme: _selected,
|
||||
data: widget.data,
|
||||
),
|
||||
),
|
||||
_sectionLabel(l10n.s_c_themes_own),
|
||||
_themeRow(
|
||||
_builtin,
|
||||
selected: isBuiltinThemeId(_selectedId),
|
||||
),
|
||||
for (final theme in _ownThemes)
|
||||
_themeRow(
|
||||
theme,
|
||||
@@ -357,7 +382,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
|
||||
_actionRow(
|
||||
icon: Majesticon.arrowDownCircleLine,
|
||||
label: l10n.s_c_themes_import,
|
||||
onTap: () {},
|
||||
onTap: _importTheme,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
|
||||
@@ -3,6 +3,7 @@ import "package:flutter/material.dart";
|
||||
import "package:firka_common/data/models/user_theme_model.dart";
|
||||
import "package:firka_common/ui/theme/core_theme.dart";
|
||||
import "package:firka_common/ui/theme/grade_theme.dart";
|
||||
import "package:firka_common/ui/theme/theme_binary_format.dart";
|
||||
|
||||
import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
|
||||
import "package:firka/ui/theme/style.dart";
|
||||
@@ -13,7 +14,7 @@ class UserTheme {
|
||||
final String id;
|
||||
String name;
|
||||
final ThemeOrigin origin;
|
||||
final List<Color> swatch;
|
||||
List<Color> swatch;
|
||||
|
||||
UserTheme({
|
||||
required this.id,
|
||||
@@ -95,3 +96,50 @@ class ThemeScreenArgs {
|
||||
required this.onChanged,
|
||||
});
|
||||
}
|
||||
|
||||
extension UserThemeShareExtension on UserTheme {
|
||||
String get shareCode {
|
||||
if (isBuiltin) {
|
||||
final core = resolveCore(id);
|
||||
return ThemeBinaryFormat.encodeToBase64(
|
||||
ThemeBinaryFormat.decode(ThemeBinaryFormat.encodeCoreTheme(core)).colors,
|
||||
);
|
||||
} else if (swatch.isNotEmpty) {
|
||||
return ThemeBinaryFormat.encodeToBase64(swatch);
|
||||
} else {
|
||||
return ThemeBinaryFormat.encodeToBase64([
|
||||
appStyle.colors.accent,
|
||||
appStyle.colors.textPrimary,
|
||||
appStyle.colors.background,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
String get shareUrl =>
|
||||
"https://firka.app/?d=$shareCode&n=${Uri.encodeComponent(name)}";
|
||||
}
|
||||
|
||||
extension ThemeShareCodeStringExtension on String {
|
||||
({String code, String? name}) parseThemeSharePayload() {
|
||||
final trimmed = trim();
|
||||
if (trimmed.startsWith('firka://') || trimmed.startsWith('http')) {
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri != null) {
|
||||
return (
|
||||
code: uri.queryParameters['d'] ?? trimmed,
|
||||
name: uri.queryParameters['n'],
|
||||
);
|
||||
}
|
||||
}
|
||||
return (code: trimmed, name: null);
|
||||
}
|
||||
|
||||
ThemeBinaryData? tryDecodeThemeData() {
|
||||
try {
|
||||
final payload = parseThemeSharePayload();
|
||||
return ThemeBinaryFormat.decodeFromBase64(payload.code);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
156
firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart
Normal file
156
firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart
Normal file
@@ -0,0 +1,156 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class ThemeQrCard extends StatelessWidget {
|
||||
final UserTheme theme;
|
||||
final String shareData;
|
||||
final double qrSize;
|
||||
|
||||
const ThemeQrCard({
|
||||
super.key,
|
||||
required this.theme,
|
||||
required this.shareData,
|
||||
this.qrSize = 180,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Theme colors extracted from swatch or current active theme
|
||||
final accentColor = theme.swatch.isNotEmpty
|
||||
? theme.swatch[0]
|
||||
: appStyle.colors.accent;
|
||||
final textColor = theme.swatch.length > 1
|
||||
? theme.swatch[1]
|
||||
: appStyle.colors.textPrimary;
|
||||
final cardBgColor = theme.swatch.length > 2
|
||||
? theme.swatch[2]
|
||||
: appStyle.colors.card;
|
||||
|
||||
// Determine contrast: if cardBgColor is dark, use light for QR dots; if light, use dark
|
||||
final brightness = ThemeData.estimateBrightnessForColor(cardBgColor);
|
||||
final qrDotColor = brightness == Brightness.dark
|
||||
? (textColor.computeLuminance() > 0.4 ? textColor : Colors.white)
|
||||
: (textColor.computeLuminance() < 0.6 ? textColor : Colors.black87);
|
||||
|
||||
return Container(
|
||||
width: 270,
|
||||
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: cardBgColor,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(
|
||||
color: accentColor.withValues(alpha: 0.3),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.2),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// QR Code with Dave Mascot in the Center
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: cardBgColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: accentColor.withValues(alpha: 0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: SizedBox(
|
||||
width: qrSize,
|
||||
height: qrSize,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
QrImageView(
|
||||
data: shareData,
|
||||
version: QrVersions.auto,
|
||||
errorCorrectionLevel: QrErrorCorrectLevel.H,
|
||||
size: qrSize,
|
||||
padding: EdgeInsets.zero,
|
||||
eyeStyle: QrEyeStyle(
|
||||
eyeShape: QrEyeShape.circle,
|
||||
color: accentColor,
|
||||
),
|
||||
dataModuleStyle: QrDataModuleStyle(
|
||||
dataModuleShape: QrDataModuleShape.circle,
|
||||
color: qrDotColor,
|
||||
),
|
||||
backgroundColor: Colors.transparent,
|
||||
),
|
||||
// Dave Mascot Badge in center of QR
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: cardBgColor,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: accentColor.withValues(alpha: 0.5),
|
||||
width: 2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.25),
|
||||
blurRadius: 6,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Center(
|
||||
child: DaveMascot(
|
||||
width: 28,
|
||||
height: 28,
|
||||
color: accentColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Theme Name Label
|
||||
Text(
|
||||
theme.name,
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontFamily: 'Figtree',
|
||||
color: textColor,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
|
||||
// https://firka.app below theme name
|
||||
Text(
|
||||
"https://firka.app",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontFamily: 'Figtree',
|
||||
color: accentColor,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ class BottomTimeTableNavIconWidget extends StatelessWidget {
|
||||
style: appStyle.fonts.H_16px.apply(
|
||||
color: active
|
||||
? appStyle.colors.textPrimary
|
||||
: appStyle.colors.textTeritary,
|
||||
: appStyle.colors.textTertiary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
@@ -62,7 +62,7 @@ class BottomTimeTableNavIconWidget extends StatelessWidget {
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: active
|
||||
? appStyle.colors.textSecondary
|
||||
: appStyle.colors.textTeritary,
|
||||
: appStyle.colors.textTertiary,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,9 +6,9 @@ import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
|
||||
/// Lightweight in-app browser used outside the login flow (e.g. privacy policy).
|
||||
///
|
||||
@@ -119,8 +119,7 @@ class _DomainBrowserWebviewWidgetState
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 2),
|
||||
child: SvgPicture.asset(
|
||||
"assets/icons/dave.svg",
|
||||
child: const DaveMascot.icon(
|
||||
width: 24,
|
||||
height: 24,
|
||||
),
|
||||
|
||||
@@ -13,10 +13,12 @@ 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));
|
||||
|
||||
@@ -49,19 +51,21 @@ class _GradeChartState extends State<GradeChart> {
|
||||
|
||||
void _computeSpots() {
|
||||
spots = [];
|
||||
for (var i = 0; i < widget.grades.length; i++) {
|
||||
final grade = widget.grades[i];
|
||||
if (!grade.shouldIncludeInAverage()) {
|
||||
continue;
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
final partialAvg = widget.grades
|
||||
.take(i + 1)
|
||||
.getSubjectAverage(halfYearFallback: widget.halfYearFallback);
|
||||
|
||||
spots.add(
|
||||
DateSpot(spots.length.toDouble(), partialAvg!, grade.writtenAt),
|
||||
);
|
||||
}
|
||||
|
||||
if (spots.isEmpty) {
|
||||
|
||||
@@ -5,9 +5,9 @@ import 'package:firka/app/app_state.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
|
||||
import 'package:firka/api/login_finish.dart';
|
||||
import 'package:firka/api/token_grant.dart';
|
||||
@@ -163,8 +163,7 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 2),
|
||||
child: SvgPicture.asset(
|
||||
"assets/icons/dave.svg",
|
||||
child: const DaveMascot.icon(
|
||||
width: 24,
|
||||
height: 24,
|
||||
),
|
||||
|
||||
@@ -62,6 +62,10 @@ class OmissionBar extends StatelessWidget {
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (segmentColors.isEmpty) {
|
||||
segmentColors.add(stateColor(null));
|
||||
}
|
||||
|
||||
final bar = ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Row(
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
|
||||
import 'lesson.dart';
|
||||
|
||||
@@ -76,8 +76,7 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/images/logos/dave.svg",
|
||||
const DaveMascot(
|
||||
width: 48,
|
||||
height: 48,
|
||||
),
|
||||
|
||||
130
firka/lib/ui/shared/dave_mascot.dart
Normal file
130
firka/lib/ui/shared/dave_mascot.dart
Normal file
@@ -0,0 +1,130 @@
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/core/image_preloader.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
|
||||
/// Generates a [ColorFilter] that recolors Dave mascot's green accents
|
||||
/// (#A7DC22) to [targetColor] while preserving all black and white paths/pixels.
|
||||
ColorFilter? getDaveColorFilter([Color? targetColor]) {
|
||||
final color = targetColor ?? appStyle.colors.accent;
|
||||
|
||||
// If the target color is already the default Firka green (#A7DC22), no filter needed.
|
||||
if ((color.toARGB32() & 0x00FFFFFF) == 0x00A7DC22) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Source green color: #A7DC22 -> R=167, G=220, B=34
|
||||
const double gSrc = 220.0 / 255.0;
|
||||
const double bSrc = 34.0 / 255.0;
|
||||
const double denom = gSrc - bSrc; // 186.0 / 255.0
|
||||
|
||||
final double rTgt = color.r;
|
||||
final double gTgt = color.g;
|
||||
final double bTgt = color.b;
|
||||
|
||||
final double m01 = (rTgt - bSrc) / denom;
|
||||
final double m02 = 1.0 - m01;
|
||||
|
||||
final double m11 = (gTgt - bSrc) / denom;
|
||||
final double m12 = 1.0 - m11;
|
||||
|
||||
final double m21 = (bTgt - bSrc) / denom;
|
||||
final double m22 = 1.0 - m21;
|
||||
|
||||
return ColorFilter.matrix(<double>[
|
||||
0.0, m01, m02, 0.0, 0.0,
|
||||
0.0, m11, m12, 0.0, 0.0,
|
||||
0.0, m21, m22, 0.0, 0.0,
|
||||
0.0, 0.0, 0.0, 1.0, 0.0,
|
||||
]);
|
||||
}
|
||||
|
||||
class DaveMascot extends StatelessWidget {
|
||||
final double? width;
|
||||
final double? height;
|
||||
final Color? color;
|
||||
final String asset;
|
||||
final bool isError;
|
||||
final BoxFit fit;
|
||||
|
||||
const DaveMascot({
|
||||
super.key,
|
||||
this.width,
|
||||
this.height,
|
||||
this.color,
|
||||
this.asset = 'assets/images/logos/dave.svg',
|
||||
this.isError = false,
|
||||
this.fit = BoxFit.contain,
|
||||
});
|
||||
|
||||
const DaveMascot.icon({
|
||||
super.key,
|
||||
this.width = 24,
|
||||
this.height = 24,
|
||||
this.color,
|
||||
this.asset = 'assets/icons/dave.svg',
|
||||
this.isError = false,
|
||||
this.fit = BoxFit.contain,
|
||||
});
|
||||
|
||||
const DaveMascot.error({
|
||||
super.key,
|
||||
this.width = 50,
|
||||
this.height = 50,
|
||||
this.color,
|
||||
this.asset = 'assets/images/logos/dave_error.png',
|
||||
this.isError = true,
|
||||
this.fit = BoxFit.cover,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final filter = getDaveColorFilter(color);
|
||||
|
||||
if (isError) {
|
||||
Widget image = Image(
|
||||
image: PreloadedImageProvider(
|
||||
FirkaBundle(),
|
||||
'assets/images/logos/dave_error.png',
|
||||
),
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
);
|
||||
|
||||
if (filter != null) {
|
||||
image = ColorFiltered(
|
||||
colorFilter: filter,
|
||||
child: image,
|
||||
);
|
||||
}
|
||||
|
||||
return Container(
|
||||
width: width,
|
||||
height: height,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: const ShapeDecoration(
|
||||
shape: ContinuousRectangleBorder(),
|
||||
),
|
||||
child: image,
|
||||
);
|
||||
}
|
||||
|
||||
Widget svg = SvgPicture.asset(
|
||||
asset,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
);
|
||||
|
||||
if (filter != null) {
|
||||
svg = ColorFiltered(
|
||||
colorFilter: filter,
|
||||
child: svg,
|
||||
);
|
||||
}
|
||||
|
||||
return svg;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ name: firka
|
||||
description: "Firka, Alternatív e-Kréta kliens."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.1.2+2001
|
||||
version: 1.2.0+2001
|
||||
|
||||
environment:
|
||||
sdk: ^3.11.0
|
||||
@@ -20,6 +20,7 @@ dependencies:
|
||||
firebase_core: ^4.1.1
|
||||
firebase_messaging: ^16.0.2
|
||||
flutter_local_notifications: ^18.0.1
|
||||
android_alarm_manager_plus: ^5.1.1
|
||||
dio: ^5.8.0+1
|
||||
isar_community: 3.3.0
|
||||
isar_community_flutter_libs: 3.3.0
|
||||
@@ -61,6 +62,9 @@ dependencies:
|
||||
go_router: ^17.1.0
|
||||
flutter_bloc: ^9.0.0
|
||||
vibration: ^3.1.8
|
||||
dynamic_color: ^2.1.0
|
||||
qr_flutter: ^4.1.0
|
||||
mobile_scanner: ^7.4.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -6,10 +6,12 @@ import 'package:path/path.dart' as p;
|
||||
import 'package:yaml/yaml.dart' as yaml;
|
||||
|
||||
const _lockFileName = 'codegen-lock.yaml';
|
||||
const _cacheFileName = '.codegen-cache.yaml';
|
||||
|
||||
void main() async {
|
||||
final root = _projectRoot();
|
||||
print(root);
|
||||
stdout.writeln(root);
|
||||
_cleanIos(root);
|
||||
var ran = false;
|
||||
|
||||
if (_iconsOutOfDate(root)) {
|
||||
@@ -31,6 +33,7 @@ void main() async {
|
||||
runInShell: true,
|
||||
);
|
||||
if (iconResult.exitCode == 0) {
|
||||
_cleanIos(root);
|
||||
_updateLockWithHashes(root, 'icons', _computeHashes(root, inputs));
|
||||
ran = true;
|
||||
}
|
||||
@@ -53,19 +56,23 @@ void main() async {
|
||||
'--template-arb-file',
|
||||
'app_hu.arb',
|
||||
], root);
|
||||
_updateLockWithHashes(root, 'l10n', _computeHashes(root, inputs));
|
||||
_updateCacheWithHashes(root, 'l10n', _computeHashes(root, inputs));
|
||||
ran = true;
|
||||
}
|
||||
|
||||
var common = p.join(p.dirname(root), "firka_common");
|
||||
if (_isarOutOfDate(common) || _isarGeneratedFilesMissing(common)) {
|
||||
final common = p.join(p.dirname(root), 'firka_common');
|
||||
if (_isarOutOfDate(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'], common);
|
||||
_updateLockWithHashes(common, 'isar', hashes);
|
||||
await _run(
|
||||
'dart',
|
||||
['run', 'build_runner', 'build', '--delete-conflicting-outputs'],
|
||||
common,
|
||||
);
|
||||
_updateCacheWithHashes(common, 'isar', hashes);
|
||||
ran = true;
|
||||
}
|
||||
|
||||
@@ -76,10 +83,13 @@ void main() async {
|
||||
'Splash out of date, running flutter_native_splash:create...',
|
||||
);
|
||||
await _run('dart', ['run', 'flutter_native_splash:create'], root);
|
||||
_cleanIos(root);
|
||||
_updateLockWithHashes(root, 'splash', _computeHashes(root, inputs));
|
||||
ran = true;
|
||||
}
|
||||
|
||||
_cleanIos(root);
|
||||
|
||||
if (!ran) {
|
||||
stdout.writeln('All generated files are up to date.');
|
||||
}
|
||||
@@ -91,9 +101,10 @@ String _projectRoot() {
|
||||
}
|
||||
|
||||
String _lockPath(String root) => p.join(root, _lockFileName);
|
||||
String _cachePath(String root) => p.join(root, _cacheFileName);
|
||||
|
||||
Map<String, Map<String, String>>? _readLock(String root) {
|
||||
final file = File(_lockPath(root));
|
||||
Map<String, Map<String, String>>? _readYamlFile(String filePath) {
|
||||
final file = File(filePath);
|
||||
if (!file.existsSync()) return null;
|
||||
try {
|
||||
final content = file.readAsStringSync();
|
||||
@@ -116,9 +127,9 @@ Map<String, Map<String, String>>? _readLock(String root) {
|
||||
}
|
||||
}
|
||||
|
||||
void _writeLock(String root, Map<String, Map<String, String>> lock) {
|
||||
void _writeYamlFile(String filePath, Map<String, Map<String, String>> data) {
|
||||
final buf = StringBuffer();
|
||||
for (final stepEntry in lock.entries) {
|
||||
for (final stepEntry in data.entries) {
|
||||
buf.writeln('${stepEntry.key}:');
|
||||
for (final fileEntry in stepEntry.value.entries) {
|
||||
buf.writeln(
|
||||
@@ -126,9 +137,15 @@ void _writeLock(String root, Map<String, Map<String, String>> lock) {
|
||||
);
|
||||
}
|
||||
}
|
||||
File(_lockPath(root)).writeAsStringSync(buf.toString());
|
||||
File(filePath).writeAsStringSync(buf.toString());
|
||||
}
|
||||
|
||||
Map<String, Map<String, String>>? _readLock(String root) =>
|
||||
_readYamlFile(_lockPath(root));
|
||||
|
||||
Map<String, Map<String, String>>? _readCache(String root) =>
|
||||
_readYamlFile(_cachePath(root));
|
||||
|
||||
String _escapeYaml(String s) =>
|
||||
s.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
|
||||
|
||||
@@ -148,10 +165,10 @@ bool _hashesMatch(
|
||||
String root,
|
||||
String stepName,
|
||||
List<File> inputs,
|
||||
Map<String, Map<String, String>>? lock,
|
||||
Map<String, Map<String, String>>? lockOrCache,
|
||||
) {
|
||||
if (lock == null || !lock.containsKey(stepName)) return false;
|
||||
final stepHashes = lock[stepName]!;
|
||||
if (lockOrCache == null || !lockOrCache.containsKey(stepName)) return false;
|
||||
final stepHashes = lockOrCache[stepName]!;
|
||||
for (final f in inputs) {
|
||||
final rel = _relativePath(root, f);
|
||||
final stored = stepHashes[rel];
|
||||
@@ -172,22 +189,24 @@ void _updateLockWithHashes(
|
||||
) {
|
||||
final lock = _readLock(root) ?? <String, Map<String, String>>{};
|
||||
lock[stepName] = Map.from(hashes);
|
||||
_writeLock(root, lock);
|
||||
_writeYamlFile(_lockPath(root), lock);
|
||||
}
|
||||
|
||||
DateTime? _modified(File file) {
|
||||
if (!file.existsSync()) return null;
|
||||
return file.lastModifiedSync();
|
||||
void _updateCacheWithHashes(
|
||||
String root,
|
||||
String stepName,
|
||||
Map<String, String> hashes,
|
||||
) {
|
||||
final cache = _readCache(root) ?? <String, Map<String, String>>{};
|
||||
cache[stepName] = Map.from(hashes);
|
||||
_writeYamlFile(_cachePath(root), cache);
|
||||
}
|
||||
|
||||
bool _anyNewerThan(Iterable<File> inputs, File output) {
|
||||
final outTime = _modified(output);
|
||||
if (outTime == null) return true;
|
||||
for (final f in inputs) {
|
||||
final t = _modified(f);
|
||||
if (t != null && t.isAfter(outTime)) return true;
|
||||
void _cleanIos(String root) {
|
||||
final iosDir = Directory(p.join(root, 'ios'));
|
||||
if (iosDir.existsSync()) {
|
||||
iosDir.deleteSync(recursive: true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
List<File> _iconsInputs(String root) {
|
||||
@@ -217,7 +236,7 @@ bool _iconsOutOfDate(String root) {
|
||||
'android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml',
|
||||
),
|
||||
);
|
||||
if (!_anyNewerThan(inputs, output)) return false;
|
||||
if (!output.existsSync()) return true;
|
||||
return !_hashesMatch(root, 'icons', inputs, _readLock(root));
|
||||
}
|
||||
|
||||
@@ -233,11 +252,28 @@ List<File> _l10nInputs(String root) {
|
||||
return [l10nYml, ...arbs].where((f) => f.existsSync()).cast<File>().toList();
|
||||
}
|
||||
|
||||
bool _l10nGeneratedFilesMissing(String root) {
|
||||
final l10nDir = p.join(root, 'lib/l10n');
|
||||
final mainOutput = File(p.join(l10nDir, 'app_localizations.dart'));
|
||||
if (!mainOutput.existsSync()) return true;
|
||||
final dir = Directory(l10nDir);
|
||||
if (!dir.existsSync()) return true;
|
||||
for (final file in dir.listSync().whereType<File>()) {
|
||||
if (file.path.endsWith('.arb')) {
|
||||
final base = p.basenameWithoutExtension(file.path);
|
||||
final genFile = File(
|
||||
p.join(l10nDir, '${base.replaceFirst("app_", "app_localizations_")}.dart'),
|
||||
);
|
||||
if (!genFile.existsSync()) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _l10nOutOfDate(String root) {
|
||||
final inputs = _l10nInputs(root);
|
||||
final output = File(p.join(root, 'lib/l10n/app_localizations.dart'));
|
||||
if (!_anyNewerThan(inputs, output)) return false;
|
||||
return !_hashesMatch(root, 'l10n', inputs, _readLock(root));
|
||||
if (_l10nGeneratedFilesMissing(root)) return true;
|
||||
return !_hashesMatch(root, 'l10n', inputs, _readCache(root));
|
||||
}
|
||||
|
||||
List<File> _isarInputs(String root) {
|
||||
@@ -253,20 +289,6 @@ List<File> _isarInputs(String root) {
|
||||
return list;
|
||||
}
|
||||
|
||||
bool _isarOutOfDate(String root) {
|
||||
final inputs = _isarInputs(root);
|
||||
if (inputs.isEmpty) return false;
|
||||
final modelsDir = p.join(root, 'lib/data/models');
|
||||
for (final dartFile in inputs) {
|
||||
final baseName = p.basenameWithoutExtension(dartFile.path);
|
||||
final gFile = File(p.join(modelsDir, '$baseName.g.dart'));
|
||||
if (_anyNewerThan([dartFile], gFile)) {
|
||||
return !_hashesMatch(root, 'isar', inputs, _readLock(root));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _isarGeneratedFilesMissing(String root) {
|
||||
final inputs = _isarInputs(root);
|
||||
if (inputs.isEmpty) return false;
|
||||
@@ -279,6 +301,13 @@ bool _isarGeneratedFilesMissing(String root) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _isarOutOfDate(String root) {
|
||||
final inputs = _isarInputs(root);
|
||||
if (inputs.isEmpty) return false;
|
||||
if (_isarGeneratedFilesMissing(root)) return true;
|
||||
return !_hashesMatch(root, 'isar', inputs, _readCache(root));
|
||||
}
|
||||
|
||||
List<File> _splashInputs(String root) {
|
||||
final config = File(p.join(root, 'flutter_native_splash.yaml'));
|
||||
final splashImage = File(p.join(root, 'assets/images/logos/splash.png'));
|
||||
@@ -294,7 +323,11 @@ bool _splashOutOfDate(String root) {
|
||||
final output = File(
|
||||
p.join(root, 'android/app/src/main/res/drawable/launch_background.xml'),
|
||||
);
|
||||
if (!_anyNewerThan(inputs, output)) return false;
|
||||
if (!output.existsSync()) return true;
|
||||
final splash12 = File(
|
||||
p.join(root, 'assets/images/logos/splash_android12.png'),
|
||||
);
|
||||
if (!splash12.existsSync()) return true;
|
||||
return !_hashesMatch(root, 'splash', inputs, _readLock(root));
|
||||
}
|
||||
|
||||
|
||||
134
firka/test/data/widget_test.dart
Normal file
134
firka/test/data/widget_test.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('WidgetCacheHelper serialization', () {
|
||||
test('serializes LessonCacheModel fields without custom DTO', () {
|
||||
final start = DateTime(2026, 9, 8, 8, 0);
|
||||
final end = DateTime(2026, 9, 8, 8, 45);
|
||||
|
||||
final lesson = LessonCacheModel()
|
||||
..name = 'Matematika'
|
||||
..start = start
|
||||
..end = end
|
||||
..dailyNth = 1
|
||||
..yearlyNth = 12
|
||||
..roomName = '101'
|
||||
..teacher = 'Kovács Péter'
|
||||
..substituteTeacher = 'Nagy Anna'
|
||||
..topic = 'Trigonometria'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final json = WidgetCacheHelper.lessonToJson(lesson);
|
||||
|
||||
// Check standard LessonCacheModel properties
|
||||
expect(json['name'], equals('Matematika'));
|
||||
expect(json['start'], equals(start.toIso8601String()));
|
||||
expect(json['end'], equals(end.toIso8601String()));
|
||||
expect(json['dailyNth'], equals(1));
|
||||
expect(json['yearlyNth'], equals(12));
|
||||
expect(json['roomName'], equals('101'));
|
||||
expect(json['teacher'], equals('Kovács Péter'));
|
||||
expect(json['substituteTeacher'], equals('Nagy Anna'));
|
||||
expect(json['topic'], equals('Trigonometria'));
|
||||
expect(json['state'], equals('Megtartott óra'));
|
||||
expect(json['type'], equals('Tanóra'));
|
||||
|
||||
// Check backward compatibility aliases
|
||||
expect(json['Nev'], equals('Matematika'));
|
||||
expect(json['KezdetIdopont'], equals(start.toIso8601String()));
|
||||
expect(json['VegIdopont'], equals(end.toIso8601String()));
|
||||
expect(json['Oraszam'], equals(1));
|
||||
expect(json['TeremNeve'], equals('101'));
|
||||
expect(json['HelyettesTanarNeve'], equals('Nagy Anna'));
|
||||
});
|
||||
|
||||
test('toJson generates complete widget state with colors and timetable', () {
|
||||
final start = DateTime(2026, 9, 8, 8, 55);
|
||||
final end = DateTime(2026, 9, 8, 9, 40);
|
||||
|
||||
final lesson = LessonCacheModel()
|
||||
..name = 'Történelem'
|
||||
..start = start
|
||||
..end = end
|
||||
..dailyNth = 2
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final result = WidgetCacheHelper.toJson(null, [lesson]);
|
||||
|
||||
expect(result.containsKey('colors'), isTrue);
|
||||
expect(result.containsKey('timetable'), isTrue);
|
||||
expect(result['timetable'], hasLength(1));
|
||||
|
||||
final first = (result['timetable'] as List).first as Map<String, dynamic>;
|
||||
expect(first['name'], equals('Történelem'));
|
||||
expect(first['dailyNth'], equals(2));
|
||||
});
|
||||
|
||||
test('toJson preserves existing colors in headless mode when style is null', () {
|
||||
final customColors = <String, dynamic>{
|
||||
'background': 0xFF123456,
|
||||
'card': 0xFF654321,
|
||||
};
|
||||
|
||||
final result = WidgetCacheHelper.toJson(
|
||||
null,
|
||||
[],
|
||||
existingColors: customColors,
|
||||
);
|
||||
|
||||
expect(result['colors']['background'], equals(0xFF123456));
|
||||
expect(result['colors']['card'], equals(0xFF654321));
|
||||
expect(result['timetable'], isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('Timetable change detection for FCM wakeups', () {
|
||||
test('detects change when timetable content differs', () {
|
||||
final tempDir = Directory.systemTemp.createTempSync('widget_test_');
|
||||
final widgetFile = File('${tempDir.path}/widget_state.json');
|
||||
|
||||
final start1 = DateTime(2026, 9, 8, 8, 0);
|
||||
final end1 = DateTime(2026, 9, 8, 8, 45);
|
||||
|
||||
final oldLesson = LessonCacheModel()
|
||||
..name = 'Angol'
|
||||
..start = start1
|
||||
..end = end1
|
||||
..dailyNth = 1
|
||||
..roomName = '102'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final initialData = WidgetCacheHelper.toJson(null, [oldLesson]);
|
||||
widgetFile.writeAsStringSync(jsonEncode(initialData));
|
||||
|
||||
// Same lesson: no change
|
||||
final readJson = jsonDecode(widgetFile.readAsStringSync());
|
||||
final tt = readJson['timetable'] as List;
|
||||
expect(tt[0]['name'], equals(oldLesson.name));
|
||||
expect(tt[0]['roomName'], equals(oldLesson.roomName));
|
||||
|
||||
// Substitute teacher assigned: changed!
|
||||
final updatedLesson = LessonCacheModel()
|
||||
..name = 'Angol'
|
||||
..start = start1
|
||||
..end = end1
|
||||
..dailyNth = 1
|
||||
..roomName = '102'
|
||||
..substituteTeacher = 'Kiss Éva'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
expect(tt[0]['substituteTeacher'], isNot(equals(updatedLesson.substituteTeacher)));
|
||||
|
||||
tempDir.deleteSync(recursive: true);
|
||||
});
|
||||
});
|
||||
}
|
||||
348
firka/test/e2e/collection_cache_reconciliation_test.dart
Normal file
348
firka/test/e2e/collection_cache_reconciliation_test.dart
Normal file
@@ -0,0 +1,348 @@
|
||||
// ignore_for_file: depend_on_referenced_packages
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
Future<bool?> initialize(
|
||||
InitializationSettings initializationSettings, {
|
||||
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
|
||||
void Function(NotificationResponse)?
|
||||
onDidReceiveBackgroundNotificationResponse,
|
||||
}) async => true;
|
||||
|
||||
@override
|
||||
Future<List<ActiveNotification>> getActiveNotifications() async => [];
|
||||
}
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(
|
||||
HttpClient httpClient,
|
||||
) async {
|
||||
final loginReq = await httpClient.getUrl(
|
||||
Uri.parse('$_mockServerUrl/Account/Login'),
|
||||
);
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception(
|
||||
'Failed to extract code from mock server login: $loginBody',
|
||||
);
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/connect/token'),
|
||||
);
|
||||
tokenReq.headers.contentType = ContentType(
|
||||
'application',
|
||||
'x-www-form-urlencoded',
|
||||
);
|
||||
tokenReq.write(
|
||||
'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}',
|
||||
);
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception(
|
||||
'Token request failed (${tokenResp.statusCode}): $tokenBody',
|
||||
);
|
||||
}
|
||||
return TokenGrantResponse.fromJson(
|
||||
jsonDecode(tokenBody) as Map<String, dynamic>,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetMockServer(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/admin/api/reset'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
await resp.drain();
|
||||
}
|
||||
|
||||
Future<void> _putCollection(
|
||||
HttpClient httpClient,
|
||||
String endpoint,
|
||||
List<Map<String, dynamic>> items,
|
||||
) async {
|
||||
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl$endpoint'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(items));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to PUT $endpoint (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
const _subject = {
|
||||
'Uid': '1,MATEK',
|
||||
'Nev': 'Matematika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező', 'Leiras': 'Kötelező tantárgy'},
|
||||
'SortIndex': 1,
|
||||
};
|
||||
|
||||
Map<String, dynamic> _grade(String uid) => {
|
||||
'Uid': uid,
|
||||
'RogzitesDatuma': '2026-09-08T00:00:00',
|
||||
'KeszitesDatuma': '2026-09-08T00:00:00',
|
||||
'Tantargy': _subject,
|
||||
'Tema': 'Teszt téma',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli felelet'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat', 'Leiras': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Teszt Tanár',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
'SortIndex': 1,
|
||||
};
|
||||
|
||||
Map<String, dynamic> _homework(String uid) => {
|
||||
'Uid': uid,
|
||||
'Tantargy': _subject,
|
||||
'TantargyNeve': 'Matematika',
|
||||
'RogzitoTanarNeve': 'Teszt Tanár',
|
||||
'Szoveg': 'Teszt házi feladat',
|
||||
'FeladasDatuma': '2026-09-09T00:00:00',
|
||||
'HataridoDatuma': '2026-09-16T00:00:00',
|
||||
'RogzitesIdopontja': '2026-09-09T00:00:00',
|
||||
'IsTanarRogzitette': true,
|
||||
'IsMegoldva': false,
|
||||
'IsBeadhato': false,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
'IsCsatolasEngedelyezes': false,
|
||||
};
|
||||
|
||||
Map<String, dynamic> _test(String uid) => {
|
||||
'Uid': uid,
|
||||
'Datum': '2026-09-14T00:00:00',
|
||||
'BejelentesDatuma': '2026-09-09T00:00:00',
|
||||
'RogzitoTanarNeve': 'Teszt Tanár',
|
||||
'OrarendiOraOraszama': 2,
|
||||
'Tantargy': _subject,
|
||||
'TantargyNeve': 'Matematika',
|
||||
'Temaja': 'Teszt dolgozat téma',
|
||||
'Modja': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli dolgozat'},
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
};
|
||||
|
||||
Map<String, dynamic> _omission(String uid) => {
|
||||
'Uid': uid,
|
||||
'Tantargy': _subject,
|
||||
'Ora': {
|
||||
'KezdoDatum': '2026-09-07T00:00:00',
|
||||
'VegDatum': '2026-09-07T00:45:00',
|
||||
'Oraszam': 1,
|
||||
},
|
||||
'Datum': '2026-09-07T00:00:00',
|
||||
'RogzitoTanarNeve': 'Teszt Tanár',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Hiányzás', 'Leiras': 'Hiányzás'},
|
||||
'Mod': {'Uid': '', 'Nev': '', 'Leiras': ''},
|
||||
'KeszitesDatuma': '2026-09-07T00:00:00',
|
||||
'IgazolasAllapota': 'Igazolt',
|
||||
'IgazolasTipusa': {'Uid': '', 'Nev': '', 'Leiras': ''},
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
};
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
|
||||
logger = Logger('CollectionCacheReconciliationTest');
|
||||
|
||||
group('Collection cache reconciliation against mock Kreta server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => Directory.systemTemp.path,
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('dev.fluttercommunity.plus/package_info'),
|
||||
(MethodCall methodCall) async => {
|
||||
'appName': 'firka',
|
||||
'packageName': 'app.firka.naplo',
|
||||
'version': '1.0.0',
|
||||
'buildNumber': '1',
|
||||
},
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('firka.app/main'),
|
||||
(MethodCall methodCall) async => 'SM-A705FN;11;30',
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
Future<void> initAndSync() async {
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
await initData.client!.init();
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
}
|
||||
|
||||
testWidgets('stale grade rows are removed after a server-side correction', (
|
||||
tester,
|
||||
) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putCollection(httpClient, '/admin/api/grades', [
|
||||
_grade('g-1'),
|
||||
_grade('g-2'),
|
||||
]);
|
||||
|
||||
await initAndSync();
|
||||
expect(isarInit.gradeCacheModels.where().findAllSync().length, 2);
|
||||
|
||||
// teacher deletes an erroneously entered grade server-side
|
||||
await _putCollection(httpClient, '/admin/api/grades', [_grade('g-1')]);
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
|
||||
expect(
|
||||
isarInit.gradeCacheModels.where().findAllSync().length,
|
||||
1,
|
||||
reason: 'deleted grade should no longer be cached locally',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'stale homework rows are removed after a server-side deletion',
|
||||
(tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putCollection(httpClient, '/admin/api/homework', [
|
||||
_homework('h-1'),
|
||||
_homework('h-2'),
|
||||
]);
|
||||
|
||||
await initAndSync();
|
||||
expect(isarInit.homeworkCacheModels.where().findAllSync().length, 2);
|
||||
|
||||
await _putCollection(httpClient, '/admin/api/homework', [
|
||||
_homework('h-1'),
|
||||
]);
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
|
||||
expect(
|
||||
isarInit.homeworkCacheModels.where().findAllSync().length,
|
||||
1,
|
||||
reason: 'deleted homework should no longer be cached locally',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'stale test rows are removed after a server-side cancellation',
|
||||
(tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putCollection(httpClient, '/admin/api/tests', [
|
||||
_test('t-1'),
|
||||
_test('t-2'),
|
||||
]);
|
||||
|
||||
await initAndSync();
|
||||
expect(isarInit.testCacheModels.where().findAllSync().length, 2);
|
||||
|
||||
await _putCollection(httpClient, '/admin/api/tests', [_test('t-1')]);
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
|
||||
expect(
|
||||
isarInit.testCacheModels.where().findAllSync().length,
|
||||
1,
|
||||
reason: 'cancelled test should no longer be cached locally',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'stale omission rows are removed after a server-side justification',
|
||||
(tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putCollection(httpClient, '/admin/api/omissions', [
|
||||
_omission('o-1'),
|
||||
_omission('o-2'),
|
||||
]);
|
||||
|
||||
await initAndSync();
|
||||
expect(isarInit.omissionCacheModels.where().findAllSync().length, 2);
|
||||
|
||||
// a teacher retroactively removes an incorrectly recorded absence
|
||||
await _putCollection(httpClient, '/admin/api/omissions', [
|
||||
_omission('o-1'),
|
||||
]);
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
|
||||
expect(
|
||||
isarInit.omissionCacheModels.where().findAllSync().length,
|
||||
1,
|
||||
reason: 'removed absence should no longer be cached locally',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
350
firka/test/e2e/multi_account_cache_isolation_test.dart
Normal file
350
firka/test/e2e/multi_account_cache_isolation_test.dart
Normal file
@@ -0,0 +1,350 @@
|
||||
// ignore_for_file: depend_on_referenced_packages
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
Future<bool?> initialize(
|
||||
InitializationSettings initializationSettings, {
|
||||
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
|
||||
void Function(NotificationResponse)?
|
||||
onDidReceiveBackgroundNotificationResponse,
|
||||
}) async => true;
|
||||
|
||||
@override
|
||||
Future<List<ActiveNotification>> getActiveNotifications() async => [];
|
||||
}
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(
|
||||
HttpClient httpClient,
|
||||
) async {
|
||||
final loginReq = await httpClient.getUrl(
|
||||
Uri.parse('$_mockServerUrl/Account/Login'),
|
||||
);
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception(
|
||||
'Failed to extract code from mock server login: $loginBody',
|
||||
);
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/connect/token'),
|
||||
);
|
||||
tokenReq.headers.contentType = ContentType(
|
||||
'application',
|
||||
'x-www-form-urlencoded',
|
||||
);
|
||||
tokenReq.write(
|
||||
'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}',
|
||||
);
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception(
|
||||
'Token request failed (${tokenResp.statusCode}): $tokenBody',
|
||||
);
|
||||
}
|
||||
return TokenGrantResponse.fromJson(
|
||||
jsonDecode(tokenBody) as Map<String, dynamic>,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetMockServer(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/admin/api/reset'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
await resp.drain();
|
||||
}
|
||||
|
||||
Future<void> _putCollection(
|
||||
HttpClient httpClient,
|
||||
String endpoint,
|
||||
List<Map<String, dynamic>> items,
|
||||
) async {
|
||||
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl$endpoint'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(items));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to PUT $endpoint (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _lesson({
|
||||
required String uid,
|
||||
required String start,
|
||||
required String end,
|
||||
required String name,
|
||||
}) {
|
||||
final today = DateTime.now();
|
||||
final datePrefix =
|
||||
'${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';
|
||||
return {
|
||||
'Uid': uid,
|
||||
'Datum': '${datePrefix}T00:00:00',
|
||||
'KezdetIdopont': '${datePrefix}T$start:00',
|
||||
'VegIdopont': '${datePrefix}T$end:00',
|
||||
'Nev': name,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A', 'Nev': '11.A'},
|
||||
'TanarNeve': 'Teszt Tanár',
|
||||
'Tantargy': {
|
||||
'Uid': '1,MATEK',
|
||||
'Nev': name,
|
||||
'Kategoria': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Kötelező',
|
||||
'Leiras': 'Kötelező tantárgy',
|
||||
},
|
||||
'SortIndex': 1,
|
||||
},
|
||||
'TeremNeve': '101',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Tanóra', 'Leiras': 'Tanóra'},
|
||||
'TanuloJelenlet': {'Uid': '', 'Nev': '', 'Leiras': ''},
|
||||
'Allapot': {'Uid': '1', 'Nev': 'Megtartott', 'Leiras': 'Megtartott óra'},
|
||||
'IsTanuloHaziFeladatEnabled': false,
|
||||
'IsHaziFeladatMegoldva': false,
|
||||
'Csatolmanyok': [],
|
||||
'IsDigitalisOra': false,
|
||||
'DigitalisTamogatoEszkozTipusList': [],
|
||||
'Letrehozas': '${datePrefix}T00:00:00',
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
Map<String, dynamic> _grade(String uid) => {
|
||||
'Uid': uid,
|
||||
'RogzitesDatuma': '2026-09-08T00:00:00',
|
||||
'KeszitesDatuma': '2026-09-08T00:00:00',
|
||||
'Tantargy': {
|
||||
'Uid': '1,MATEK',
|
||||
'Nev': 'Matematika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező', 'Leiras': 'Kötelező tantárgy'},
|
||||
'SortIndex': 1,
|
||||
},
|
||||
'Tema': 'Teszt téma',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli felelet'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat', 'Leiras': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Teszt Tanár',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
'SortIndex': 1,
|
||||
};
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
|
||||
logger = Logger('MultiAccountCacheIsolationTest');
|
||||
|
||||
group('Multi-account cache isolation', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => Directory.systemTemp.path,
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('dev.fluttercommunity.plus/package_info'),
|
||||
(MethodCall methodCall) async => {
|
||||
'appName': 'firka',
|
||||
'packageName': 'app.firka.naplo',
|
||||
'version': '1.0.0',
|
||||
'buildNumber': '1',
|
||||
},
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('firka.app/main'),
|
||||
(MethodCall methodCall) async => 'SM-A705FN;11;30',
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'resyncing one account does not delete another account\'s cached rows',
|
||||
(tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putCollection(httpClient, '/admin/api/timetable', [
|
||||
_lesson(
|
||||
uid: '9001',
|
||||
start: '07:30',
|
||||
end: '08:15',
|
||||
name: 'Matematika',
|
||||
),
|
||||
_lesson(uid: '9002', start: '08:25', end: '09:10', name: 'Fizika'),
|
||||
_lesson(uid: '9003', start: '09:20', end: '10:05', name: 'Kémia'),
|
||||
]);
|
||||
await _putCollection(httpClient, '/admin/api/grades', [
|
||||
_grade('g-1'),
|
||||
]);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
|
||||
// mock server is single-tenant. a cloned token with a different iss gets its own cache.
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenA = TokenModel.fromResp(tokenResp);
|
||||
// studentId must match the server's real id. isCurrentStudent matches on it.
|
||||
final tokenB = TokenModel()
|
||||
..key = tokenA.key + 1
|
||||
..studentId = tokenA.studentId
|
||||
..username = '${tokenA.username}-b'
|
||||
..iss = '${tokenA.iss}-b'
|
||||
..idToken = tokenA.idToken
|
||||
..accessToken = tokenA.accessToken
|
||||
..refreshToken = tokenA.refreshToken
|
||||
..expiryDate = tokenA.expiryDate
|
||||
..tokenVersion = tokenA.tokenVersion
|
||||
..updatedAtMs = tokenA.updatedAtMs;
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenA);
|
||||
await isar.tokenModels.put(tokenB);
|
||||
});
|
||||
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
final clientA = KretaClient(tokenA);
|
||||
final clientB = KretaClient(tokenB);
|
||||
|
||||
await clientA.init();
|
||||
await clientA.renewCache(reInit: false);
|
||||
await clientB.init();
|
||||
await clientB.renewCache(reInit: false);
|
||||
|
||||
List<LessonCacheModel> lessonsFor(KretaClient client) {
|
||||
final today = DateTime.now();
|
||||
bool isToday(DateTime d) =>
|
||||
d.year == today.year &&
|
||||
d.month == today.month &&
|
||||
d.day == today.day;
|
||||
return client.cache
|
||||
.getTimeTable()
|
||||
.findAllSync()
|
||||
.where((l) => isToday(l.start))
|
||||
.toList();
|
||||
}
|
||||
|
||||
expect(lessonsFor(clientA).length, 3);
|
||||
expect(lessonsFor(clientB).length, 3);
|
||||
expect(clientB.cache.getGrades().findAllSync().length, 1);
|
||||
|
||||
// account A's timetable and grade get edited server-side
|
||||
await _putCollection(httpClient, '/admin/api/timetable', [
|
||||
_lesson(
|
||||
uid: '9001',
|
||||
start: '07:30',
|
||||
end: '08:15',
|
||||
name: 'Matematika',
|
||||
),
|
||||
_lesson(
|
||||
uid: '9002-v2',
|
||||
start: '08:20',
|
||||
end: '09:00',
|
||||
name: 'Fizika',
|
||||
),
|
||||
_lesson(uid: '9003', start: '09:05', end: '09:50', name: 'Kémia'),
|
||||
]);
|
||||
await _putCollection(httpClient, '/admin/api/grades', []);
|
||||
await clientA.renewCache(reInit: false);
|
||||
|
||||
final aAfter = lessonsFor(clientA);
|
||||
expect(
|
||||
aAfter.length,
|
||||
3,
|
||||
reason: 'account A should still reconcile correctly',
|
||||
);
|
||||
final aFizika = aAfter.firstWhere((l) => l.name == 'Fizika');
|
||||
expect(
|
||||
aFizika.start.minute,
|
||||
20,
|
||||
reason: "account A should see its own edited copy",
|
||||
);
|
||||
expect(clientA.cache.getGrades().findAllSync(), isEmpty);
|
||||
|
||||
final bAfter = lessonsFor(clientB);
|
||||
expect(
|
||||
bAfter.length,
|
||||
3,
|
||||
reason: "account B's lessons must survive account A's resync",
|
||||
);
|
||||
expect(bAfter.map((l) => l.name).toSet(), {
|
||||
'Matematika',
|
||||
'Fizika',
|
||||
'Kémia',
|
||||
});
|
||||
// lesson name is identical on both sides. start time reveals the account.
|
||||
final bFizika = bAfter.firstWhere((l) => l.name == 'Fizika');
|
||||
expect(bFizika.start.hour, 8);
|
||||
expect(bFizika.start.minute, 25);
|
||||
|
||||
final bGrades = clientB.cache.getGrades().findAllSync();
|
||||
expect(
|
||||
bGrades.length,
|
||||
1,
|
||||
reason:
|
||||
"account B's grade must survive account A's grade being cleared",
|
||||
);
|
||||
expect(
|
||||
bGrades.single.cacheKey,
|
||||
clientB.cache.genCacheKey(UidObj(uid: 'g-1')),
|
||||
reason:
|
||||
"the surviving row must be account B's own copy of g-1, not "
|
||||
"some row aliased in from account A",
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
351
firka/test/e2e/notification_diff_test.dart
Normal file
351
firka/test/e2e/notification_diff_test.dart
Normal file
@@ -0,0 +1,351 @@
|
||||
// ignore_for_file: depend_on_referenced_packages
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/alarm_notification_service.dart';
|
||||
import 'package:firka/services/local_notification_service.dart';
|
||||
import 'package:firka/services/notification_diff_service.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(HttpClient httpClient) async {
|
||||
final loginReq = await httpClient.getUrl(Uri.parse('$_mockServerUrl/Account/Login'));
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception('Failed to extract code from mock server login: $loginBody');
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/connect/token'));
|
||||
tokenReq.headers.contentType = ContentType('application', 'x-www-form-urlencoded');
|
||||
tokenReq.write('grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}');
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception('Token request failed (${tokenResp.statusCode}): $tokenBody');
|
||||
}
|
||||
return TokenGrantResponse.fromJson(jsonDecode(tokenBody) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> _postItem(HttpClient httpClient, String endpoint, Map<String, dynamic> item) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl$endpoint'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(item));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200 && resp.statusCode != 204) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('POST $endpoint failed (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
Future<bool?> initialize(
|
||||
InitializationSettings initializationSettings, {
|
||||
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
|
||||
void Function(NotificationResponse)? onDidReceiveBackgroundNotificationResponse,
|
||||
}) async => true;
|
||||
|
||||
@override
|
||||
Future<void> show(
|
||||
int id,
|
||||
String? title,
|
||||
String? body, {
|
||||
NotificationDetails? notificationDetails,
|
||||
String? payload,
|
||||
}) async {}
|
||||
|
||||
@override
|
||||
Future<List<ActiveNotification>> getActiveNotifications() async => [];
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
|
||||
logger = Logger("NotificationDiffTest");
|
||||
|
||||
group('Notification System End-to-End Test with Mock Kreta Server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => Directory.systemTemp.path,
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('dev.fluttercommunity.plus/package_info'),
|
||||
(MethodCall methodCall) async => {
|
||||
'appName': 'firka',
|
||||
'packageName': 'app.firka.naplo',
|
||||
'version': '1.0.0',
|
||||
'buildNumber': '1',
|
||||
},
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('firka.app/main'),
|
||||
(MethodCall methodCall) async => 'SM-A705FN;11;30',
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Synthetic FCM wakeup diffs changes correctly and posts notifications', (tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await _seedMockLessonsToday(httpClient);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
await Settings.notifyAll.set(true);
|
||||
await Settings.notifyGrades.set(true);
|
||||
await Settings.notifyHomeworkTests.set(true);
|
||||
await Settings.notifyLessons.set(true);
|
||||
await Settings.notifyAbsences.set(true);
|
||||
await Settings.notifyMessages.set(true);
|
||||
await Settings.notifyMutedSubjects.set('[]');
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
if (initData.client != null) {
|
||||
await initData.client!.init();
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
}
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isEmpty);
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
final newGradeUid = 'test-grade-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final newGradeTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/grades', {
|
||||
'Uid': newGradeUid,
|
||||
'RogzitesDatuma': newGradeTime,
|
||||
'KeszitesDatuma': newGradeTime,
|
||||
'Tantargy': {
|
||||
'Uid': '10,INF',
|
||||
'Nev': 'Informatika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 10,
|
||||
},
|
||||
'Tema': 'Algoritmusok',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Gyakorlati feladat'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Turing Alan',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final gradeNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('jegy'),
|
||||
);
|
||||
expect(gradeNotif.title, contains('jegy'));
|
||||
expect(gradeNotif.body, contains('Informatika'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
final newHwUid = 'test-hw-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final newHwTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/homework', {
|
||||
'Uid': newHwUid,
|
||||
'Tantargy': {
|
||||
'Uid': '11,BIO',
|
||||
'Nev': 'Biológia',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 11,
|
||||
},
|
||||
'TantargyNeve': 'Biológia',
|
||||
'RogzitoTanarNeve': 'Darwin Károly',
|
||||
'Szoveg': 'Olvassátok el a sejtbiológia fejezetet.',
|
||||
'FeladasDatuma': newHwTime,
|
||||
'HataridoDatuma': DateTime.now().add(const Duration(days: 3)).toUtc().toIso8601String(),
|
||||
'RogzitesIdopontja': newHwTime,
|
||||
'IsTanarRogzitette': true,
|
||||
'IsMegoldva': false,
|
||||
'IsBeadhato': false,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final hwNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('házi feladat'),
|
||||
);
|
||||
expect(hwNotif.title, contains('házi feladat'));
|
||||
expect(hwNotif.body, contains('Biológia'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await _postItem(httpClient, '/admin/api/timetable/mutate', {
|
||||
'Uid': '5000',
|
||||
'Nev': 'Matematika',
|
||||
'HelyettesTanarNeve': 'Prof. Helyettes',
|
||||
'Allapot': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Megtartott',
|
||||
'Leiras': 'Megtartott óra',
|
||||
},
|
||||
'Tipus': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Tanóra',
|
||||
'Leiras': 'Tanóra',
|
||||
},
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final subNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('Helyettesítés'),
|
||||
);
|
||||
expect(subNotif.title, equals('Helyettesítés'));
|
||||
expect(subNotif.body, contains('Prof. Helyettes'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await _postItem(httpClient, '/admin/api/timetable/mutate', {
|
||||
'Uid': '5000',
|
||||
'Nev': 'Matematika',
|
||||
'Allapot': {
|
||||
'Uid': '3',
|
||||
'Nev': 'Elmaradt',
|
||||
'Leiras': 'Elmaradt óra',
|
||||
},
|
||||
'Tipus': {
|
||||
'Uid': 'UresOra',
|
||||
'Nev': 'UresOra',
|
||||
'Leiras': 'Lyukasóra',
|
||||
},
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final cancelNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('Elmaradt óra'),
|
||||
);
|
||||
expect(cancelNotif.title, equals('Elmaradt óra'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await Settings.notifyMutedSubjects.set(jsonEncode(['Fizika']));
|
||||
|
||||
final mutedGradeUid = 'test-grade-muted-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final mutedGradeTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/grades', {
|
||||
'Uid': mutedGradeUid,
|
||||
'RogzitesDatuma': mutedGradeTime,
|
||||
'KeszitesDatuma': mutedGradeTime,
|
||||
'Tantargy': {
|
||||
'Uid': '12,FIZ',
|
||||
'Nev': 'Fizika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 12,
|
||||
},
|
||||
'Tema': 'Mechanika',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Írásbeli'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Newton Izsák',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
|
||||
final fizikaNotifs = LocalNotificationService.postedNotifications
|
||||
.where((n) => n.body.contains('Fizika') || n.body.contains('Newton'))
|
||||
.toList();
|
||||
expect(fizikaNotifs, isEmpty);
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
final alarmGradeUid = 'test-grade-alarm-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final alarmGradeTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/grades', {
|
||||
'Uid': alarmGradeUid,
|
||||
'RogzitesDatuma': alarmGradeTime,
|
||||
'KeszitesDatuma': alarmGradeTime,
|
||||
'Tantargy': {
|
||||
'Uid': '14,TOR',
|
||||
'Nev': 'Történelem',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 14,
|
||||
},
|
||||
'Tema': 'Középkor',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Szóbeli'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Hérodotosz',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await alarmNotificationWakeupCallback();
|
||||
|
||||
final alarmNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('jegy') && n.body.contains('Történelem'),
|
||||
);
|
||||
expect(alarmNotif.title, contains('jegy'));
|
||||
expect(alarmNotif.body, contains('Történelem'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
248
firka/test/e2e/screenshot_widget_test.dart
Normal file
248
firka/test/e2e/screenshot_widget_test.dart
Normal file
@@ -0,0 +1,248 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _getMockLessons(HttpClient httpClient) async {
|
||||
final req = await httpClient.getUrl(Uri.parse('$_mockServerUrl/admin/api/timetable'));
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
final list = jsonDecode(body) as List;
|
||||
return list.cast<Map<String, dynamic>>();
|
||||
}
|
||||
|
||||
Future<void> _putMockLessons(HttpClient httpClient, List<Map<String, dynamic>> lessons) async {
|
||||
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl/admin/api/timetable'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(lessons));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to update mock lessons (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
class TimetableWidgetView extends StatelessWidget {
|
||||
final GlobalKey boundaryKey;
|
||||
final List<Map<String, dynamic>> lessons;
|
||||
|
||||
const TimetableWidgetView({
|
||||
required this.boundaryKey,
|
||||
required this.lessons,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const bgColor = Color(0xFFFAFFF0);
|
||||
const cardColor = Color(0xFFEFF4E3);
|
||||
const textPrimary = Color(0xFF1B1C18);
|
||||
const textSecondary = Color(0xFF45483D);
|
||||
const warningColor = Color(0xFFE65100);
|
||||
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Center(
|
||||
child: RepaintBoundary(
|
||||
key: boundaryKey,
|
||||
child: Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Mai órarend',
|
||||
style: TextStyle(
|
||||
color: textSecondary,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
for (final lesson in lessons.take(4))
|
||||
Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: lesson['HelyettesTanarNeve'] != null &&
|
||||
(lesson['HelyettesTanarNeve'] as String).isNotEmpty
|
||||
? warningColor.withValues(alpha: 0.15)
|
||||
: cardColor,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'${lesson['Oraszam'] ?? 1}.',
|
||||
style: const TextStyle(
|
||||
color: textSecondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
lesson['Nev'] as String? ?? '',
|
||||
style: const TextStyle(
|
||||
color: textPrimary,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (lesson['HelyettesTanarNeve'] != null &&
|
||||
(lesson['HelyettesTanarNeve'] as String).isNotEmpty)
|
||||
Text(
|
||||
'Helyettes: ${lesson['HelyettesTanarNeve']}',
|
||||
style: const TextStyle(
|
||||
color: warningColor,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (lesson['TeremNeve'] != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: textSecondary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
lesson['TeremNeve'] as String,
|
||||
style: const TextStyle(
|
||||
color: textSecondary,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<int>> _capturePng(WidgetTester tester, GlobalKey key) async {
|
||||
return await tester.runAsync(() async {
|
||||
final boundary = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
|
||||
final image = await boundary.toImage(pixelRatio: 2.0);
|
||||
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
return byteData!.buffer.asUint8List().toList();
|
||||
}) ?? [];
|
||||
}
|
||||
|
||||
int _countDifferentBytes(List<int> a, List<int> b) {
|
||||
int diff = 0;
|
||||
final minLen = a.length < b.length ? a.length : b.length;
|
||||
for (int i = 0; i < minLen; i++) {
|
||||
if (a[i] != b[i]) diff++;
|
||||
}
|
||||
diff += (a.length - b.length).abs();
|
||||
return diff;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
group('Widget End-to-End Screenshot Comparison Test', () {
|
||||
late HttpClient httpClient;
|
||||
late List<Map<String, dynamic>> originalLessons;
|
||||
|
||||
setUp(() async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
originalLessons = await _getMockLessons(httpClient);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
try {
|
||||
await _putMockLessons(httpClient, originalLessons);
|
||||
} catch (_) {}
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Widget screenshots differ programmatically after mock server timetable mutation', (tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
late List<Map<String, dynamic>> lessonsBefore;
|
||||
await tester.runAsync(() async {
|
||||
await _seedMockLessonsToday(httpClient);
|
||||
lessonsBefore = await _getMockLessons(httpClient);
|
||||
});
|
||||
expect(lessonsBefore.isNotEmpty, isTrue);
|
||||
|
||||
final boundaryKey1 = GlobalKey();
|
||||
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey1, lessons: lessonsBefore));
|
||||
await tester.pump();
|
||||
|
||||
final screenshotBefore = await _capturePng(tester, boundaryKey1);
|
||||
expect(screenshotBefore, isNotEmpty);
|
||||
|
||||
late List<Map<String, dynamic>> lessonsAfter;
|
||||
final targetName = lessonsBefore.first['Nev'];
|
||||
await tester.runAsync(() async {
|
||||
final mutateReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/mutate'));
|
||||
mutateReq.headers.contentType = ContentType.json;
|
||||
mutateReq.write(jsonEncode({
|
||||
'Uid': lessonsBefore.first['Uid'],
|
||||
'Nev': targetName,
|
||||
'TeremNeve': 'LAB-999',
|
||||
'HelyettesTanarNeve': 'Prof. E2E Teszt',
|
||||
}));
|
||||
final mutateResp = await mutateReq.close();
|
||||
expect(mutateResp.statusCode, equals(200));
|
||||
|
||||
lessonsAfter = await _getMockLessons(httpClient);
|
||||
});
|
||||
|
||||
final targetLesson = lessonsAfter.firstWhere((l) => l['Nev'] == targetName);
|
||||
expect(targetLesson['TeremNeve'], equals('LAB-999'));
|
||||
expect(targetLesson['HelyettesTanarNeve'], equals('Prof. E2E Teszt'));
|
||||
|
||||
final boundaryKey2 = GlobalKey();
|
||||
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey2, lessons: lessonsAfter));
|
||||
await tester.pump();
|
||||
|
||||
final screenshotAfter = await _capturePng(tester, boundaryKey2);
|
||||
expect(screenshotAfter, isNotEmpty);
|
||||
|
||||
expect(screenshotBefore, isNot(equals(screenshotAfter)));
|
||||
expect(_countDifferentBytes(screenshotBefore, screenshotAfter), greaterThan(0));
|
||||
});
|
||||
});
|
||||
}
|
||||
278
firka/test/e2e/timetable_cache_reconciliation_test.dart
Normal file
278
firka/test/e2e/timetable_cache_reconciliation_test.dart
Normal file
@@ -0,0 +1,278 @@
|
||||
// ignore_for_file: depend_on_referenced_packages
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka_common/data/cache_manager.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
Future<bool?> initialize(
|
||||
InitializationSettings initializationSettings, {
|
||||
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
|
||||
void Function(NotificationResponse)?
|
||||
onDidReceiveBackgroundNotificationResponse,
|
||||
}) async => true;
|
||||
|
||||
@override
|
||||
Future<List<ActiveNotification>> getActiveNotifications() async => [];
|
||||
}
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(
|
||||
HttpClient httpClient,
|
||||
) async {
|
||||
final loginReq = await httpClient.getUrl(
|
||||
Uri.parse('$_mockServerUrl/Account/Login'),
|
||||
);
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception(
|
||||
'Failed to extract code from mock server login: $loginBody',
|
||||
);
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/connect/token'),
|
||||
);
|
||||
tokenReq.headers.contentType = ContentType(
|
||||
'application',
|
||||
'x-www-form-urlencoded',
|
||||
);
|
||||
tokenReq.write(
|
||||
'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}',
|
||||
);
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception(
|
||||
'Token request failed (${tokenResp.statusCode}): $tokenBody',
|
||||
);
|
||||
}
|
||||
return TokenGrantResponse.fromJson(
|
||||
jsonDecode(tokenBody) as Map<String, dynamic>,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetMockServer(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(
|
||||
Uri.parse('$_mockServerUrl/admin/api/reset'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
await resp.drain();
|
||||
}
|
||||
|
||||
Future<void> _putTimetable(
|
||||
HttpClient httpClient,
|
||||
List<Map<String, dynamic>> lessons,
|
||||
) async {
|
||||
final req = await httpClient.putUrl(
|
||||
Uri.parse('$_mockServerUrl/admin/api/timetable'),
|
||||
);
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(lessons));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to PUT timetable (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _lesson({
|
||||
required String uid,
|
||||
required String start,
|
||||
required String end,
|
||||
required String name,
|
||||
}) {
|
||||
final today = DateTime.now();
|
||||
final datePrefix =
|
||||
'${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';
|
||||
return {
|
||||
'Uid': uid,
|
||||
'Datum': '${datePrefix}T00:00:00',
|
||||
'KezdetIdopont': '${datePrefix}T$start:00',
|
||||
'VegIdopont': '${datePrefix}T$end:00',
|
||||
'Nev': name,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A', 'Nev': '11.A'},
|
||||
'TanarNeve': 'Teszt Tanár',
|
||||
'Tantargy': {
|
||||
'Uid': '1,MATEK',
|
||||
'Nev': name,
|
||||
'Kategoria': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Kötelező',
|
||||
'Leiras': 'Kötelező tantárgy',
|
||||
},
|
||||
'SortIndex': 1,
|
||||
},
|
||||
'TeremNeve': '101',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Tanóra', 'Leiras': 'Tanóra'},
|
||||
'TanuloJelenlet': {'Uid': '', 'Nev': '', 'Leiras': ''},
|
||||
'Allapot': {'Uid': '1', 'Nev': 'Megtartott', 'Leiras': 'Megtartott óra'},
|
||||
'IsTanuloHaziFeladatEnabled': false,
|
||||
'IsHaziFeladatMegoldva': false,
|
||||
'Csatolmanyok': [],
|
||||
'IsDigitalisOra': false,
|
||||
'DigitalisTamogatoEszkozTipusList': [],
|
||||
'Letrehozas': '${datePrefix}T00:00:00',
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
|
||||
logger = Logger('TimetableCacheReconciliationTest');
|
||||
|
||||
group('Timetable cache reconciliation against mock Kreta server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => Directory.systemTemp.path,
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('dev.fluttercommunity.plus/package_info'),
|
||||
(MethodCall methodCall) async => {
|
||||
'appName': 'firka',
|
||||
'packageName': 'app.firka.naplo',
|
||||
'version': '1.0.0',
|
||||
'buildNumber': '1',
|
||||
},
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('firka.app/main'),
|
||||
(MethodCall methodCall) async => 'SM-A705FN;11;30',
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'stale lesson rows are removed when the school edits the timetable',
|
||||
(tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await _resetMockServer(httpClient);
|
||||
await _putTimetable(httpClient, [
|
||||
_lesson(
|
||||
uid: '9001',
|
||||
start: '07:30',
|
||||
end: '08:15',
|
||||
name: 'Matematika',
|
||||
),
|
||||
_lesson(uid: '9002', start: '08:25', end: '09:10', name: 'Fizika'),
|
||||
_lesson(uid: '9003', start: '09:20', end: '10:05', name: 'Kémia'),
|
||||
]);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
final client = initData.client!;
|
||||
await client.init();
|
||||
await client.renewCache(reInit: false);
|
||||
|
||||
final today = DateTime.now();
|
||||
bool isToday(DateTime d) =>
|
||||
d.year == today.year &&
|
||||
d.month == today.month &&
|
||||
d.day == today.day;
|
||||
List<LessonCacheModel> lessonsFor(CacheManager cache) => cache
|
||||
.getTimeTable()
|
||||
.findAllSync()
|
||||
.where((l) => isToday(l.start))
|
||||
.toList();
|
||||
|
||||
final before = lessonsFor(client.cache);
|
||||
expect(
|
||||
before.length,
|
||||
3,
|
||||
reason: 'initial sync should cache exactly the 3 seeded lessons',
|
||||
);
|
||||
|
||||
// simulates a school schedule edit
|
||||
await _putTimetable(httpClient, [
|
||||
_lesson(
|
||||
uid: '9001',
|
||||
start: '07:30',
|
||||
end: '08:15',
|
||||
name: 'Matematika',
|
||||
),
|
||||
_lesson(
|
||||
uid: '9002-v2',
|
||||
start: '08:20',
|
||||
end: '09:00',
|
||||
name: 'Fizika',
|
||||
),
|
||||
_lesson(uid: '9003', start: '09:05', end: '09:50', name: 'Kémia'),
|
||||
]);
|
||||
|
||||
await client.renewCache(reInit: false);
|
||||
|
||||
final after = lessonsFor(client.cache);
|
||||
expect(
|
||||
after.length,
|
||||
3,
|
||||
reason:
|
||||
'stale lesson row for the old timetable version should have been deleted',
|
||||
);
|
||||
expect(
|
||||
after.map((l) => l.dailyNth).toSet().length,
|
||||
after.length,
|
||||
reason: 'no two lessons should occupy the same period number',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
102
firka/test/services/alarm_notification_service_test.dart
Normal file
102
firka/test/services/alarm_notification_service_test.dart
Normal file
@@ -0,0 +1,102 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/alarm_notification_service.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const alarmChannel = MethodChannel(
|
||||
'dev.fluttercommunity.plus/android_alarm_manager',
|
||||
JSONMethodCodec(),
|
||||
);
|
||||
|
||||
late Directory tempDir;
|
||||
late List<MethodCall> alarmCalls;
|
||||
|
||||
setUp(() async {
|
||||
alarmCalls = [];
|
||||
AlarmNotificationService.resetForTesting();
|
||||
AlarmNotificationService.isAndroidOverride = true;
|
||||
|
||||
tempDir = Directory.systemTemp.createTempSync('alarm_test_');
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => tempDir.path,
|
||||
);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
alarmChannel,
|
||||
(MethodCall call) async {
|
||||
alarmCalls.add(call);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
AndroidAlarmManager.setTestOverrides(
|
||||
getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
|
||||
);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
AlarmNotificationService.resetForTesting();
|
||||
try {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
test('initialize invokes AlarmService.start', () async {
|
||||
await AlarmNotificationService.initialize();
|
||||
expect(AlarmNotificationService.isInitialized, isTrue);
|
||||
expect(alarmCalls.any((call) => call.method == 'AlarmService.start'), isTrue);
|
||||
});
|
||||
|
||||
test('schedule sets up hourly periodic alarm with sync ID 910001', () async {
|
||||
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
|
||||
await AlarmNotificationService.schedule();
|
||||
|
||||
final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
|
||||
expect(periodicCalls, isNotEmpty);
|
||||
final call = periodicCalls.last;
|
||||
expect(call.arguments[0], 910001);
|
||||
expect(call.arguments[3], isTrue); // wakeup
|
||||
expect(call.arguments[5], const Duration(hours: 1).inMilliseconds);
|
||||
expect(call.arguments[6], isTrue); // rescheduleOnReboot
|
||||
});
|
||||
|
||||
test('schedule sets up two-hourly periodic alarm when configured', () async {
|
||||
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
|
||||
await AlarmNotificationService.schedule();
|
||||
|
||||
final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
|
||||
expect(periodicCalls, isNotEmpty);
|
||||
final call = periodicCalls.last;
|
||||
expect(call.arguments[0], 910001);
|
||||
expect(call.arguments[3], isTrue); // wakeup
|
||||
expect(call.arguments[5], const Duration(hours: 2).inMilliseconds);
|
||||
expect(call.arguments[6], isTrue); // rescheduleOnReboot
|
||||
});
|
||||
|
||||
test('cancel invokes Alarm.cancel with sync ID 910001', () async {
|
||||
await AlarmNotificationService.cancel();
|
||||
|
||||
final cancelCalls = alarmCalls.where((call) => call.method == 'Alarm.cancel').toList();
|
||||
expect(cancelCalls, isNotEmpty);
|
||||
expect(cancelCalls.last.arguments[0], 910001);
|
||||
});
|
||||
}
|
||||
174
firka/test/services/notification_delivery_service_test.dart
Normal file
174
firka/test/services/notification_delivery_service_test.dart
Normal file
@@ -0,0 +1,174 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/services/alarm_notification_service.dart';
|
||||
import 'package:firka/services/notification_delivery_service.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const alarmChannel = MethodChannel(
|
||||
'dev.fluttercommunity.plus/android_alarm_manager',
|
||||
JSONMethodCodec(),
|
||||
);
|
||||
|
||||
late Directory tempDir;
|
||||
late List<MethodCall> alarmCalls;
|
||||
|
||||
setUp(() async {
|
||||
alarmCalls = [];
|
||||
NotificationDeliveryService.resetForTesting();
|
||||
AlarmNotificationService.resetForTesting();
|
||||
NotificationDeliveryService.isAndroidOverride = true;
|
||||
AlarmNotificationService.isAndroidOverride = true;
|
||||
|
||||
tempDir = Directory.systemTemp.createTempSync('delivery_test_');
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => tempDir.path,
|
||||
);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
alarmChannel,
|
||||
(MethodCall call) async {
|
||||
alarmCalls.add(call);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
AndroidAlarmManager.setTestOverrides(
|
||||
getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
|
||||
);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
NotificationDeliveryService.resetForTesting();
|
||||
AlarmNotificationService.resetForTesting();
|
||||
try {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
group('NotificationDeliveryService effective method resolution', () {
|
||||
test('resolves explicit FCM setting', () async {
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
|
||||
final effective = await NotificationDeliveryService.getEffectiveMethod();
|
||||
expect(effective, NotificationDeliveryMethod.fcm);
|
||||
});
|
||||
|
||||
test('resolves explicit Alarm setting', () async {
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
final effective = await NotificationDeliveryService.getEffectiveMethod();
|
||||
expect(effective, NotificationDeliveryMethod.alarm);
|
||||
});
|
||||
|
||||
test('auto resolves to FCM when GMS is available', () async {
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
|
||||
NotificationDeliveryService.gmsAvailabilityOverride = true;
|
||||
|
||||
final effective = await NotificationDeliveryService.getEffectiveMethod();
|
||||
expect(effective, NotificationDeliveryMethod.fcm);
|
||||
});
|
||||
|
||||
test('auto resolves to Alarm when GMS is unavailable', () async {
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
|
||||
NotificationDeliveryService.gmsAvailabilityOverride = false;
|
||||
|
||||
final effective = await NotificationDeliveryService.getEffectiveMethod();
|
||||
expect(effective, NotificationDeliveryMethod.alarm);
|
||||
});
|
||||
});
|
||||
|
||||
group('NotificationDeliveryService backend coordination & settings effects', () {
|
||||
test('syncDeliveryBackend cancels alarm when notifyAll is disabled', () async {
|
||||
await Settings.notifyAll.set(false);
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
|
||||
alarmCalls.clear();
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
|
||||
final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
|
||||
expect(cancelCalls, isNotEmpty);
|
||||
expect(cancelCalls.last.arguments[0], 910001);
|
||||
});
|
||||
|
||||
test('syncDeliveryBackend schedules alarm when method is alarm and notifyAll is true', () async {
|
||||
await Settings.notifyAll.set(true);
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
|
||||
|
||||
alarmCalls.clear();
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
|
||||
final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
|
||||
expect(periodicCalls, isNotEmpty);
|
||||
expect(periodicCalls.last.arguments[0], 910001);
|
||||
expect(periodicCalls.last.arguments[5], const Duration(hours: 1).inMilliseconds);
|
||||
});
|
||||
|
||||
test('syncDeliveryBackend cancels alarm when switching from alarm to fcm', () async {
|
||||
await Settings.notifyAll.set(true);
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
|
||||
alarmCalls.clear();
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
|
||||
final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
|
||||
expect(cancelCalls, isNotEmpty);
|
||||
expect(cancelCalls.last.arguments[0], 910001);
|
||||
});
|
||||
|
||||
test('handleWakeupIntervalChange reschedules alarm with new duration', () async {
|
||||
await Settings.notifyAll.set(true);
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
|
||||
|
||||
alarmCalls.clear();
|
||||
await NotificationDeliveryService.handleWakeupIntervalChange();
|
||||
|
||||
final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
|
||||
expect(periodicCalls, isNotEmpty);
|
||||
expect(periodicCalls.last.arguments[5], const Duration(hours: 2).inMilliseconds);
|
||||
});
|
||||
|
||||
test('changing settings triggers registered settings effects', () async {
|
||||
Settings.onChange(SettingsRegistry.notifyAll, (_) async {
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
});
|
||||
Settings.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
|
||||
await NotificationDeliveryService.syncDeliveryBackend();
|
||||
});
|
||||
Settings.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
|
||||
await NotificationDeliveryService.handleWakeupIntervalChange();
|
||||
});
|
||||
|
||||
await Settings.notifyAll.set(true);
|
||||
alarmCalls.clear();
|
||||
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
|
||||
expect(alarmCalls.any((c) => c.method == 'Alarm.periodic'), isTrue);
|
||||
|
||||
alarmCalls.clear();
|
||||
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
|
||||
expect(alarmCalls.any((c) => c.method == 'Alarm.cancel'), isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
14
firka/test/ui/dave_mascot_test.dart
Normal file
14
firka/test/ui/dave_mascot_test.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:firka/ui/shared/dave_mascot.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('getDaveColorFilter returns null for default firka green (#A7DC22)', () {
|
||||
expect(getDaveColorFilter(const Color(0xFFA7DC22)), isNull);
|
||||
});
|
||||
|
||||
test('getDaveColorFilter returns non-null ColorFilter for non-default color', () {
|
||||
final filter = getDaveColorFilter(const Color(0xFFFF0000));
|
||||
expect(filter, isNotNull);
|
||||
});
|
||||
}
|
||||
55
firka/test/ui/theme_sharing_test.dart
Normal file
55
firka/test/ui/theme_sharing_test.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
|
||||
import 'package:firka/ui/phone/screens/themes/widgets/theme_qr_card.dart';
|
||||
import 'package:firka_common/ui/theme/core_theme.dart';
|
||||
import 'package:firka_common/ui/theme/theme_binary_format.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('Theme sharing binary format in firka', () {
|
||||
test('encode and decode URL-safe base64 string for firkaCore', () {
|
||||
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore);
|
||||
final b64 = ThemeBinaryFormat.toBase64(bytes);
|
||||
expect(b64.isNotEmpty, isTrue);
|
||||
|
||||
final decodedBytes = ThemeBinaryFormat.fromBase64(b64);
|
||||
final decoded = ThemeBinaryFormat.decode(decodedBytes);
|
||||
final slots = decoded.toThemeSlots();
|
||||
expect(slots.light[ThemeColorSlot.background], firkaCore.light.background);
|
||||
expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background);
|
||||
expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent);
|
||||
expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent);
|
||||
});
|
||||
|
||||
testWidgets('ThemeQrCard renders theme name and QR code', (tester) async {
|
||||
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore);
|
||||
final b64 = ThemeBinaryFormat.toBase64(bytes);
|
||||
final userTheme = UserTheme(
|
||||
id: 'test_theme',
|
||||
name: 'Firka Green',
|
||||
origin: ThemeOrigin.own,
|
||||
swatch: const [
|
||||
Color(0xFFA7DC22),
|
||||
Colors.white,
|
||||
Color(0xFF1E1E1E),
|
||||
],
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: ThemeQrCard(
|
||||
theme: userTheme,
|
||||
shareData: b64,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('Firka Green'), findsOneWidget);
|
||||
expect(find.text('https://firka.app'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -18,6 +18,14 @@ extension IterableExtension<T> on Iterable<T> {
|
||||
}
|
||||
}
|
||||
|
||||
extension FirstUpperExtension on String {
|
||||
String firstUpper() {
|
||||
if (isEmpty) return this;
|
||||
if (length == 1) this[0].toUpperCase();
|
||||
return this[0].toUpperCase() + substring(1, length);
|
||||
}
|
||||
}
|
||||
|
||||
extension MidnightExtension on DateTime {
|
||||
DateTime getMidnight() {
|
||||
return subtract(
|
||||
|
||||
@@ -18,6 +18,9 @@ import 'package:path_provider/path_provider.dart';
|
||||
late Isar isarInit;
|
||||
|
||||
Future<Isar> initDB() async {
|
||||
if (Isar.getInstance() != null) {
|
||||
return isarInit = Isar.getInstance()!;
|
||||
}
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
|
||||
isarInit = await Isar.open(
|
||||
|
||||
@@ -50,6 +50,7 @@ class LessonCacheModel extends GenericCacheModel<Lesson> {
|
||||
..topic = ctx.data.theme
|
||||
..roomName = ctx.data.roomName
|
||||
..type = ctx.data.type.name
|
||||
..createdAt = ctx.data.lastModifiedAt
|
||||
..classGroup.init(ctx.cacheManager, ctx.data.classGroup)
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:firka_common/data/models/class_group_cache_model.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/util.dart';
|
||||
@@ -15,6 +16,7 @@ class OmissionCacheModel extends GenericCacheModel<Omission> {
|
||||
String? proofType;
|
||||
|
||||
final lesson = IsarLink<LessonCacheModel>();
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Omission> ctx) {
|
||||
@@ -23,7 +25,8 @@ class OmissionCacheModel extends GenericCacheModel<Omission> {
|
||||
..state = ctx.data.state
|
||||
..teacherName = ctx.data.teacher
|
||||
..proofType = ctx.data.proofType?.description
|
||||
..createdAt = ctx.data.createdAt;
|
||||
..createdAt = ctx.data.createdAt
|
||||
..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup);
|
||||
lesson.value = ctx.cacheManager
|
||||
.getTimeTable()
|
||||
.startEqualTo(ctx.data.lesson!.start)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:firka_common/data/models/class_group_cache_model.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/util.dart';
|
||||
@@ -14,6 +15,7 @@ class TestCacheModel extends GenericCacheModel<Test> {
|
||||
|
||||
@Backlink(to: "test")
|
||||
final lesson = IsarLink<LessonCacheModel>();
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Test> ctx) {
|
||||
@@ -21,6 +23,7 @@ class TestCacheModel extends GenericCacheModel<Test> {
|
||||
..topic = ctx.data.theme
|
||||
..method = ctx.data.method.description
|
||||
..teacherName = ctx.data.teacherName
|
||||
..createdAt = ctx.data.reportDate;
|
||||
..createdAt = ctx.data.reportDate
|
||||
..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:firka_common/core/extensions.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@@ -34,7 +35,7 @@ class GradeSmallCard extends StatelessWidget {
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
subject.name,
|
||||
subject.name.firstUpper(),
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
|
||||
67
firka_common/lib/ui/theme/core/butcher_vanity.dart
Normal file
67
firka_common/lib/ui/theme/core/butcher_vanity.dart
Normal file
@@ -0,0 +1,67 @@
|
||||
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),
|
||||
),
|
||||
);
|
||||
162
firka_common/lib/ui/theme/core/m3e.dart
Normal file
162
firka_common/lib/ui/theme/core/m3e.dart
Normal file
@@ -0,0 +1,162 @@
|
||||
part of "../core_theme.dart";
|
||||
|
||||
const _defaultM3eSeed = Color(0xFF6750A4);
|
||||
|
||||
CoreThemeColors coreColorsFromColorScheme(ColorScheme scheme) {
|
||||
final isLight = scheme.brightness == Brightness.light;
|
||||
final bg = scheme.surface;
|
||||
final card = isLight ? scheme.surfaceContainerLow : scheme.surfaceContainer;
|
||||
final buttonFill =
|
||||
isLight ? scheme.surfaceContainerLowest : scheme.surfaceContainerHigh;
|
||||
final accent = scheme.primary;
|
||||
final secondary = scheme.secondary;
|
||||
|
||||
return CoreThemeColors(
|
||||
background: bg,
|
||||
backgroundGradient: null,
|
||||
backgroundAmoled: Colors.black,
|
||||
background0p: bg.withAlpha(0),
|
||||
success: isLight ? const Color(0xFF34C759) : const Color(0xFF32D74B),
|
||||
shadowBlur: isLight ? 2 : 0,
|
||||
textPrimary: scheme.onSurface,
|
||||
textSecondary: scheme.onSurfaceVariant,
|
||||
textTertiary: scheme.onSurface.withAlpha(0x80),
|
||||
textTeritary: scheme.outline,
|
||||
textPrimaryLight: scheme.onSurface,
|
||||
textSecondaryLight: scheme.onSurfaceVariant,
|
||||
textTertiaryLight: scheme.onSurface.withAlpha(0x80),
|
||||
card: card,
|
||||
cardTranslucent: card.withAlpha(0x80),
|
||||
buttonSecondaryFill: buttonFill,
|
||||
buttonDisabledIcon: scheme.outline.withAlpha(0x80),
|
||||
accent: accent,
|
||||
secondary: secondary,
|
||||
shadowColor: scheme.shadow.withAlpha(isLight ? 0x26 : 0x40),
|
||||
a10p: accent.withAlpha(0x1a),
|
||||
a15p: accent.withAlpha(0x26),
|
||||
warningAccent: const Color(0xFFFFA046),
|
||||
warningText: isLight ? const Color(0xFF8F531B) : const Color(0xFFF0B37A),
|
||||
warning15p: const Color(0x26FFA046),
|
||||
warningCard: isLight ? const Color(0xFFFAEBDC) : const Color(0xFF201203),
|
||||
errorAccent: scheme.error,
|
||||
errorText: isLight ? const Color(0xFF8F1B4F) : const Color(0xFFF59EC5),
|
||||
error15p: scheme.error.withAlpha(0x26),
|
||||
errorCard: isLight ? scheme.errorContainer : const Color(0xFF1E030F),
|
||||
);
|
||||
}
|
||||
|
||||
ColorScheme corePaletteToFlutterColorScheme(
|
||||
// ignore: deprecated_member_use
|
||||
CorePalette palette, {
|
||||
required bool isLight,
|
||||
}) {
|
||||
// ignore: deprecated_member_use
|
||||
final scheme = isLight
|
||||
// ignore: deprecated_member_use
|
||||
? Scheme.lightFromCorePalette(palette)
|
||||
// ignore: deprecated_member_use
|
||||
: Scheme.darkFromCorePalette(palette);
|
||||
|
||||
final base = ColorScheme.fromSeed(
|
||||
seedColor: Color(scheme.primary),
|
||||
brightness: isLight ? Brightness.light : Brightness.dark,
|
||||
);
|
||||
|
||||
return base.copyWith(
|
||||
primary: Color(scheme.primary),
|
||||
onPrimary: Color(scheme.onPrimary),
|
||||
primaryContainer: Color(scheme.primaryContainer),
|
||||
onPrimaryContainer: Color(scheme.onPrimaryContainer),
|
||||
secondary: Color(scheme.secondary),
|
||||
onSecondary: Color(scheme.onSecondary),
|
||||
secondaryContainer: Color(scheme.secondaryContainer),
|
||||
onSecondaryContainer: Color(scheme.onSecondaryContainer),
|
||||
tertiary: Color(scheme.tertiary),
|
||||
onTertiary: Color(scheme.onTertiary),
|
||||
tertiaryContainer: Color(scheme.tertiaryContainer),
|
||||
onTertiaryContainer: Color(scheme.onTertiaryContainer),
|
||||
error: Color(scheme.error),
|
||||
onError: Color(scheme.onError),
|
||||
errorContainer: Color(scheme.errorContainer),
|
||||
onErrorContainer: Color(scheme.onErrorContainer),
|
||||
outline: Color(scheme.outline),
|
||||
outlineVariant: Color(scheme.outlineVariant),
|
||||
surface: Color(scheme.surface),
|
||||
onSurface: Color(scheme.onSurface),
|
||||
onSurfaceVariant: Color(scheme.onSurfaceVariant),
|
||||
inverseSurface: Color(scheme.inverseSurface),
|
||||
onInverseSurface: Color(scheme.inverseOnSurface),
|
||||
inversePrimary: Color(scheme.inversePrimary),
|
||||
shadow: Color(scheme.shadow),
|
||||
surfaceTint: Color(scheme.primary),
|
||||
scrim: Color(scheme.scrim),
|
||||
);
|
||||
}
|
||||
|
||||
final _defaultM3eLight = coreColorsFromColorScheme(
|
||||
ColorScheme.fromSeed(
|
||||
seedColor: _defaultM3eSeed,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
);
|
||||
|
||||
final _defaultM3eDark = coreColorsFromColorScheme(
|
||||
ColorScheme.fromSeed(
|
||||
seedColor: _defaultM3eSeed,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
);
|
||||
|
||||
CoreTheme m3eCore = CoreTheme(
|
||||
id: "m3e",
|
||||
light: _defaultM3eLight,
|
||||
dark: _defaultM3eDark,
|
||||
);
|
||||
|
||||
void updateM3eFromColorSchemes({
|
||||
ColorScheme? light,
|
||||
ColorScheme? dark,
|
||||
}) {
|
||||
final lightColors =
|
||||
light != null ? coreColorsFromColorScheme(light) : _defaultM3eLight;
|
||||
final darkColors =
|
||||
dark != null ? coreColorsFromColorScheme(dark) : _defaultM3eDark;
|
||||
m3eCore = CoreTheme(
|
||||
id: "m3e",
|
||||
light: lightColors,
|
||||
dark: darkColors,
|
||||
);
|
||||
coreThemes["m3e"] = m3eCore;
|
||||
}
|
||||
|
||||
Future<void> regenerateM3eTheme() async {
|
||||
try {
|
||||
final corePalette = await DynamicColorPlugin.getCorePalette();
|
||||
if (corePalette != null) {
|
||||
final lightScheme =
|
||||
corePaletteToFlutterColorScheme(corePalette, isLight: true);
|
||||
final darkScheme =
|
||||
corePaletteToFlutterColorScheme(corePalette, isLight: false);
|
||||
updateM3eFromColorSchemes(light: lightScheme, dark: darkScheme);
|
||||
return;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
final accentColor = await DynamicColorPlugin.getAccentColor();
|
||||
if (accentColor != null) {
|
||||
final lightScheme = ColorScheme.fromSeed(
|
||||
seedColor: accentColor,
|
||||
brightness: Brightness.light,
|
||||
);
|
||||
final darkScheme = ColorScheme.fromSeed(
|
||||
seedColor: accentColor,
|
||||
brightness: Brightness.dark,
|
||||
);
|
||||
updateM3eFromColorSchemes(light: lightScheme, dark: darkScheme);
|
||||
return;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
updateM3eFromColorSchemes();
|
||||
}
|
||||
67
firka_common/lib/ui/theme/core/refilc.dart
Normal file
67
firka_common/lib/ui/theme/core/refilc.dart
Normal file
@@ -0,0 +1,67 @@
|
||||
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),
|
||||
),
|
||||
);
|
||||
@@ -1,14 +1,24 @@
|
||||
// ignore_for_file: deprecated_member_use
|
||||
import "package:dynamic_color/dynamic_color.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:material_color_utilities/material_color_utilities.dart";
|
||||
|
||||
part "core/butcher_vanity.dart";
|
||||
part "core/firka.dart";
|
||||
part "core/m3e.dart";
|
||||
part "core/refilc.dart";
|
||||
|
||||
const Map<String, CoreTheme> coreThemes = {
|
||||
final Map<String, CoreTheme> coreThemes = {
|
||||
"firka": firkaCore,
|
||||
"m3e": m3eCore,
|
||||
"refilc": refilcCore,
|
||||
"butcher_vanity": butcherVanityCore,
|
||||
};
|
||||
|
||||
/// App chrome colors (everything except grade colors)
|
||||
class CoreThemeColors {
|
||||
final Color background;
|
||||
final List<Color>? backgroundGradient;
|
||||
final Color backgroundAmoled;
|
||||
final Color background0p;
|
||||
final Color success;
|
||||
@@ -47,6 +57,7 @@ class CoreThemeColors {
|
||||
|
||||
const CoreThemeColors({
|
||||
required this.background,
|
||||
this.backgroundGradient,
|
||||
required this.backgroundAmoled,
|
||||
required this.background0p,
|
||||
required this.success,
|
||||
|
||||
25
firka_common/lib/ui/theme/grade/rainbow.dart
Normal file
25
firka_common/lib/ui/theme/grade/rainbow.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
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);
|
||||
@@ -1,6 +1,7 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
part "grade/firka.dart";
|
||||
part "grade/rainbow.dart";
|
||||
|
||||
class GradeThemeColors {
|
||||
final Color grade5;
|
||||
@@ -32,8 +33,16 @@ class GradeTheme {
|
||||
GradeThemeColors forBrightness(bool isLight) => isLight ? light : dark;
|
||||
}
|
||||
|
||||
const Map<String, GradeTheme> gradeThemes = {
|
||||
final 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;
|
||||
|
||||
@@ -50,11 +50,21 @@ class FirkaFonts {
|
||||
|
||||
class FirkaColors {
|
||||
Color background;
|
||||
List<Color>? backgroundGradient;
|
||||
Color backgroundAmoled;
|
||||
Color background0p;
|
||||
Color success;
|
||||
int shadowBlur;
|
||||
|
||||
LinearGradient? get backgroundLinearGradient =>
|
||||
backgroundGradient != null && backgroundGradient!.length >= 2
|
||||
? LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: backgroundGradient!,
|
||||
)
|
||||
: null;
|
||||
|
||||
Color textPrimary;
|
||||
Color textSecondary;
|
||||
Color textTertiary;
|
||||
@@ -94,6 +104,7 @@ class FirkaColors {
|
||||
|
||||
FirkaColors({
|
||||
required this.background,
|
||||
this.backgroundGradient,
|
||||
required this.backgroundAmoled,
|
||||
required this.background0p,
|
||||
required this.success,
|
||||
@@ -269,6 +280,7 @@ final _defaultFonts = buildAppFonts();
|
||||
FirkaColors mergeColors(CoreThemeColors core, GradeThemeColors grades) {
|
||||
return FirkaColors(
|
||||
background: core.background,
|
||||
backgroundGradient: core.backgroundGradient,
|
||||
backgroundAmoled: core.backgroundAmoled,
|
||||
background0p: core.background0p,
|
||||
success: core.success,
|
||||
|
||||
264
firka_common/lib/ui/theme/theme_binary_format.dart
Normal file
264
firka_common/lib/ui/theme/theme_binary_format.dart
Normal file
@@ -0,0 +1,264 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firka_common/ui/theme/core_theme.dart';
|
||||
|
||||
/// The 16 customizable color slots of a Firka theme.
|
||||
enum ThemeColorSlot {
|
||||
accent,
|
||||
background,
|
||||
card,
|
||||
button,
|
||||
secondary,
|
||||
textPrimary,
|
||||
textSecondary,
|
||||
textTertiary,
|
||||
shadowColor,
|
||||
success,
|
||||
warningAccent,
|
||||
warningText,
|
||||
warningCard,
|
||||
errorAccent,
|
||||
errorText,
|
||||
errorCard,
|
||||
}
|
||||
|
||||
/// Decoded theme binary data.
|
||||
class ThemeBinaryData {
|
||||
/// Format version (e.g. 0).
|
||||
final int version;
|
||||
|
||||
/// Ordered list of colors stored as raw bytes.
|
||||
final List<Color> colors;
|
||||
|
||||
const ThemeBinaryData({
|
||||
required this.version,
|
||||
required this.colors,
|
||||
});
|
||||
|
||||
/// True if the payload contains both light (0..15) and dark (16..31) slots.
|
||||
bool get isFullTheme => colors.length >= 32;
|
||||
|
||||
/// Retrieves the color for [slot] in light mode, or null if out of range.
|
||||
Color? lightSlot(ThemeColorSlot slot) {
|
||||
final idx = slot.index;
|
||||
return idx < colors.length ? colors[idx] : null;
|
||||
}
|
||||
|
||||
/// Retrieves the color for [slot] in dark mode, or null if out of range.
|
||||
Color? darkSlot(ThemeColorSlot slot) {
|
||||
final idx = 16 + slot.index;
|
||||
return idx < colors.length ? colors[idx] : null;
|
||||
}
|
||||
|
||||
/// Extracts the full theme mapping for light and dark modes.
|
||||
({Map<ThemeColorSlot, Color> light, Map<ThemeColorSlot, Color> dark}) toThemeSlots() {
|
||||
final lightMap = <ThemeColorSlot, Color>{};
|
||||
final darkMap = <ThemeColorSlot, Color>{};
|
||||
|
||||
for (final slot in ThemeColorSlot.values) {
|
||||
final lColor = lightSlot(slot);
|
||||
if (lColor != null) lightMap[slot] = lColor;
|
||||
|
||||
final dColor = darkSlot(slot) ?? lColor;
|
||||
if (dColor != null) darkMap[slot] = dColor;
|
||||
}
|
||||
|
||||
return (light: lightMap, dark: darkMap);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'ThemeBinaryData(version: $version, colors: ${colors.length})';
|
||||
}
|
||||
|
||||
/// Binary encoder and decoder for Firka themes.
|
||||
///
|
||||
/// Format specification:
|
||||
/// 1. Header: Varint storing the format version (e.g. `0x00` for version 0).
|
||||
/// 2. Colors: Raw 32-bit ARGB bytes (4 bytes per color: Alpha, Red, Green, Blue).
|
||||
class ThemeBinaryFormat {
|
||||
/// Current binary format version.
|
||||
static const int currentVersion = 0;
|
||||
|
||||
/// Encodes [value] into a standard unsigned LEB128 varint.
|
||||
static void writeVarint(BytesBuilder builder, int value) {
|
||||
if (value < 0) {
|
||||
throw ArgumentError.value(value, 'value', 'Varint must be non-negative');
|
||||
}
|
||||
var v = value;
|
||||
while (v >= 0x80) {
|
||||
builder.addByte((v & 0x7F) | 0x80);
|
||||
v >>= 7;
|
||||
}
|
||||
builder.addByte(v & 0x7F);
|
||||
}
|
||||
|
||||
/// Reads a standard unsigned LEB128 varint from [bytes] starting at [offset].
|
||||
/// Returns a record of `(value, bytesRead)`.
|
||||
static (int value, int bytesRead) readVarint(Uint8List bytes, [int offset = 0]) {
|
||||
var result = 0;
|
||||
var shift = 0;
|
||||
var index = offset;
|
||||
|
||||
while (index < bytes.length) {
|
||||
final byte = bytes[index++];
|
||||
result |= (byte & 0x7F) << shift;
|
||||
if ((byte & 0x80) == 0) {
|
||||
return (result, index - offset);
|
||||
}
|
||||
shift += 7;
|
||||
if (shift >= 64) {
|
||||
throw const FormatException('Varint overflow');
|
||||
}
|
||||
}
|
||||
throw const FormatException('Unexpected end of buffer while reading varint');
|
||||
}
|
||||
|
||||
/// Encodes a list of [colors] into the binary theme format.
|
||||
///
|
||||
/// Prepends [version] as a varint (default 0), followed by 4 raw bytes per
|
||||
/// color in 32-bit ARGB order (Alpha, Red, Green, Blue).
|
||||
static Uint8List encode({
|
||||
required List<Color> colors,
|
||||
int version = currentVersion,
|
||||
}) {
|
||||
final builder = BytesBuilder(copy: false);
|
||||
|
||||
// 1. Version as varint
|
||||
writeVarint(builder, version);
|
||||
|
||||
// 2. Colors as raw bytes (4 bytes each: A, R, G, B)
|
||||
for (final color in colors) {
|
||||
final argb = color.toARGB32();
|
||||
builder.addByte((argb >> 24) & 0xFF);
|
||||
builder.addByte((argb >> 16) & 0xFF);
|
||||
builder.addByte((argb >> 8) & 0xFF);
|
||||
builder.addByte(argb & 0xFF);
|
||||
}
|
||||
|
||||
return builder.takeBytes();
|
||||
}
|
||||
|
||||
/// Decodes raw binary theme [bytes].
|
||||
///
|
||||
/// Reads the leading varint version and parses the subsequent raw bytes as
|
||||
/// 32-bit ARGB colors (4 bytes per color).
|
||||
static ThemeBinaryData decode(Uint8List bytes) {
|
||||
if (bytes.isEmpty) {
|
||||
throw const FormatException('Cannot decode empty theme bytes');
|
||||
}
|
||||
|
||||
// 1. Read version varint
|
||||
final (version, headerLength) = readVarint(bytes, 0);
|
||||
|
||||
final colorByteLength = bytes.length - headerLength;
|
||||
if (colorByteLength % 4 != 0) {
|
||||
throw FormatException(
|
||||
'Invalid color byte length ($colorByteLength). '
|
||||
'Color bytes must be a multiple of 4.',
|
||||
);
|
||||
}
|
||||
|
||||
final colorCount = colorByteLength ~/ 4;
|
||||
final colors = <Color>[];
|
||||
|
||||
for (var i = 0; i < colorCount; i++) {
|
||||
final offset = headerLength + (i * 4);
|
||||
final a = bytes[offset];
|
||||
final r = bytes[offset + 1];
|
||||
final g = bytes[offset + 2];
|
||||
final b = bytes[offset + 3];
|
||||
colors.add(Color.fromARGB(a, r, g, b));
|
||||
}
|
||||
|
||||
return ThemeBinaryData(version: version, colors: colors);
|
||||
}
|
||||
|
||||
/// Encodes a complete 32-color Firka theme (16 light slots + 16 dark slots).
|
||||
static Uint8List encodeFullTheme({
|
||||
required Map<ThemeColorSlot, Color> light,
|
||||
required Map<ThemeColorSlot, Color> dark,
|
||||
int version = currentVersion,
|
||||
}) {
|
||||
final colors = <Color>[];
|
||||
|
||||
// Light slots (0..15)
|
||||
for (final slot in ThemeColorSlot.values) {
|
||||
colors.add(light[slot] ?? Colors.transparent);
|
||||
}
|
||||
|
||||
// Dark slots (16..31)
|
||||
for (final slot in ThemeColorSlot.values) {
|
||||
colors.add(dark[slot] ?? light[slot] ?? Colors.transparent);
|
||||
}
|
||||
|
||||
return encode(colors: colors, version: version);
|
||||
}
|
||||
|
||||
/// Encodes a [CoreTheme] (both light and dark colors) into binary.
|
||||
static Uint8List encodeCoreTheme(
|
||||
CoreTheme theme, {
|
||||
int version = currentVersion,
|
||||
}) {
|
||||
Color getSlot(CoreThemeColors c, ThemeColorSlot slot) => switch (slot) {
|
||||
ThemeColorSlot.accent => c.accent,
|
||||
ThemeColorSlot.background => c.background,
|
||||
ThemeColorSlot.card => c.card,
|
||||
ThemeColorSlot.button => c.buttonSecondaryFill,
|
||||
ThemeColorSlot.secondary => c.secondary,
|
||||
ThemeColorSlot.textPrimary => c.textPrimary,
|
||||
ThemeColorSlot.textSecondary => c.textSecondary,
|
||||
ThemeColorSlot.textTertiary => c.textTertiary,
|
||||
ThemeColorSlot.shadowColor => c.shadowColor,
|
||||
ThemeColorSlot.success => c.success,
|
||||
ThemeColorSlot.warningAccent => c.warningAccent,
|
||||
ThemeColorSlot.warningText => c.warningText,
|
||||
ThemeColorSlot.warningCard => c.warningCard,
|
||||
ThemeColorSlot.errorAccent => c.errorAccent,
|
||||
ThemeColorSlot.errorText => c.errorText,
|
||||
ThemeColorSlot.errorCard => c.errorCard,
|
||||
};
|
||||
|
||||
final lightMap = {
|
||||
for (final slot in ThemeColorSlot.values) slot: getSlot(theme.light, slot),
|
||||
};
|
||||
final darkMap = {
|
||||
for (final slot in ThemeColorSlot.values) slot: getSlot(theme.dark, slot),
|
||||
};
|
||||
|
||||
return encodeFullTheme(light: lightMap, dark: darkMap, version: version);
|
||||
}
|
||||
|
||||
/// Encodes [bytes] to Base64 (URL-safe without padding by default).
|
||||
static String toBase64(Uint8List bytes, {bool urlSafe = true}) {
|
||||
final b64 = urlSafe ? base64UrlEncode(bytes) : base64Encode(bytes);
|
||||
return urlSafe ? b64.replaceAll('=', '') : b64;
|
||||
}
|
||||
|
||||
/// Decodes a Base64 or URL-safe Base64 string into binary theme bytes.
|
||||
static Uint8List fromBase64(String encoded) {
|
||||
var normalized = encoded.trim();
|
||||
final mod = normalized.length % 4;
|
||||
if (mod != 0) {
|
||||
normalized += '=' * (4 - mod);
|
||||
}
|
||||
return base64Url.decode(normalized);
|
||||
}
|
||||
|
||||
/// Convenience method: Encodes [colors] directly into a URL-safe Base64 string.
|
||||
static String encodeToBase64(
|
||||
List<Color> colors, {
|
||||
int version = currentVersion,
|
||||
bool urlSafe = true,
|
||||
}) {
|
||||
final bytes = encode(colors: colors, version: version);
|
||||
return toBase64(bytes, urlSafe: urlSafe);
|
||||
}
|
||||
|
||||
/// Convenience method: Decodes a URL-safe Base64 string into [ThemeBinaryData].
|
||||
static ThemeBinaryData decodeFromBase64(String encoded) {
|
||||
final bytes = fromBase64(encoded);
|
||||
return decode(bytes);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ dependencies:
|
||||
isar_community: 3.3.0
|
||||
isar_community_flutter_libs: 3.3.0
|
||||
build_runner: any
|
||||
dynamic_color: ^2.1.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
132
firka_common/test/theme_binary_format_test.dart
Normal file
132
firka_common/test/theme_binary_format_test.dart
Normal file
@@ -0,0 +1,132 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:firka_common/ui/theme/core_theme.dart';
|
||||
import 'package:firka_common/ui/theme/theme_binary_format.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('ThemeBinaryFormat varint tests', () {
|
||||
test('encodes and decodes 0 (version 0) as a single byte 0x00', () {
|
||||
final builder = BytesBuilder();
|
||||
ThemeBinaryFormat.writeVarint(builder, 0);
|
||||
final bytes = builder.takeBytes();
|
||||
|
||||
expect(bytes.length, 1);
|
||||
expect(bytes[0], 0x00);
|
||||
|
||||
final (value, bytesRead) = ThemeBinaryFormat.readVarint(bytes, 0);
|
||||
expect(value, 0);
|
||||
expect(bytesRead, 1);
|
||||
});
|
||||
|
||||
test('encodes and decodes multi-byte varints', () {
|
||||
for (final testVal in [1, 63, 127, 128, 255, 300, 16384, 2097151]) {
|
||||
final builder = BytesBuilder();
|
||||
ThemeBinaryFormat.writeVarint(builder, testVal);
|
||||
final bytes = builder.takeBytes();
|
||||
|
||||
final (decoded, bytesRead) = ThemeBinaryFormat.readVarint(bytes, 0);
|
||||
expect(decoded, testVal);
|
||||
expect(bytesRead, bytes.length);
|
||||
}
|
||||
});
|
||||
|
||||
test('throws on negative varint', () {
|
||||
final builder = BytesBuilder();
|
||||
expect(() => ThemeBinaryFormat.writeVarint(builder, -1), throwsArgumentError);
|
||||
});
|
||||
});
|
||||
|
||||
group('ThemeBinaryFormat color encoding', () {
|
||||
test('encodes empty list as only version varint', () {
|
||||
final bytes = ThemeBinaryFormat.encode(colors: []);
|
||||
expect(bytes, equals([0x00]));
|
||||
|
||||
final decoded = ThemeBinaryFormat.decode(bytes);
|
||||
expect(decoded.version, 0);
|
||||
expect(decoded.colors, isEmpty);
|
||||
});
|
||||
|
||||
test('stores colors as 4 raw ARGB bytes following version 0', () {
|
||||
const red = Color(0xFFFF0000);
|
||||
const semiGreen = Color(0x8000FF00);
|
||||
|
||||
final bytes = ThemeBinaryFormat.encode(colors: [red, semiGreen]);
|
||||
|
||||
expect(bytes[0], 0x00);
|
||||
expect(bytes.sublist(1, 5), equals([0xFF, 0xFF, 0x00, 0x00]));
|
||||
expect(bytes.sublist(5, 9), equals([0x80, 0x00, 0xFF, 0x00]));
|
||||
expect(bytes.length, 9);
|
||||
|
||||
final decoded = ThemeBinaryFormat.decode(bytes);
|
||||
expect(decoded.version, 0);
|
||||
expect(decoded.colors.length, 2);
|
||||
expect(decoded.colors[0], red);
|
||||
expect(decoded.colors[1], semiGreen);
|
||||
});
|
||||
|
||||
test('round-trips full theme (32 colors)', () {
|
||||
final lightMap = {
|
||||
for (final slot in ThemeColorSlot.values)
|
||||
slot: Color((0xFF000000 + slot.index * 0x0F0F0F) & 0xFFFFFFFF),
|
||||
};
|
||||
final darkMap = {
|
||||
for (final slot in ThemeColorSlot.values)
|
||||
slot: Color((0xFF111111 + slot.index * 0x0E0E0E) & 0xFFFFFFFF),
|
||||
};
|
||||
|
||||
final bytes = ThemeBinaryFormat.encodeFullTheme(
|
||||
light: lightMap,
|
||||
dark: darkMap,
|
||||
);
|
||||
|
||||
expect(bytes.length, 129);
|
||||
expect(bytes[0], 0x00);
|
||||
|
||||
final decoded = ThemeBinaryFormat.decode(bytes);
|
||||
expect(decoded.version, 0);
|
||||
expect(decoded.isFullTheme, isTrue);
|
||||
|
||||
final slots = decoded.toThemeSlots();
|
||||
for (final slot in ThemeColorSlot.values) {
|
||||
expect(slots.light[slot], lightMap[slot]);
|
||||
expect(slots.dark[slot], darkMap[slot]);
|
||||
}
|
||||
});
|
||||
|
||||
test('round-trips CoreTheme (firkaCore)', () {
|
||||
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore);
|
||||
expect(bytes.length, 129);
|
||||
|
||||
final decoded = ThemeBinaryFormat.decode(bytes);
|
||||
expect(decoded.version, 0);
|
||||
|
||||
final slots = decoded.toThemeSlots();
|
||||
expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent);
|
||||
expect(slots.light[ThemeColorSlot.background], firkaCore.light.background);
|
||||
expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent);
|
||||
expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background);
|
||||
});
|
||||
|
||||
test('throws on malformed binary data', () {
|
||||
expect(() => ThemeBinaryFormat.decode(Uint8List(0)), throwsFormatException);
|
||||
expect(
|
||||
() => ThemeBinaryFormat.decode(Uint8List.fromList([0x00, 0xFF, 0x00, 0x00])),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
|
||||
test('Base64 and URL-safe serialization', () {
|
||||
final colors = [const Color(0xFFA7DC22), const Color(0xFFFAFFF0)];
|
||||
final b64 = ThemeBinaryFormat.encodeToBase64(colors);
|
||||
|
||||
expect(b64.contains('/'), isFalse);
|
||||
expect(b64.contains('+'), isFalse);
|
||||
expect(b64.contains('='), isFalse);
|
||||
|
||||
final decoded = ThemeBinaryFormat.decodeFromBase64(b64);
|
||||
expect(decoded.version, 0);
|
||||
expect(decoded.colors, equals(colors));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -8,3 +8,6 @@ environment:
|
||||
|
||||
dependencies:
|
||||
intl: any
|
||||
|
||||
dev_dependencies:
|
||||
test: ^1.25.0
|
||||
|
||||
166
kreta_api/test/mock_kreta_server_test.dart
Normal file
166
kreta_api/test/mock_kreta_server_test.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
// Integration test that runs against a live mock_kreta_server instance
|
||||
// (git.firka.app/firka/mock_kreta_server) to catch drift between the wire
|
||||
// format it serves and the DTOs in this package. The server URL is provided
|
||||
// by CI via MOCK_KRETA_SERVER_URL; see .woodpecker.yml.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
final _serverUrl =
|
||||
Platform.environment['MOCK_KRETA_SERVER_URL'] ?? 'http://127.0.0.1:8090';
|
||||
|
||||
Future<String> _fetchLoginCode(HttpClient client) async {
|
||||
final req = await client.getUrl(Uri.parse('$_serverUrl/Account/Login'));
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(body);
|
||||
if (match == null) {
|
||||
fail('mock server login page did not contain a code: $body');
|
||||
}
|
||||
return match.group(1)!;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _postToken(
|
||||
HttpClient client,
|
||||
Map<String, String> form,
|
||||
) async {
|
||||
final req = await client.postUrl(Uri.parse('$_serverUrl/connect/token'));
|
||||
req.headers.contentType = ContentType(
|
||||
'application',
|
||||
'x-www-form-urlencoded',
|
||||
);
|
||||
req.write(
|
||||
form.entries
|
||||
.map(
|
||||
(e) =>
|
||||
'${Uri.encodeQueryComponent(e.key)}=${Uri.encodeQueryComponent(e.value)}',
|
||||
)
|
||||
.join('&'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
if (resp.statusCode != 200) {
|
||||
throw HttpException('token request failed (${resp.statusCode}): $body');
|
||||
}
|
||||
return jsonDecode(body) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<TokenGrantResponse> _authenticate(HttpClient client) async {
|
||||
final code = await _fetchLoginCode(client);
|
||||
final json = await _postToken(client, {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
});
|
||||
return TokenGrantResponse.fromJson(json);
|
||||
}
|
||||
|
||||
Future<dynamic> _getAuthed(
|
||||
HttpClient client,
|
||||
String path,
|
||||
String accessToken,
|
||||
) async {
|
||||
final req = await client.getUrl(Uri.parse('$_serverUrl$path'));
|
||||
req.headers.set('Authorization', 'Bearer $accessToken');
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
if (resp.statusCode != 200) {
|
||||
throw HttpException('$path failed (${resp.statusCode}): $body');
|
||||
}
|
||||
return jsonDecode(body);
|
||||
}
|
||||
|
||||
void main() {
|
||||
late HttpClient client;
|
||||
|
||||
setUp(() => client = HttpClient());
|
||||
tearDown(() => client.close(force: true));
|
||||
|
||||
group('mock_kreta_server', () {
|
||||
test('authorization_code grant returns a usable token', () async {
|
||||
final token = await _authenticate(client);
|
||||
|
||||
expect(token.accessToken, isNotEmpty);
|
||||
expect(token.refreshToken, isNotEmpty);
|
||||
expect(token.tokenType, 'Bearer');
|
||||
});
|
||||
|
||||
test('an authorization code can only be redeemed once', () async {
|
||||
final code = await _fetchLoginCode(client);
|
||||
await _postToken(client, {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
});
|
||||
|
||||
await expectLater(
|
||||
_postToken(client, {'grant_type': 'authorization_code', 'code': code}),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('refresh_token grant issues a new token and consumes the old one', () async {
|
||||
final first = await _authenticate(client);
|
||||
|
||||
final refreshed = TokenGrantResponse.fromJson(
|
||||
await _postToken(client, {
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': first.refreshToken,
|
||||
}),
|
||||
);
|
||||
expect(refreshed.accessToken, isNotEmpty);
|
||||
expect(refreshed.accessToken, isNot(first.accessToken));
|
||||
|
||||
await expectLater(
|
||||
_postToken(client, {
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': first.refreshToken,
|
||||
}),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('student profile matches the Student DTO contract', () async {
|
||||
final token = await _authenticate(client);
|
||||
final json = await _getAuthed(
|
||||
client,
|
||||
Uri.parse(KretaEndpoints.getStudent('dummy')).path,
|
||||
token.accessToken,
|
||||
);
|
||||
|
||||
final student = Student.fromJson(json as Map<String, dynamic>);
|
||||
expect(student.name, isNotEmpty);
|
||||
expect(student.uid, isNotEmpty);
|
||||
expect(student.instituteCode, isNotEmpty);
|
||||
});
|
||||
|
||||
test('class groups match the ClassGroup DTO contract', () async {
|
||||
final token = await _authenticate(client);
|
||||
final json = await _getAuthed(
|
||||
client,
|
||||
Uri.parse(KretaEndpoints.getClassGroups('dummy')).path,
|
||||
token.accessToken,
|
||||
);
|
||||
|
||||
final list = (json as List)
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map(ClassGroup.fromJson)
|
||||
.toList();
|
||||
expect(list, isNotEmpty);
|
||||
for (final group in list) {
|
||||
expect(group.uid, isNotEmpty);
|
||||
expect(group.name, isNotEmpty);
|
||||
}
|
||||
});
|
||||
|
||||
test('protected endpoints reject requests without a token', () async {
|
||||
final req = await client.getUrl(
|
||||
Uri.parse('$_serverUrl/ellenorzo/v3/sajat/TanuloAdatlap'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
await resp.drain();
|
||||
expect(resp.statusCode, HttpStatus.unauthorized);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user