Compare commits
286 Commits
fix/live-a
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e757d9afd | ||
|
|
fff41d95d7 | ||
|
|
93b1d78fd2 | ||
|
|
717b4b27aa | ||
| a097c80516 | |||
| ec2b22c825 | |||
| d8ee1d8073 | |||
| 280b5142a5 | |||
| 31b9d86ed9 | |||
| ff297bf4b8 | |||
| 0f0b7c0c8b | |||
| 394b7bfd70 | |||
| 95b6af52c2 | |||
| fcf6a08e79 | |||
| 705d1fee4e | |||
| 6290c27a7e | |||
| a3a036440a | |||
| 062f1afe67 | |||
| 6d30767cb0 | |||
| 0e3c3c421f | |||
| b6d1b221b8 | |||
| e79c489de6 | |||
| c9a034c0f8 | |||
| 4dbe0b71e6 | |||
| eddfe52a51 | |||
| 1f2f7e9d4e | |||
|
|
5766eb6675 | ||
| b28bebcce1 | |||
|
|
8fb5d5c89b | ||
|
|
f22ab629bc | ||
|
|
09ac4b7f61 | ||
|
|
5320625d83 | ||
|
|
eccdf90fd8 | ||
|
|
b4ccd52321 | ||
|
|
4658366fd4 | ||
|
|
aa77e25fe4 | ||
|
|
8984f8a915 | ||
|
|
4c28999d10 | ||
|
|
50274575f6 | ||
|
|
fb8fad142a | ||
|
|
2dccb59f7f | ||
|
|
7c9ade35f0 | ||
|
|
ca9e6c3efa | ||
| a4af924653 | |||
| 8bc52aadcb | |||
| 6101513a43 | |||
| 16e7ca49ca | |||
| dd05320346 | |||
| 1f9512d03a | |||
| d36992c7bc | |||
| fd57184f99 | |||
| fa31c0d7a3 | |||
| 47e9047873 | |||
| 7319878cb8 | |||
| 3dc902b4cf | |||
| 71e1250932 | |||
| 39651c2ab7 | |||
| bffd1d66d9 | |||
| 3480fb2ac0 | |||
| f5a16da72d | |||
| 04a441cd08 | |||
| 80856d1e8d | |||
| 9a74bd5178 | |||
| 05c1cce469 | |||
| 0b1313d0be | |||
| 5a79c48e6d | |||
| 7bf9351b22 | |||
|
|
368ad86f71 | ||
|
|
46a508cc33 | ||
|
|
2923d868e6 | ||
|
|
7f33b50822 | ||
|
|
54d792eb01 | ||
|
|
c8b402118c | ||
|
|
c0f3e61b90 | ||
|
|
9aaf43892f | ||
|
|
a64a7f7509 | ||
|
|
1225e6763f | ||
|
|
b159530de9 | ||
|
|
5fb1f6cc30 | ||
|
|
670968247a | ||
| 5847301e70 | |||
|
|
6342f16d80 | ||
|
|
7167bf8da4 | ||
|
|
7747e5d90b | ||
|
|
49ec23c18e | ||
| 37e7cac61e | |||
| d64ea1d2d6 | |||
| d010544ff2 | |||
| 20d0cf9736 | |||
| c8c299ba36 | |||
| f3414499a7 | |||
| 4b1d113918 | |||
| 0e965a87b9 | |||
| ead4dcd7b6 | |||
| 155d42d4d9 | |||
| caa4db3254 | |||
| 4e64dd9959 | |||
| 07f6a5c562 | |||
| f74ddb4c88 | |||
| 97b06044a4 | |||
| 2311556309 | |||
| 7a2bfb2cd8 | |||
| 39f683a0bf | |||
| 3576a3ab1e | |||
| 04af2c0402 | |||
| 70ff3ae8b9 | |||
| 5a42884d20 | |||
| 3fb0fd55de | |||
| 4c06daf02f | |||
| 3d07b2b2ce | |||
| 9a45c5c456 | |||
|
|
858d558cc3 | ||
|
|
76f345cd6b | ||
|
|
e211d64ffb | ||
|
|
c67ce7472a | ||
|
|
2b9ac14d6e | ||
|
|
eea10a4878 | ||
|
|
1ef6ae6e87 | ||
|
|
141431f378 | ||
|
|
f0114e3976 | ||
|
|
414a1ad254 | ||
|
|
d858c38bb1 | ||
|
|
87e3331428 | ||
|
|
1d912abc7d | ||
| 3a2cdfce05 | |||
| c5ba318c3b | |||
| fe9a2b36f1 | |||
| 80b05c1500 | |||
| 2ed6a04bf5 | |||
| 2d5ff89cad | |||
| 16b11564cc | |||
| 1ca975f0bd | |||
| 7985a11f99 | |||
| 2cf95375cb | |||
| 163b3a3135 | |||
| e839b8fa70 | |||
| c6378c9d46 | |||
| 51456b3b6e | |||
|
|
28f8f1d6f8 | ||
| d51c9d6411 | |||
| 4ef2f479d6 | |||
| d81d261c52 | |||
| 5baec2e65f | |||
| 48ea97ecef | |||
|
|
1154997531 | ||
|
|
dde05ce1db | ||
| 99ab6c07f7 | |||
|
|
40c6b83627 | ||
|
|
f4f6ddac72 | ||
|
|
938f2a56c6 | ||
|
|
e1b571afa0 | ||
|
|
729c281f1e | ||
|
|
a61a41e677 | ||
|
|
e8f1f18725 | ||
|
|
613b66bc22 | ||
|
|
1807d96895 | ||
|
|
e06d2168c0 | ||
|
|
91603923bc | ||
|
|
67e9ded2ed | ||
|
|
e9aaa26e26 | ||
|
|
56f15a681c | ||
|
|
178ebf7271 | ||
|
|
70c1397262 | ||
|
|
a334901f84 | ||
|
|
ddba6ad888 | ||
|
|
780aaee1dd | ||
|
|
09c408a6be | ||
|
|
7847878551 | ||
|
|
09ef386eab | ||
|
|
c19dd2f7eb | ||
|
|
39d4f49e99 | ||
|
|
bbdbf406d4 | ||
|
|
b17509f9db | ||
|
|
9ec164daac | ||
|
|
08f691d559 | ||
|
|
ad9e2c6676 | ||
|
|
55dbf12a2f | ||
|
|
4fc13efc52 | ||
|
|
5f16128bb0 | ||
|
|
4c8d73aa06 | ||
|
|
e4629d8489 | ||
|
|
f806dd8143 | ||
|
|
f653dc9fb4 | ||
|
|
06249bfc3d | ||
|
|
607f49bafc | ||
|
|
251e8de446 | ||
|
|
21845f89a8 | ||
|
|
25b1d06c06 | ||
|
|
dd20aa6138 | ||
|
|
9aa84c6fa1 | ||
|
|
6c75acad66 | ||
|
|
6311cafd51 | ||
|
|
1de32a35a4 | ||
|
|
f8a69a7561 | ||
|
|
f73c1127e7 | ||
|
|
a369e4ab14 | ||
|
|
8b04b77327 | ||
|
|
d56db4fe3a | ||
|
|
e7c0a95638 | ||
|
|
fa66d9af14 | ||
|
|
90c334d859 | ||
|
|
cc9ebcf6b0 | ||
|
|
ac914aa02e | ||
|
|
061f803f93 | ||
|
|
57c5e17b1c | ||
|
|
fa6f5390b1 | ||
|
|
21ff8f082f | ||
|
|
3b09d072f0 | ||
|
|
84f8e75694 | ||
|
|
1a05cce49b | ||
|
|
e732168a1b | ||
|
|
68035140b9 | ||
|
|
e004b7ee35 | ||
|
|
34718ed8ae | ||
|
|
03a5b5e767 | ||
|
|
d30dc67626 | ||
|
|
d0a517ae1e | ||
| 32a6452c1b | |||
| 579bf6bcad | |||
| 4ecf0d1a3f | |||
| 0675a5109a | |||
| bfb06d3e5f | |||
| 71b4b6aec7 | |||
| be6d28cfe3 | |||
| 8cfca13d1a | |||
| 632bb81408 | |||
|
|
f953dbd49f | ||
|
|
01e7e559ba | ||
| b6bfef7715 | |||
| bf75f72bcd | |||
|
|
b0cb020d76 | ||
|
|
4239ffa00c | ||
|
|
427b6f8086 | ||
|
|
fbd2351073 | ||
|
|
150e90d19b | ||
|
|
a6cf8b13c6 | ||
|
|
d8ae8471ab | ||
|
|
0e65f8e68c | ||
|
|
3912ad593b | ||
|
|
1f6eaaeccc | ||
| 40f188c2e2 | |||
| 0aae3801b7 | |||
| 26902b7616 | |||
| ffaf2c77e0 | |||
| 23f7f7cd48 | |||
| c2879766eb | |||
| 01cc08d5f3 | |||
| c386e1194b | |||
| 67ed4e03eb | |||
| c7d1f80e79 | |||
| 7531e58114 | |||
| c1e329cb5a | |||
| dad52bf20e | |||
| 5fb6d03d9c | |||
| 1ef757d10f | |||
| 444abb83c2 | |||
| e835dcf6b1 | |||
| e61a19fbbf | |||
| a937b854cd | |||
| 6d8f17ac00 | |||
| 78dd4239cc | |||
| 39c5ca357e | |||
| 8249dbf03e | |||
| c4e30ee4a6 | |||
| 1291d20e55 | |||
| fb8d57c0ee | |||
| e79de0326c | |||
| de335af3c1 | |||
| 4be0bcd813 | |||
|
|
b3f46d8e84 | ||
|
|
e97246ee55 | ||
|
|
159fb73919 | ||
| 7c35a5675c | |||
| 45adddb7f7 | |||
|
|
4aad2bb292 | ||
|
|
4c9eca217e | ||
|
|
ec6700e1cb | ||
|
|
b55595108f | ||
|
|
8b3ab4a3a9 | ||
|
|
046b7926c4 | ||
|
|
5626466107 | ||
|
|
6c674bd596 | ||
|
|
9465a2b2a7 | ||
| 484d8cf4cb | |||
| 863f9c8077 | |||
| a8983074dd |
4
.gitignore
vendored
@@ -100,8 +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
|
||||
|
||||
9
.gitmodules
vendored
@@ -1,9 +1,8 @@
|
||||
[submodule "firka/lib/l10n"]
|
||||
path = firka/lib/l10n
|
||||
url = https://github.com/QwIT-Development/firka-localization
|
||||
[submodule "firka/android/app/src/main/java/org/brotli"]
|
||||
path = firka/android/app/src/main/java/org/brotli
|
||||
url = https://git.firka.app/firka/org_brotli
|
||||
url = https://git.firka.app/firka/firka-localization
|
||||
branch = weblate
|
||||
[submodule "firka_wear/lib/l10n"]
|
||||
path = firka_wear/lib/l10n
|
||||
url = https://github.com/qwit-development/firka-localization
|
||||
url = https://git.firka.app/firka/firka-localization
|
||||
branch = weblate
|
||||
|
||||
213
.woodpecker.yml
Normal file
@@ -0,0 +1,213 @@
|
||||
when:
|
||||
- event: [push, pull_request]
|
||||
- event: manual
|
||||
|
||||
steps:
|
||||
- name: submodules
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- git submodule update --init --recursive
|
||||
|
||||
- name: secrets
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
environment:
|
||||
UPLOAD_KEYSTORE_B64:
|
||||
from_secret: upload_keystore_b64
|
||||
KEYSTORE_PROPERTIES_B64:
|
||||
from_secret: keystore_properties_b64
|
||||
commands:
|
||||
- echo "$UPLOAD_KEYSTORE_B64" | base64 -d > secrets/upload-keystore.jks
|
||||
- echo "$KEYSTORE_PROPERTIES_B64" | base64 -d > secrets/keystore.properties
|
||||
|
||||
# Each step runs in a fresh container from the builder image -- only the
|
||||
# workspace volume is shared between them. Pointing PUB_CACHE at a
|
||||
# workspace-local dir (instead of the image's default /root/.pub-cache)
|
||||
# is what lets `flutter pub get`'s downloads survive into later steps.
|
||||
- name: dependencies
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- flutter pub get
|
||||
|
||||
- name: codegen
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- dart run scripts/codegen.dart
|
||||
|
||||
- name: 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, staging]
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- '[ -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, staging]
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- '[ -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, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/bundle/release/app-release.aab
|
||||
file_name: app-release.aab
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-arm64-v8a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-arm64-v8a-debug.apk
|
||||
file_name: app-arm64-v8a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-armeabi-v7a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-armeabi-v7a-debug.apk
|
||||
file_name: app-armeabi-v7a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-x86_64
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: [main, staging]
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-x86_64-debug.apk
|
||||
file_name: app-x86_64-debug.apk
|
||||
update: 'true'
|
||||
|
||||
@@ -1,35 +1,19 @@
|
||||
# Flutter telepítése
|
||||
|
||||
A firka androidra való lebuildeléséhez kötelező a saját Flutter fork használata, illetve minden más fajta --release buildhez is.
|
||||
|
||||
A Flutter telepítéséhez a dokumentáció [itt](https://docs.flutter.dev/get-started/install) található.
|
||||
|
||||
A Flutter zip letöltése helyett a custom engine-t cloneold le ([https://git.firka.app/firka/flutter/](https://git.firka.app/firka/flutter/))
|
||||
|
||||
# Brotli
|
||||
|
||||
A firka brotlival compresseli a libflutter-t buildelés közben ezért szükséges a projekt
|
||||
buildeléséhez hogy a brotli a PATH-ben legyen
|
||||
|
||||
## Windows
|
||||
- Töltsd le a `brotli-x64-windows-static.zip`-et a [google/brotli github repoból](https://github.com/google/brotli/releases/latest)
|
||||
- Csomagold ki valahol (pl. C:\Users\\<username>\dev\brotli)
|
||||
- Add hozzá a mappát ahova kicsomagoltad (C:\Users\\<username>\dev\brotli) a PATH-hez
|
||||
- Ne felejtsd el újraindítani az IDE-det illetve parancssorodat utánna hogy frissüljön a PATH
|
||||
|
||||
## Linux/MacOS
|
||||
Telepítsd fel a brotli packaget a distro-d package managerével
|
||||
A projekt jelenleg a 3.41.2-es Flutter SDK-t használja.
|
||||
|
||||
# Keystore
|
||||
|
||||
[Secrets dokumentáció](secrets/README.md)
|
||||
|
||||
# Flutter l10n
|
||||
# Fileok generálása
|
||||
|
||||
Flutter l10n fileok generálása
|
||||
Flutter l10n és egyéb fileok generálása
|
||||
|
||||
```shell
|
||||
Flutter gen-l10n --template-arb-file app_hu.arb
|
||||
$ cd firka # vagy firka_wear
|
||||
$ dart run scripts/codegen.dart
|
||||
```
|
||||
|
||||
# Android debug build
|
||||
@@ -42,20 +26,10 @@ $ Flutter build apk --debug --target-platform android-arm,android-arm64,android-
|
||||
|
||||
# Android release build
|
||||
|
||||
A release buildhez közelező egy keystore használata, illetve a saját Flutter engineünk használata.
|
||||
A release buildhez közelező egy keystore használata.
|
||||
|
||||
## Custom Flutter engine setupolása
|
||||
## Release appbundle buildelése (firka és firka_wear)
|
||||
|
||||
```shell
|
||||
$ git clone https://git.firka.app/firka/flutter
|
||||
$ cd flutter
|
||||
$ . dev/tools/envsetup.sh
|
||||
$ gclient sync -D
|
||||
$ ./dev/tools/build_release.sh
|
||||
```
|
||||
|
||||
## Release apk buildelése
|
||||
|
||||
```shell
|
||||
$ ./tools/linux/build_apk.sh main
|
||||
$ ./build.sh
|
||||
```
|
||||
35
CONTRIBUTING_de.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Flutter installieren
|
||||
|
||||
Die Dokumentation zur Installation von Flutter findest du [hier](https://docs.flutter.dev/get-started/install).
|
||||
Das Projekt verwendet derzeit das Flutter SDK 3.41.2.
|
||||
|
||||
# Keystore
|
||||
|
||||
[Dokumentation zu Secrets](secrets/README.md)
|
||||
|
||||
# Dateien generieren
|
||||
|
||||
Flutter-L10N-Dateien und andere Dateien generieren
|
||||
|
||||
```shell
|
||||
$ cd firka # oder firka_wear
|
||||
$ dart run scripts/codegen.dart
|
||||
```
|
||||
|
||||
# Android-Debug-Build
|
||||
|
||||
Für den Dev-Build ist kein Keystore erforderlich
|
||||
```shell
|
||||
$ cd firka
|
||||
$ flutter build apk --debug --target-platform android-arm,android-arm64,android-x64
|
||||
```
|
||||
|
||||
# Android-Release-Build
|
||||
|
||||
Der Release-Build erfordert die Verwendung eines Keystores.
|
||||
|
||||
## Erstellen des Release-Appbundles (firka und firka_wear)
|
||||
|
||||
```shell
|
||||
$ ./build.sh
|
||||
```
|
||||
@@ -1,41 +1,24 @@
|
||||
# Installing flutter
|
||||
# Installing Flutter
|
||||
|
||||
To build firka you will have to use our custom Flutter fork,
|
||||
and to make a release build you will have to use our custom
|
||||
flutter engine.
|
||||
The documentation for installing flutter can be found [here](https://docs.flutter.dev/get-started/install).
|
||||
|
||||
Instead of downloading the regular flutter zip, clone it from ([https://git.firka.app/firka/flutter/](https://git.firka.app/firka/flutter/)).
|
||||
|
||||
# Brotli
|
||||
|
||||
Firka uses brotli to compress libflutter during the build process to make the app smaller,
|
||||
so building Firka requires you to have brotli in your path
|
||||
|
||||
## Windows
|
||||
- Download `brotli-x64-windows-static.zip` from [google/brotli](https://github.com/google/brotli/releases/latest)
|
||||
- Extract it to somewhere like C:\Users\\<username>\dev\brotli
|
||||
- Add the directory (ex. C:\Users\\<username>\dev\brotli) to your PATH
|
||||
- Don't forget to restart your IDE or terminal sessions for the PATH variable to update
|
||||
|
||||
## Linux/MacOS
|
||||
Install it using your distro's package manager
|
||||
Flutter installation documentation can be found [here](https://docs.flutter.dev/get-started/install).
|
||||
The project currently uses Flutter SDK 3.41.2.
|
||||
|
||||
# Keystore
|
||||
|
||||
[Secrets docs](secrets/README_en.md)
|
||||
[Secrets documentation](secrets/README.md)
|
||||
|
||||
# Flutter l10n
|
||||
# Generating files
|
||||
|
||||
Generating flutter l10n files
|
||||
Generating Flutter l10n and other files
|
||||
|
||||
```shell
|
||||
flutter gen-l10n --template-arb-file app_hu.arb
|
||||
$ cd firka # or firka_wear
|
||||
$ dart run scripts/codegen.dart
|
||||
```
|
||||
|
||||
# Android debug build
|
||||
|
||||
The dev build doesn't require using a custom keystore
|
||||
The dev build does not require using a keystore
|
||||
```shell
|
||||
$ cd firka
|
||||
$ flutter build apk --debug --target-platform android-arm,android-arm64,android-x64
|
||||
@@ -43,20 +26,10 @@ $ flutter build apk --debug --target-platform android-arm,android-arm64,android-
|
||||
|
||||
# Android release build
|
||||
|
||||
The release build requires using a custom keystore and our custom flutter fork
|
||||
The release build requires using a keystore.
|
||||
|
||||
## Setting up our flutter engine fork
|
||||
## Building the release appbundle (firka and firka_wear)
|
||||
|
||||
```shell
|
||||
$ git clone https://git.firka.app/firka/flutter
|
||||
$ cd flutter
|
||||
$ . dev/tools/envsetup.sh
|
||||
$ gclient sync -D
|
||||
$ ./dev/tools/build_release.sh
|
||||
$ ./build.sh
|
||||
```
|
||||
|
||||
## Building the release apk
|
||||
|
||||
```shell
|
||||
$ ./tools/linux/build_apk.sh main
|
||||
```
|
||||
167
Jenkinsfile
vendored
@@ -1,167 +0,0 @@
|
||||
pipeline {
|
||||
agent {
|
||||
label 'ubuntu'
|
||||
}
|
||||
environment {
|
||||
PATH = "/home/jenkins/development/flutter/bin:${env.PATH}"
|
||||
}
|
||||
stages {
|
||||
stage('Pre-build Cleanup') {
|
||||
steps {
|
||||
script {
|
||||
sh '''#!/bin/sh
|
||||
set -x
|
||||
fusermount -u secrets || true
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Decrypt main keys') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def userInput = input(
|
||||
id: 'signaturePassword',
|
||||
message: 'Please enter the signing key password:',
|
||||
parameters: [
|
||||
password(
|
||||
defaultValue: '',
|
||||
description: 'Enter the signing key password',
|
||||
name: 'password'
|
||||
)
|
||||
]
|
||||
)
|
||||
env.PASSWORD = userInput.toString()
|
||||
}
|
||||
sh '''#!/bin/sh
|
||||
echo \$PASSWORD | gocryptfs $HOME/android_secrets secrets/ -nonempty
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Clone submodules') {
|
||||
steps {
|
||||
script {
|
||||
sh 'git submodule update --init --recursive'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build firka') {
|
||||
steps {
|
||||
sh 'bash -c "./tools/linux/build_apk.sh ' + env.BRANCH_NAME + '"'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Rename Release APKs') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
sh '''#!/bin/sh
|
||||
set -e
|
||||
|
||||
APK_DIR="firka/build/app/outputs/flutter-apk"
|
||||
|
||||
# Find all release APKs and rename them
|
||||
for apk_file in $APK_DIR/app-*-release.apk; do
|
||||
if [ -f "$apk_file" ]; then
|
||||
# Extract ABI from filename (e.g., app-arm64-v8a-release.apk -> arm64-v8a)
|
||||
basename_file=$(basename "$apk_file")
|
||||
abi=$(echo "$basename_file" | sed 's/app-//; s/-release.apk//')
|
||||
|
||||
# Create new filename
|
||||
new_name="app.firka.naplo_${abi}.apk"
|
||||
new_path="$APK_DIR/$new_name"
|
||||
|
||||
echo "Renaming $apk_file to $new_path"
|
||||
mv "$apk_file" "$new_path"
|
||||
fi
|
||||
done
|
||||
|
||||
ls -la $APK_DIR/app.firka.naplo_*.apk || echo "APK files not found"
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Calculate Version Code') {
|
||||
steps {
|
||||
script {
|
||||
sh '''#!/bin/sh
|
||||
set -e
|
||||
cd firka
|
||||
|
||||
# Calculate version code based on git commits (same logic as build script)
|
||||
COMMIT_COUNT=$(git rev-list --count HEAD)
|
||||
BASE_BUILD_NUMBER=$((1300 + COMMIT_COUNT))
|
||||
|
||||
if [ "$BRANCH_NAME" = "main" ]; then
|
||||
# For main branch, highest version code is BASE + 3000 (x64 build)
|
||||
VERSION_CODE=$((BASE_BUILD_NUMBER + 3000))
|
||||
else
|
||||
# For debug builds, version code is BASE + 0
|
||||
VERSION_CODE=$BASE_BUILD_NUMBER
|
||||
fi
|
||||
|
||||
echo "Calculated version code: $VERSION_CODE"
|
||||
echo "$VERSION_CODE" > ../version_code.txt
|
||||
'''
|
||||
|
||||
env.VERSION_CODE = readFile('version_code.txt').trim()
|
||||
echo "Setting VERSION_CODE environment variable to: ${env.VERSION_CODE}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish debug artifacts') {
|
||||
when {
|
||||
not {
|
||||
branch 'main'
|
||||
}
|
||||
}
|
||||
steps {
|
||||
archiveArtifacts artifacts: 'firka/build/app/outputs/flutter-apk/app-debug.apk', fingerprint: true
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish release AABs artifacts') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
archiveArtifacts artifacts: 'firka/build/app/outputs/bundle/release/*.aab', fingerprint: true
|
||||
sh 'rm firka/build/app/outputs/bundle/release/*.aab'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish release APKs artifacts') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
archiveArtifacts artifacts: 'firka/build/app/outputs/flutter-apk/app.firka.naplo_*.apk', fingerprint: true
|
||||
sh 'rm firka/build/app/outputs/flutter-apk/app.firka.naplo_*.apk'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Post Cleanup') {
|
||||
steps {
|
||||
script {
|
||||
sh '''
|
||||
rm firka/build/app/outputs/bundle/release/*.aab || true
|
||||
rm firka/build/app/outputs/flutter-apk/app.firka.naplo_*.apk || true
|
||||
rm firka/build/app/outputs/flutter-apk/app-debug.apk || true
|
||||
rm version_code.txt || true
|
||||
git checkout -- firka/pubspec.yaml || true
|
||||
git checkout -- firka/lib/helpers/firka_bundle.dart || true
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
README.md
@@ -1,13 +1,49 @@
|
||||
# Firka Napló
|
||||
# <img src="https://git.firka.app/firka/readme-files/raw/branch/main/dave.png" height="40" /> Firka
|
||||
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) |
|
||||
|-----------------------------------|---------------------------------------|
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) | <sub>DE</sub> [Deutsch](README_de.md) |
|
||||
|-----------------------------------|---------------------------------------|---------------------------------------|
|
||||
|
||||
[](https://crowdin.com/project/firka)
|
||||
<a href="https://translate.firka.app/engage/firka-naplo/"><img src="https://translate.firka.app/widget/firka-naplo/firka-app/en/svg-badge.svg" alt="Fordítás állapota"></a>
|
||||
<a href="https://status.firka.app/"><img src="https://status.firka.app/api/badge/1/uptime/24?label=Üzemidő&suffix=%" alt="Üzemidő"></a>
|
||||
<a href="https://builds.firka.app/job/Firka%20Beta/"><img src="https://img.shields.io/jenkins/build?jobUrl=https%3A%2F%2Fbuilds.firka.app%2Fjob%2FFirka%2520Beta%2F&label=Build" alt="Build állapota"></a>
|
||||
|
||||
## A projektről
|
||||
### Azért kezdtünk neki ennek a projektnek, mert úgy véltük, hogy a hivatalos alkalmazás nem volt elég jó. A Firka egy teljesen nyílt forráskódú, közösség által karbantartott alternatíva, és ez még csak a kezdet. Minden verzióval gyorsabb, testreszabhatóbb és felhasználóbarátabb lesz.
|
||||
|
||||
Firka egy alternatív [megnevezetlen naplóra] egy kliens alkalmazás. Az alkalmazás célja
|
||||
egy modern, felhasználóbarát felület biztosítása a(z) [megnevezetlen napló] rendszerhez.
|
||||
<img src="https://git.firka.app/firka/readme-files/raw/branch/main/firka_features.png" width="100%" />
|
||||
|
||||
A [fejlesztői környezet beállítsa](CONTRIBUTING.md)
|
||||
<br />
|
||||
|
||||
## Mik egyáltalán az alkalmazás funkciói?
|
||||
### Lásd előre, mi vár rád
|
||||
|
||||
A főképernyő megmutatja a közelgő óráidat, hogy soha ne érjen meglepetés. Szűrj tantárgy, dolgozatok, vagy bármi más alapján, ami számodra fontos. Az alsó sáv teljesen testreszabható – tedd oda, amit használsz, és rejtsd el, amit nem.
|
||||
|
||||
|
||||
### Jegyek, a te feltételeid szerint
|
||||
|
||||
Nem vagy felkészülve a jegyeidre? Ez a beállítás elrejti őket, amíg egyesével meg nem nyitod őket, így kényelmes tempóban dolgozhatod fel minden kudarcodat.
|
||||
|
||||
|
||||
### Pontosan mennyire vagy rossz matekból?
|
||||
|
||||
A jegyek oldalon grafikon mutatja az összesített átlagodat, így végig követheted, ahogyan lassan süllyed a félév során. Minden tantárgyhoz külön grafikon is tartozik, ha pontosan tudni akarod melyik a tettes.
|
||||
|
||||
|
||||
### Szabj testre mindent
|
||||
|
||||
A beállítások képernyőn olyan lehetőségek is vannak, amelyekről nem is tudtad, hogy szükséged van rájuk. Állítsd be a csengő eltolását, hogy másodpercre pontosan tudd, mikor ér véget az óra.
|
||||
Balkezes mód is van, mert úgy tűnik, van, aki nem volt szerencsés az életben.
|
||||
|
||||
|
||||
## Mit támogattok?
|
||||
|
||||
Jelenleg **Androidot** támogatunk (Wear OS-es okosóra-kísérőalkalmazással).
|
||||
<br />
|
||||
Tervezzük a böngészős támogatást is!
|
||||
|
||||
## Contribution
|
||||
Az első lépéseket a [közreműködési útmutatóban](CONTRIBUTING_en.md) találod.
|
||||
|
||||
## Közösség
|
||||
|
||||
[Discord](https://discord.gg/xTspd3zzRZ)
|
||||
51
README_de.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# <img src="https://git.firka.app/firka/readme-files/raw/branch/main/dave.png" height="40" /> Firka
|
||||
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) | <sub>DE</sub> [Deutsch](README_de.md) |
|
||||
|-----------------------------------|---------------------------------------|---------------------------------------|
|
||||
|
||||
<a href="https://translate.firka.app/engage/firka-naplo/"><img src="https://translate.firka.app/widget/firka-naplo/firka-app/en/svg-badge.svg" alt="Translation status"></a>
|
||||
<a href="https://status.firka.app/"><img src="https://status.firka.app/api/badge/1/uptime/24?label=Uptime&suffix=%" alt="Uptime"></a>
|
||||
<a href="https://builds.firka.app/job/Firka%20Beta/"><img src="https://img.shields.io/jenkins/build?jobUrl=https%3A%2F%2Fbuilds.firka.app%2Fjob%2FFirka%2520Beta%2F&label=Build" alt="Build status"></a>
|
||||
|
||||
### Wir haben diese App entwickelt, weil die offizielle App viel zu wünschen übrig ließ. Firka ist eine vollständig open-source, von der Community gepflegte Alternative, und wir stehen erst am Anfang. Mit jedem Release wird sie schneller, anpassbarer und benutzerfreundlicher.
|
||||
|
||||
|
||||
|
||||
<img src="https://git.firka.app/firka/readme-files/raw/branch/main/firka_features.png" width="100%" />
|
||||
|
||||
<br />
|
||||
|
||||
## Was sind überhaupt die Funktionen der App?
|
||||
### Sieh, was ansteht
|
||||
|
||||
Der Startbildschirm zeigt deine anstehenden Lektionen an, damit du nie unvorbereitet bist. Filtere nach Fach, Prüfungen oder was auch immer dir gerade wichtig ist. Die untere Leiste ist vollständig anpassbar: Zeige an was du nutzt und verstecke was du nicht brauchst.
|
||||
|
||||
|
||||
### Noten, ganz nach deinen Vorstellungen
|
||||
|
||||
Emotional nicht bereit für deine eigenen Noten? Diese Einstellung hält sie verborgen, bis du jede einzelne antippst, damit du deine Misserfolge in einem angenehmen Tempo verarbeiten kannst.
|
||||
|
||||
|
||||
### Wie schlecht bist du eigentlich in Mathe?
|
||||
|
||||
Die Noten-Seite enthält ein Diagramm deines Gesamtdurchschnitts, sodass du beobachten kannst, wie er im Laufe des Semesters langsam sinkt. Jedes Fach hat zudem ein eigenes Diagramm, falls du genau wissen möchtest, welches dafür verantwortlich ist.
|
||||
|
||||
|
||||
### Alles anpassen
|
||||
|
||||
Der Einstellungsbildschirm bietet Optionen, von denen du nicht wusstest, dass du sie brauchst. Passe die Glockenverzögerung an, damit du auf die Sekunde genau weißt, wann der Unterricht endet. Es gibt auch einen Linkshänder-Modus, denn anscheinend benutzen manche Leute ihr Handy falsch.
|
||||
|
||||
|
||||
## Was wird unterstützt?
|
||||
|
||||
Derzeit unterstützen wir **Android** (mit einer Wear OS Smartwatch-Begleit-App).
|
||||
<br />
|
||||
Wir planen, auch deinen Browser zu unterstützen!
|
||||
|
||||
## Mitwirken
|
||||
Wir würden uns sehr über deine Hilfe freuen.
|
||||
Du kannst im [Leitfaden zum unterstützen](CONTRIBUTING_de.md) loslegen.
|
||||
|
||||
## Community
|
||||
|
||||
[Discord](https://discord.gg/xTspd3zzRZ)
|
||||
54
README_en.md
@@ -1,13 +1,51 @@
|
||||
# Firka
|
||||
# <img src="https://git.firka.app/firka/readme-files/raw/branch/main/dave.png" height="40" /> Firka
|
||||
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) |
|
||||
|-----------------------------------|---------------------------------------|
|
||||
| <sub>HU</sub> [Magyar](README.md) | <sub>EN</sub> [English](README_en.md) | <sub>DE</sub> [Deutsch](README_de.md) |
|
||||
|-----------------------------------|---------------------------------------|---------------------------------------|
|
||||
|
||||
[](https://crowdin.com/project/firka)
|
||||
<a href="https://translate.firka.app/engage/firka-naplo/"><img src="https://translate.firka.app/widget/firka-naplo/firka-app/en/svg-badge.svg" alt="Translation status"></a>
|
||||
<a href="https://status.firka.app/"><img src="https://status.firka.app/api/badge/1/uptime/24?label=Uptime&suffix=%" alt="Uptime"></a>
|
||||
<a href="https://builds.firka.app/job/Firka%20Beta/"><img src="https://img.shields.io/jenkins/build?jobUrl=https%3A%2F%2Fbuilds.firka.app%2Fjob%2FFirka%2520Beta%2F&label=Build" alt="Build status"></a>
|
||||
|
||||
## The project
|
||||
### We built this because the official app left a lot to be desired. Firka is a fully open source, community maintained alternative and we're just getting started. Faster, more customizable, and more user friendly with every release.
|
||||
|
||||
Firka is an alternative client for [an application to be named]. The app's goal is to be a modern
|
||||
user friendly app for the [to be named] system.
|
||||
|
||||
[Contribution guide](CONTRIBUTING_en.md)
|
||||
|
||||
<img src="https://git.firka.app/firka/readme-files/raw/branch/main/firka_features.png" width="100%" />
|
||||
|
||||
<br />
|
||||
|
||||
## What even are the app's features?
|
||||
### See what's coming
|
||||
|
||||
The home screen shows your upcoming lessons so you're never caught off guard. Filter by subject, exams, or whatever you actually care about. The bottom bar is fully customizable, put what you use, hide what you don't.
|
||||
|
||||
|
||||
### Grades, on your terms
|
||||
|
||||
Emotionally unprepared for your own grades? This setting keeps them hidden until you tap each one open, so you can process your failures at a comfortable pace.
|
||||
|
||||
|
||||
### How bad are you at maths, exactly?
|
||||
|
||||
The grades page has a graph of your overall average, so you can watch it slowly decline over the semester. Each subject also gets its own graph, in case you wanted to know exactly which one is responsible.
|
||||
|
||||
|
||||
### Customize everything
|
||||
|
||||
The settings screen has options you didn't know you needed. Adjust the bell offset so you know exactly when class ends down to the second. Left-handed mode exists too, because apparently some people use their phones wrong.
|
||||
|
||||
|
||||
## What do you support?
|
||||
|
||||
Currently, we support **Android** (with a Wear OS smartwatch companion app).
|
||||
<br />
|
||||
We're planning on supporting your browser also!
|
||||
|
||||
## Contribution
|
||||
We would really appriciate your help.
|
||||
You can get started at the [contribution guide](CONTRIBUTING_en.md).
|
||||
|
||||
## Community
|
||||
|
||||
[Discord](https://discord.gg/xTspd3zzRZ)
|
||||
52
build.ps1
Normal file
@@ -0,0 +1,52 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$ROOT = $PSScriptRoot
|
||||
$SHA = (git -C $ROOT rev-parse --short HEAD)
|
||||
$COMMIT_COUNT = [int](git -C $ROOT rev-list --count HEAD)
|
||||
|
||||
function Build-App {
|
||||
param([string]$App)
|
||||
|
||||
$pubspec = Join-Path $ROOT $App "pubspec.yaml"
|
||||
if (-not (Test-Path $pubspec)) {
|
||||
Write-Error "Not found: $pubspec"
|
||||
}
|
||||
|
||||
$versionLine = Get-Content $pubspec | Select-String -Pattern '^\s*version:\s*' | Select-Object -First 1
|
||||
if (-not $versionLine) {
|
||||
Write-Error "No version line in $pubspec"
|
||||
}
|
||||
$line = $versionLine.Line
|
||||
if ($line -match '^\s*version:\s*([^+\s]+)') {
|
||||
$baseVersion = $Matches[1].Trim()
|
||||
} else {
|
||||
Write-Error "Could not parse version from: $line"
|
||||
}
|
||||
|
||||
$buildName = "${baseVersion}-${SHA}"
|
||||
$versionCode = 2000 + $COMMIT_COUNT
|
||||
if ($App -eq "firka_wear") {
|
||||
$versionCode += 1
|
||||
}
|
||||
|
||||
Write-Host "Building $App : version $buildName (version code: $versionCode)"
|
||||
Push-Location (Join-Path $ROOT $App)
|
||||
try {
|
||||
flutter pub get
|
||||
dart run scripts/codegen.dart
|
||||
flutter build appbundle --build-name="$buildName" --build-number="$versionCode" --verbose
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
$target = if ($args.Count -gt 0) { $args[0] } else { "all" }
|
||||
|
||||
switch ($target) {
|
||||
"firka" { Build-App firka }
|
||||
"firka_wear" { Build-App firka_wear }
|
||||
"all" { Build-App firka; Build-App firka_wear }
|
||||
default {
|
||||
Write-Error "Usage: $MyInvocation.MyCommand.Name [firka|firka_wear|all]"
|
||||
}
|
||||
}
|
||||
41
build.sh
Normal file
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
SHA=$(git -C "$ROOT" rev-parse --short HEAD)
|
||||
COMMIT_COUNT=$(git -C "$ROOT" rev-list --count HEAD)
|
||||
|
||||
build_app() {
|
||||
local APP="$1"
|
||||
local PUBSPEC="$ROOT/$APP/pubspec.yaml"
|
||||
if [[ ! -f "$PUBSPEC" ]]; then
|
||||
echo "Not found: $PUBSPEC" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local VERSION_LINE BASE_VERSION BUILD_NAME VERSION_CODE
|
||||
VERSION_LINE=$(grep -E '^\s*version:\s*' "$PUBSPEC" | head -1)
|
||||
BASE_VERSION=$(echo "$VERSION_LINE" | sed -E 's/^[[:space:]]*version:[[:space:]]*([^+]+).*/\1/' | tr -d ' ')
|
||||
BUILD_NAME="${BASE_VERSION}-${SHA}"
|
||||
|
||||
VERSION_CODE=$((2000 + COMMIT_COUNT))
|
||||
[[ "$APP" == "firka_wear" ]] && VERSION_CODE=$((VERSION_CODE + 1))
|
||||
|
||||
echo "Building $APP: version $BUILD_NAME (version code: $VERSION_CODE)"
|
||||
cd "$ROOT/$APP"
|
||||
|
||||
flutter pub get
|
||||
dart run scripts/codegen.dart
|
||||
|
||||
flutter build appbundle --build-name="$BUILD_NAME" --build-number="$VERSION_CODE" --verbose
|
||||
}
|
||||
|
||||
case "${1:-all}" in
|
||||
firka) build_app firka ;;
|
||||
firka_wear) build_app firka_wear ;;
|
||||
all) build_app firka && build_app firka_wear ;;
|
||||
*)
|
||||
echo "Usage: $0 [firka|firka_wear|all]" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
48
cache.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Cache
|
||||
|
||||
Entry:
|
||||
|
||||
név|típus|
|
||||
-|-|
|
||||
latestElement|idő|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
|
||||
Legutóbbi = Legutóbbi sikeres adatlekérdezés listájának legfrissebb elemének ideje.
|
||||
|
||||
## Timetable
|
||||
|
||||
TimetableDay entry.
|
||||
|
||||
Frissíteni|Korábbi|Múlt hét|Jelenlegi hét|Jövő hét|Későbbi|
|
||||
-|-|-|-|-|-|
|
||||
belépéskor?|✖️|✖️|✔️|✔️|✖️|
|
||||
kijelzéskor?|✖️|✖️|✖️|✖️|✔️|
|
||||
|
||||
Új mulasztáskor a mulasztás napját MINDIG frissíti.
|
||||
|
||||
## Értékelések/Tesztek/Faliújság/Feljegyzések/Házi feladatok
|
||||
|
||||
Frissíteni|Korábbi|Legutóbbi létrehozástól|
|
||||
-|-|-|
|
||||
belépéskor?|✖️|✔️|
|
||||
kijelzéskor?|✖️|✖️|
|
||||
|
||||
## Mulasztások
|
||||
|
||||
Összes
|
||||
|
||||
## Egyéb
|
||||
|
||||
Belépéskor
|
||||
|
||||
--------
|
||||
# IMPL
|
||||
|
||||
### GenericCache
|
||||
Entry:
|
||||
név|típus|
|
||||
-|-|
|
||||
userId|id|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
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:
|
||||
|
||||
@@ -1,32 +1,27 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services")
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.firka.naplo"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
compileSdk = 37
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
isCoreLibraryDesugaringEnabled = true
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_17.toString()
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "app.firka.naplo"
|
||||
// You can update the following values to match your application needs.
|
||||
@@ -36,14 +31,11 @@ android {
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (propsFile.exists()) {
|
||||
val props = Properties().apply { FileInputStream(propsFile).use { load(it) } }
|
||||
val store = File(secretsDir, props["storeFile"].toString())
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
storeFile = store
|
||||
@@ -57,7 +49,6 @@ android {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
applicationIdSuffix = ".debug"
|
||||
@@ -65,20 +56,30 @@ android {
|
||||
}
|
||||
release {
|
||||
val config = signingConfigs.findByName("release")
|
||||
|
||||
if (config != null) {
|
||||
signingConfig = config
|
||||
}
|
||||
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
proguardFiles("proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
}
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
configurations.all {
|
||||
resolutionStrategy {
|
||||
force("androidx.test.espresso:espresso-core:3.6.1")
|
||||
force("androidx.test.espresso:espresso-idling-resource:3.6.1")
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
implementation("androidx.glance:glance-appwidget:1.1.1")
|
||||
implementation("com.google.android.gms:play-services-wearable:18.1.0")
|
||||
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)
|
||||
val envFile = file("${project.projectDir}/../../.env")
|
||||
val envExampleFile = file("${project.projectDir}/../../.env.example")
|
||||
@@ -94,6 +95,25 @@ 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 = "../.."
|
||||
}
|
||||
29
firka/android/app/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
77
firka/android/app/proguard-rules.pro
vendored
@@ -1,2 +1,75 @@
|
||||
-keep class org.brotli.** { *; }
|
||||
-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.**
|
||||
@@ -4,6 +4,7 @@
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<application android:label="Firka Debug"
|
||||
<application android:name="app.firka.naplo.AppMain"
|
||||
android:label="Firka Debug"
|
||||
android:usesCleartextTraffic="true" />
|
||||
</manifest>
|
||||
</manifest>
|
||||
29
firka/android/app/src/debug/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo.debug"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<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" />
|
||||
@@ -11,7 +12,6 @@
|
||||
android:name=".AppMain"
|
||||
android:icon="@mipmap/launcher_icon">
|
||||
|
||||
|
||||
<service
|
||||
android:name=".WearSyncForegroundService"
|
||||
android:exported="false"
|
||||
@@ -670,6 +670,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"
|
||||
@@ -685,6 +686,13 @@
|
||||
<meta-data
|
||||
android:name="com.google.android.wearable.standalone"
|
||||
android:value="true" />
|
||||
|
||||
<!-- Small status-bar icon for FCM notification-payload messages that
|
||||
Android displays automatically (data-only wakeups instead go
|
||||
through LocalNotificationService, which sets its own icon). -->
|
||||
<meta-data
|
||||
android:name="com.google.firebase.messaging.default_notification_icon"
|
||||
android:resource="@drawable/ic_notification" />
|
||||
</application>
|
||||
|
||||
<!-- Required to query activities that can process text, see:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import androidx.glance.layout.padding
|
||||
import androidx.glance.layout.width
|
||||
import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextAlign
|
||||
import androidx.glance.text.TextStyle
|
||||
import app.firka.naplo.model.Colors
|
||||
import app.firka.naplo.glance.WidgetLesson
|
||||
@@ -31,6 +32,7 @@ fun LessonCard(
|
||||
colors: Colors,
|
||||
modifier: GlanceModifier = GlanceModifier,
|
||||
roomBadgeWidthDp: Float = 48f,
|
||||
subjectColumnWidthDp: Float = 226f,
|
||||
) {
|
||||
Box(modifier =
|
||||
modifier
|
||||
@@ -49,17 +51,21 @@ fun LessonCard(
|
||||
|
||||
|
||||
Box(modifier = GlanceModifier.padding(12.dp)) {
|
||||
Row {
|
||||
Row(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
val badgeStyle = TextStyle(
|
||||
color = ColorProvider(colors.textSecondary, colors.textSecondary),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Bold
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
val badgePadding = GlanceModifier.padding(8.dp, 4.dp)
|
||||
val lessonNumberBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(24.dp)
|
||||
val roomBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(roomBadgeWidthDp.dp)
|
||||
|
||||
Row(modifier = GlanceModifier.width(226.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(
|
||||
modifier = GlanceModifier.width(subjectColumnWidthDp.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (lesson.lessonNumber != null) {
|
||||
Box(
|
||||
modifier = lessonNumberBadgeModifier.background(bgColor),
|
||||
@@ -79,12 +85,14 @@ fun LessonCard(
|
||||
}
|
||||
// TODO: Add subject icons
|
||||
Text(
|
||||
lesson.name,
|
||||
text = lesson.name,
|
||||
style = TextStyle(
|
||||
color = ColorProvider(colors.textPrimary, colors.textPrimary),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Bold
|
||||
),
|
||||
maxLines = 1,
|
||||
modifier = GlanceModifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -98,15 +106,18 @@ fun LessonCard(
|
||||
),
|
||||
)
|
||||
Spacer(modifier = GlanceModifier.width(8.dp))
|
||||
val roomName = (lesson.roomName ?: "N/A").take(5)
|
||||
val roomName = lesson.roomName ?: "N/A"
|
||||
Box(
|
||||
modifier = roomBadgeModifier.background(colors.a15p),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
roomName,
|
||||
text = roomName,
|
||||
style = badgeStyle,
|
||||
modifier = GlanceModifier.padding(4.dp, 4.dp),
|
||||
maxLines = 1,
|
||||
modifier = GlanceModifier
|
||||
.fillMaxWidth()
|
||||
.padding(4.dp, 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -116,8 +120,10 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
val displayLessons = data.lessons.take(maxLessons)
|
||||
val lessonChunks = displayLessons.chunked(2)
|
||||
val showDate = maxLessons > 1
|
||||
val maxRoomNameLen = displayLessons.maxOfOrNull { (it.roomName ?: "N/A").take(5).length } ?: 0
|
||||
val roomBadgeWidthDp = if (maxRoomNameLen <= 3) 28f else 48f
|
||||
val roomBadgeWidthDp = 48f
|
||||
val minWidthForTimeAndChipDp = 8f + 40f + roomBadgeWidthDp
|
||||
val subjectColumnWidthDp = (size.width.value - 2 * paddingDp - 32f - minWidthForTimeAndChipDp)
|
||||
.coerceIn(80f, 226f)
|
||||
val dateSectionHeight = if (showDate) headerHeightDp + spacerDp else 0f
|
||||
val lessonListHeight = when (val n = displayLessons.size) {
|
||||
0 -> 0f
|
||||
@@ -148,7 +154,12 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
for (chunk in lessonChunks) {
|
||||
Column {
|
||||
for (lesson in chunk) {
|
||||
LessonCard(lesson, data.colors, roomBadgeWidthDp = roomBadgeWidthDp)
|
||||
LessonCard(
|
||||
lesson,
|
||||
data.colors,
|
||||
roomBadgeWidthDp = roomBadgeWidthDp,
|
||||
subjectColumnWidthDp = subjectColumnWidthDp,
|
||||
)
|
||||
Spacer(modifier = GlanceModifier.height(spacerDp.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 957 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 8.1 KiB |
@@ -1,5 +1,5 @@
|
||||
import com.android.build.gradle.BaseExtension
|
||||
import org.jetbrains.kotlin.gradle.plugin.extraProperties
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
@@ -13,34 +13,29 @@ rootProject.layout.buildDirectory.value(newBuildDir)
|
||||
|
||||
subprojects {
|
||||
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
|
||||
// fix for verifyReleaseResources
|
||||
if (project.name != "app") {
|
||||
project.evaluationDependsOn(":app")
|
||||
|
||||
// note(4831c0): taken from https://github.com/isar/isar/issues/1662
|
||||
// note(4831c0): and adapted to kotlin
|
||||
afterEvaluate {
|
||||
if (plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.library")) {
|
||||
val androidExtension = extensions.getByName("android") as BaseExtension
|
||||
androidExtension.apply {
|
||||
compileSdkVersion(36)
|
||||
buildToolsVersion = "36.1.0"
|
||||
}
|
||||
// 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")
|
||||
}
|
||||
if (hasProperty("android")) {
|
||||
val androidExtension = extensions.getByName("android") as BaseExtension
|
||||
androidExtension.apply {
|
||||
// Set namespace if it's not already set
|
||||
if (!extraProperties.has("namespace")) {
|
||||
extraProperties["namespace"] = project.group.toString()
|
||||
|
||||
afterEvaluate {
|
||||
if (plugins.hasPlugin("com.android.library")) {
|
||||
extensions.configure<LibraryExtension> {
|
||||
compileSdk = 37
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ===============================
|
||||
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
}
|
||||
|
||||
tasks.register<Delete>("clean") {
|
||||
delete(rootProject.layout.buildDirectory)
|
||||
}
|
||||
}
|
||||
@@ -11,3 +11,10 @@ org.gradle.parallel=true
|
||||
org.gradle.daemon=true
|
||||
# Better Kotlin incremental compilation (warm builds)
|
||||
kotlin.incremental.useClasspathSnapshot=true
|
||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
||||
android.builtInKotlin=false
|
||||
|
||||
android.newDsl=false
|
||||
|
||||
# Prevent AGP 9.0+ build failures due to relocated build directory ProGuard path mismatches
|
||||
android.proguard.failOnMissingFiles=false
|
||||
|
||||
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-all.zip
|
||||
|
||||
@@ -18,9 +18,12 @@ pluginManagement {
|
||||
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "8.11.1" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.1.0" apply false
|
||||
id("com.android.application") version "9.2.0" apply false
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services") version("4.4.4") apply false
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.android") version "2.3.10" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.3.10" apply false
|
||||
}
|
||||
|
||||
include(":app")
|
||||
|
||||
BIN
firka/assets/fonts/FiraCode-VariableFont_wght.ttf
Normal file
BIN
firka/assets/fonts/JustMeAgainDownHere.ttf
Normal file
BIN
firka/assets/fonts/Monoton-Regular.ttf
Normal file
BIN
firka/assets/fonts/PirataOne-Regular.ttf
Normal file
BIN
firka/assets/fonts/Vollkorn-VariableFont_wght.ttf
Normal file
BIN
firka/assets/icons/button/colorwheel.png
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
15
firka/assets/icons/dave.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
14
firka/assets/images/carousel/card1.svg
Normal file
|
After Width: | Height: | Size: 15 KiB |
6
firka/assets/images/carousel/card2.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg width="108" height="48" viewBox="0 0 108 48" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="108" height="48" rx="12" fill="#F3FBDE"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M30.6555 15.6657C30.968 15.3533 31.3919 15.1777 31.8338 15.1777C32.2758 15.1777 32.6996 15.3533 33.0122 15.6657L34.3338 16.9874C34.6463 17.2999 34.8218 17.7238 34.8218 18.1657C34.8218 18.6077 34.6463 19.0315 34.3338 19.344L33.0122 20.6657L29.3338 16.9874L30.6555 15.6657ZM28.1555 18.1657L23.9888 22.3324C23.6762 22.6449 23.5006 23.0687 23.5005 23.5107V24.8324C23.5005 25.2744 23.6761 25.6983 23.9886 26.0109C24.3012 26.3235 24.7251 26.499 25.1672 26.499H26.4888C26.9308 26.499 27.3547 26.3233 27.6672 26.0107L31.8338 21.844L28.1555 18.1657Z" fill="#A7DC22"/>
|
||||
<path d="M21.0005 25.666H20.1672C19.7251 25.666 19.3012 25.8416 18.9886 26.1542C18.6761 26.4667 18.5005 26.8907 18.5005 27.3327C18.5005 27.7747 18.6761 28.1986 18.9886 28.5112C19.3012 28.8238 19.7251 28.9993 20.1672 28.9993H31.8338C32.2758 28.9993 32.6998 29.1749 33.0123 29.4875C33.3249 29.8001 33.5005 30.224 33.5005 30.666C33.5005 31.108 33.3249 31.532 33.0123 31.8445C32.6998 32.1571 32.2758 32.3327 31.8338 32.3327H28.5005" stroke="#A7DC22" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M47.648 29.5V19.996H44.208V18.3H52.944V19.996H49.504V29.5H47.648ZM56.7006 29.692C55.922 29.692 55.2286 29.516 54.6206 29.164C54.0233 28.8013 53.5486 28.3053 53.1966 27.676C52.8553 27.0467 52.6846 26.3213 52.6846 25.5C52.6846 24.6787 52.8606 23.9533 53.2126 23.324C53.5646 22.6947 54.0446 22.204 54.6526 21.852C55.2713 21.4893 55.9753 21.308 56.7646 21.308C57.4793 21.308 58.1246 21.4947 58.7006 21.868C59.2766 22.2307 59.73 22.7587 60.0606 23.452C60.402 24.1453 60.5726 24.972 60.5726 25.932H54.2846L54.5246 25.708C54.5246 26.1987 54.6313 26.6253 54.8446 26.988C55.058 27.34 55.3406 27.612 55.6926 27.804C56.0446 27.996 56.434 28.092 56.8606 28.092C57.3513 28.092 57.7566 27.9853 58.0766 27.772C58.3966 27.548 58.6473 27.26 58.8286 26.908L60.4126 27.58C60.1886 28.0067 59.9006 28.38 59.5486 28.7C59.2073 29.02 58.7966 29.2653 58.3166 29.436C57.8473 29.6067 57.3086 29.692 56.7006 29.692ZM54.6366 24.78L54.3806 24.556H58.8926L58.6526 24.78C58.6526 24.3427 58.5566 23.9853 58.3646 23.708C58.1726 23.42 57.9273 23.2067 57.6286 23.068C57.3406 22.9187 57.0366 22.844 56.7166 22.844C56.3966 22.844 56.0766 22.9187 55.7566 23.068C55.4366 23.2067 55.17 23.42 54.9566 23.708C54.7433 23.9853 54.6366 24.3427 54.6366 24.78ZM55.5326 20.46L57.3886 18.3H59.4686L57.4046 20.46H55.5326ZM61.9764 29.5V21.5H63.6564L63.7364 22.572C63.9817 22.156 64.2964 21.8413 64.6804 21.628C65.0644 21.4147 65.5017 21.308 65.9924 21.308C66.6324 21.308 67.1764 21.452 67.6244 21.74C68.0724 22.028 68.3977 22.4653 68.6004 23.052C68.835 22.4867 69.1657 22.0547 69.5924 21.756C70.019 21.4573 70.5204 21.308 71.0964 21.308C72.0244 21.308 72.739 21.6067 73.2404 22.204C73.7417 22.7907 73.987 23.6973 73.9764 24.924V29.5H72.2004V25.404C72.2004 24.764 72.131 24.2733 71.9924 23.932C71.8537 23.58 71.667 23.3347 71.4324 23.196C71.1977 23.0573 70.9257 22.988 70.6164 22.988C70.0617 22.9773 69.6297 23.1747 69.3204 23.58C69.0217 23.9853 68.8724 24.5667 68.8724 25.324V29.5H67.0804V25.404C67.0804 24.764 67.011 24.2733 66.8724 23.932C66.7444 23.58 66.563 23.3347 66.3284 23.196C66.0937 23.0573 65.8217 22.988 65.5124 22.988C64.9577 22.9773 64.5257 23.1747 64.2164 23.58C63.9177 23.9853 63.7684 24.5667 63.7684 25.324V29.5H61.9764ZM80.6845 29.5L80.6045 27.996V25.388C80.6045 24.844 80.5458 24.3907 80.4285 24.028C80.3218 23.6547 80.1405 23.372 79.8845 23.18C79.6392 22.9773 79.3085 22.876 78.8925 22.876C78.5085 22.876 78.1725 22.956 77.8845 23.116C77.5965 23.276 77.3512 23.5267 77.1485 23.868L75.5805 23.292C75.7512 22.94 75.9752 22.6147 76.2525 22.316C76.5405 22.0067 76.8978 21.7613 77.3245 21.58C77.7618 21.3987 78.2845 21.308 78.8925 21.308C79.6712 21.308 80.3218 21.4627 80.8445 21.772C81.3672 22.0707 81.7512 22.5027 81.9965 23.068C82.2525 23.6333 82.3805 24.316 82.3805 25.116L82.3325 29.5H80.6845ZM78.3805 29.692C77.4205 29.692 76.6738 29.4787 76.1405 29.052C75.6178 28.6253 75.3565 28.0227 75.3565 27.244C75.3565 26.412 75.6338 25.7773 76.1885 25.34C76.7538 24.9027 77.5378 24.684 78.5405 24.684H80.6845V26.06H79.1165C78.4018 26.06 77.9005 26.1613 77.6125 26.364C77.3245 26.556 77.1805 26.8333 77.1805 27.196C77.1805 27.5053 77.3032 27.7507 77.5485 27.932C77.8045 28.1027 78.1565 28.188 78.6045 28.188C79.0098 28.188 79.3618 28.0973 79.6605 27.916C79.9592 27.7347 80.1885 27.4947 80.3485 27.196C80.5192 26.8973 80.6045 26.5613 80.6045 26.188H81.1325C81.1325 27.276 80.9138 28.1347 80.4765 28.764C80.0392 29.3827 79.3405 29.692 78.3805 29.692ZM77.5965 20.46L79.4525 18.3H81.5325L79.4685 20.46H77.5965ZM85.829 27.26L84.741 26.028L88.901 21.5H91.061L85.829 27.26ZM84.117 29.5V18.3H85.909V29.5H84.117ZM89.205 29.5L86.389 25.356L87.557 24.108L91.333 29.5H89.205Z" fill="#394C0A"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
5
firka/assets/images/carousel/card3.svg
Normal file
|
After Width: | Height: | Size: 17 KiB |
5
firka/assets/images/carousel/card4.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg width="108" height="48" viewBox="0 0 108 48" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="108" height="48" rx="12" fill="#F3FBDE"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M26.8026 15.9055C26.7524 15.8382 26.6891 15.7817 26.6166 15.7394C26.544 15.6971 26.4637 15.6699 26.3804 15.6593C26.2971 15.6487 26.2125 15.655 26.1317 15.6778C26.0509 15.7007 25.9755 15.7396 25.9101 15.7922C24.3129 17.0742 23.2594 18.9127 22.9609 20.9388C22.4141 20.5413 21.9344 20.0589 21.5401 19.5097C21.4866 19.4349 21.4173 19.3729 21.3371 19.328C21.2569 19.2831 21.1678 19.2564 21.0761 19.2499C20.9845 19.2434 20.8925 19.2572 20.8067 19.2902C20.721 19.3233 20.6436 19.3749 20.5801 19.4413C19.4795 20.5926 18.774 22.0644 18.5658 23.6435C18.3576 25.2225 18.6575 26.8268 19.4221 28.2241C20.1866 29.6213 21.3761 30.7388 22.8182 31.4148C24.2604 32.0908 25.8803 32.2902 27.4433 31.984C29.0063 31.6778 30.4312 30.882 31.5117 29.7118C32.5922 28.5416 33.2721 27.0579 33.453 25.4755C33.6338 23.893 33.3062 22.2941 32.5176 20.9104C31.729 19.5266 30.5204 18.4298 29.0667 17.7788C28.1732 17.3443 27.3967 16.7019 26.8026 15.9055ZM29.1251 25.8755C29.1248 26.3275 29.0264 26.7741 28.8367 27.1844C28.6471 27.5948 28.3707 27.959 28.0266 28.2522C27.6825 28.5453 27.2789 28.7603 26.8437 28.8823C26.4084 29.0044 25.9519 29.0305 25.5056 28.959C25.0592 28.8875 24.6337 28.7199 24.2584 28.468C23.8831 28.2161 23.5669 27.8857 23.3317 27.4998C23.0964 27.1138 22.9477 26.6814 22.8958 26.2323C22.8438 25.7833 22.8899 25.3283 23.0309 24.8988C23.5542 25.2863 24.1559 25.5738 24.8084 25.7322C24.986 24.5915 25.5528 23.5475 26.4126 22.7772C27.1634 22.8772 27.8524 23.2465 28.3513 23.8164C28.8503 24.3863 29.1252 25.118 29.1251 25.8755Z" fill="#A7DC22"/>
|
||||
<path d="M49.008 29.692C48.4213 29.692 47.8827 29.6227 47.392 29.484C46.912 29.3453 46.4853 29.1533 46.112 28.908C45.7493 28.6627 45.4453 28.3907 45.2 28.092C44.9653 27.7827 44.8 27.4627 44.704 27.132L46.528 26.572C46.6667 26.9667 46.9387 27.3133 47.344 27.612C47.7493 27.9107 48.2507 28.0653 48.848 28.076C49.5413 28.076 50.0907 27.932 50.496 27.644C50.9013 27.356 51.104 26.9773 51.104 26.508C51.104 26.0813 50.9333 25.7347 50.592 25.468C50.2507 25.1907 49.792 24.9773 49.216 24.828L47.84 24.476C47.3173 24.3373 46.8427 24.1347 46.416 23.868C46 23.6013 45.6693 23.2653 45.424 22.86C45.1893 22.4547 45.072 21.9747 45.072 21.42C45.072 20.3747 45.4133 19.564 46.096 18.988C46.7787 18.4013 47.7547 18.108 49.024 18.108C49.7387 18.108 50.3627 18.22 50.896 18.444C51.44 18.6573 51.888 18.956 52.24 19.34C52.592 19.7133 52.8533 20.14 53.024 20.62L51.232 21.196C51.072 20.7693 50.7947 20.4173 50.4 20.14C50.0053 19.8627 49.5147 19.724 48.928 19.724C48.32 19.724 47.84 19.868 47.488 20.156C47.1467 20.444 46.976 20.844 46.976 21.356C46.976 21.772 47.1093 22.0973 47.376 22.332C47.6533 22.556 48.0267 22.7267 48.496 22.844L49.872 23.18C50.8747 23.4253 51.6533 23.8467 52.208 24.444C52.7627 25.0413 53.04 25.7027 53.04 26.428C53.04 27.068 52.8853 27.6333 52.576 28.124C52.2667 28.6147 51.808 28.9987 51.2 29.276C50.6027 29.5533 49.872 29.692 49.008 29.692ZM57.9416 29.692C57.099 29.692 56.4536 29.484 56.0056 29.068C55.5683 28.6413 55.3496 28.0333 55.3496 27.244V19.004H57.1256V26.908C57.1256 27.2813 57.211 27.564 57.3816 27.756C57.563 27.948 57.8243 28.044 58.1656 28.044C58.2723 28.044 58.3896 28.0227 58.5176 27.98C58.6456 27.9373 58.7896 27.8573 58.9496 27.74L59.6056 29.1C59.3283 29.292 59.051 29.436 58.7736 29.532C58.4963 29.6387 58.219 29.692 57.9416 29.692ZM54.0216 23.036V21.5H59.2856V23.036H54.0216ZM62.2229 25.244C62.2229 24.38 62.3882 23.6707 62.7189 23.116C63.0495 22.5613 63.4762 22.1507 63.9989 21.884C64.5322 21.6067 65.0869 21.468 65.6629 21.468V23.18C65.1722 23.18 64.7082 23.2493 64.2709 23.388C63.8442 23.516 63.4975 23.7293 63.2309 24.028C62.9642 24.3267 62.8309 24.7213 62.8309 25.212L62.2229 25.244ZM61.0389 29.5V21.5H62.8309V29.5H61.0389ZM70.4194 29.692C69.6407 29.692 68.9474 29.516 68.3394 29.164C67.742 28.8013 67.2674 28.3053 66.9154 27.676C66.574 27.0467 66.4034 26.3213 66.4034 25.5C66.4034 24.6787 66.5794 23.9533 66.9314 23.324C67.2834 22.6947 67.7634 22.204 68.3714 21.852C68.99 21.4893 69.694 21.308 70.4834 21.308C71.198 21.308 71.8434 21.4947 72.4194 21.868C72.9954 22.2307 73.4487 22.7587 73.7794 23.452C74.1207 24.1453 74.2914 24.972 74.2914 25.932H68.0034L68.2434 25.708C68.2434 26.1987 68.35 26.6253 68.5634 26.988C68.7767 27.34 69.0594 27.612 69.4114 27.804C69.7634 27.996 70.1527 28.092 70.5794 28.092C71.07 28.092 71.4754 27.9853 71.7954 27.772C72.1154 27.548 72.366 27.26 72.5474 26.908L74.1314 27.58C73.9074 28.0067 73.6194 28.38 73.2674 28.7C72.926 29.02 72.5154 29.2653 72.0354 29.436C71.566 29.6067 71.0274 29.692 70.4194 29.692ZM68.3554 24.78L68.0994 24.556H72.6114L72.3714 24.78C72.3714 24.3427 72.2754 23.9853 72.0834 23.708C71.8914 23.42 71.646 23.2067 71.3474 23.068C71.0594 22.9187 70.7554 22.844 70.4354 22.844C70.1154 22.844 69.7954 22.9187 69.4754 23.068C69.1554 23.2067 68.8887 23.42 68.6754 23.708C68.462 23.9853 68.3554 24.3427 68.3554 24.78ZM80.5439 29.5L80.4639 27.996V25.388C80.4639 24.844 80.4052 24.3907 80.2879 24.028C80.1812 23.6547 79.9999 23.372 79.7439 23.18C79.4985 22.9773 79.1679 22.876 78.7519 22.876C78.3679 22.876 78.0319 22.956 77.7439 23.116C77.4559 23.276 77.2105 23.5267 77.0079 23.868L75.4399 23.292C75.6105 22.94 75.8345 22.6147 76.1119 22.316C76.3999 22.0067 76.7572 21.7613 77.1839 21.58C77.6212 21.3987 78.1439 21.308 78.7519 21.308C79.5305 21.308 80.1812 21.4627 80.7039 21.772C81.2265 22.0707 81.6105 22.5027 81.8559 23.068C82.1119 23.6333 82.2399 24.316 82.2399 25.116L82.1919 29.5H80.5439ZM78.2399 29.692C77.2799 29.692 76.5332 29.4787 75.9999 29.052C75.4772 28.6253 75.2159 28.0227 75.2159 27.244C75.2159 26.412 75.4932 25.7773 76.0479 25.34C76.6132 24.9027 77.3972 24.684 78.3999 24.684H80.5439V26.06H78.9759C78.2612 26.06 77.7599 26.1613 77.4719 26.364C77.1839 26.556 77.0399 26.8333 77.0399 27.196C77.0399 27.5053 77.1625 27.7507 77.4079 27.932C77.6639 28.1027 78.0159 28.188 78.4639 28.188C78.8692 28.188 79.2212 28.0973 79.5199 27.916C79.8185 27.7347 80.0479 27.4947 80.2079 27.196C80.3785 26.8973 80.4639 26.5613 80.4639 26.188H80.9919C80.9919 27.276 80.7732 28.1347 80.3359 28.764C79.8985 29.3827 79.1999 29.692 78.2399 29.692ZM85.7665 27.26L84.6785 26.028L88.8385 21.5H90.9985L85.7665 27.26ZM84.0545 29.5V18.3H85.8465V29.5H84.0545ZM89.1425 29.5L86.3265 25.356L87.4945 24.108L91.2705 29.5H89.1425Z" fill="#394C0A"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
6
firka/assets/images/carousel/card5.svg
Normal file
|
After Width: | Height: | Size: 8.8 KiB |
5
firka/assets/images/carousel/card6.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
6
firka/assets/images/carousel/card7.svg
Normal file
|
After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 13 KiB |
5
firka/assets/images/surprise_grades/play_card_star.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g id="tabler:play-card-star-filled">
|
||||
<path id="Vector" d="M14.1667 1.66667C14.8297 1.66667 15.4656 1.93006 15.9344 2.3989C16.4033 2.86774 16.6667 3.50363 16.6667 4.16667V15.8333C16.6667 16.4964 16.4033 17.1323 15.9344 17.6011C15.4656 18.0699 14.8297 18.3333 14.1667 18.3333H5.83333C5.17029 18.3333 4.53441 18.0699 4.06557 17.6011C3.59673 17.1323 3.33333 16.4964 3.33333 15.8333V4.16667C3.33333 3.50363 3.59673 2.86774 4.06557 2.3989C4.53441 1.93006 5.17029 1.66667 5.83333 1.66667H14.1667ZM14.175 15H14.1667C13.9543 15.0002 13.75 15.0816 13.5955 15.2274C13.4411 15.3732 13.3481 15.5725 13.3357 15.7845C13.3232 15.9965 13.3922 16.2053 13.5286 16.3682C13.6649 16.5311 13.8583 16.6357 14.0692 16.6608L14.175 16.6667C14.396 16.6667 14.608 16.5789 14.7643 16.4226C14.9205 16.2663 15.0083 16.0543 15.0083 15.8333C15.0083 15.6123 14.9205 15.4004 14.7643 15.2441C14.608 15.0878 14.396 15 14.175 15ZM10.025 7.08333L9.92917 7.0875C9.60917 7.12083 9.32583 7.315 9.18083 7.60667L8.75583 8.4625L7.8075 8.60083C7.455 8.65 7.1575 8.89833 7.04583 9.24083L7.01833 9.345C6.9866 9.50024 6.99456 9.66098 7.04146 9.81233C7.08837 9.96368 7.17271 10.1007 7.28667 10.2108L7.97 10.875L7.80833 11.8142C7.75 12.1742 7.8975 12.5283 8.18667 12.7375L8.27583 12.7942C8.41247 12.8713 8.56621 12.9131 8.7231 12.9157C8.87998 12.9183 9.03503 12.8817 9.17417 12.8092L10.0258 12.3625L10.875 12.8083C11.1892 12.975 11.575 12.9483 11.8667 12.7367L11.95 12.67C12.1842 12.4542 12.2967 12.1325 12.2417 11.8133L12.08 10.875L12.7658 10.2092C13.0242 9.9575 13.1158 9.5825 13.005 9.24167L12.97 9.15C12.9051 9.00436 12.8044 8.87758 12.6771 8.78153C12.5499 8.68548 12.4003 8.6233 12.2425 8.60083L11.2942 8.4625L10.8708 7.6075C10.793 7.44983 10.6727 7.31709 10.5233 7.22431C10.374 7.13152 10.2016 7.0824 10.0258 7.0825M5.84167 3.33333H5.83333C5.62093 3.33357 5.41664 3.4149 5.26219 3.56071C5.10775 3.70651 5.0148 3.90579 5.00236 4.11783C4.98991 4.32986 5.0589 4.53865 5.19522 4.70153C5.33155 4.8644 5.52492 4.96908 5.73583 4.99417L5.84167 5C6.06268 5 6.27464 4.9122 6.43092 4.75592C6.5872 4.59964 6.675 4.38768 6.675 4.16667C6.675 3.94565 6.5872 3.73369 6.43092 3.57741C6.27464 3.42113 6.06268 3.33333 5.84167 3.33333Z" fill="#A7DC22"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
3
firka/assets/images/surprise_grades/star_large.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 9" d="M10.5 0L11.047 7.18922C11.1594 8.66653 12.3335 9.84055 13.8108 9.95296L21 10.5L13.8108 11.047C12.3335 11.1594 11.1594 12.3335 11.047 13.8108L10.5 21L9.95296 13.8108C9.84055 12.3335 8.66653 11.1594 7.18923 11.047L0 10.5L7.18922 9.95296C8.66653 9.84055 9.84055 8.66653 9.95296 7.18923L10.5 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 503 B |
3
firka/assets/images/surprise_grades/star_medium.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 11" d="M12.5 0L13.1885 9.0478C13.3009 10.5251 14.4749 11.6991 15.9522 11.8115L25 12.5L15.9522 13.1885C14.4749 13.3009 13.3009 14.4749 13.1885 15.9522L12.5 25L11.8115 15.9522C11.6991 14.4749 10.5251 13.3009 9.0478 13.1885L0 12.5L9.0478 11.8115C10.5251 11.6991 11.6991 10.5251 11.8115 9.0478L12.5 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 504 B |
3
firka/assets/images/surprise_grades/star_small.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="9.87586" height="9.87586" viewBox="0 0 9.87586 9.87586" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="Star 10" d="M4.93793 0L5.15681 2.87656C5.23175 3.86143 6.01443 4.64411 6.9993 4.71905L9.87586 4.93793L6.9993 5.15681C6.01443 5.23175 5.23175 6.01443 5.15681 6.9993L4.93793 9.87586L4.71905 6.9993C4.64411 6.01443 3.86143 5.23175 2.87656 5.15681L0 4.93793L2.87656 4.71905C3.86143 4.64411 4.64411 3.86143 4.71905 2.87656L4.93793 0Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 549 B |
3
firka/assets/majesticons/check.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.7069 7.70643C19.8891 7.51783 19.9899 7.26523 19.9876 7.00303C19.9853 6.74083 19.8801 6.49002 19.6947 6.30461C19.5093 6.1192 19.2585 6.01403 18.9963 6.01176C18.7341 6.00948 18.4815 6.11027 18.2929 6.29243L8.99992 15.5854L5.70692 12.2924C5.51832 12.1103 5.26571 12.0095 5.00352 12.0118C4.74132 12.014 4.49051 12.1192 4.3051 12.3046C4.11969 12.49 4.01452 12.7408 4.01224 13.003C4.00997 13.2652 4.11076 13.5178 4.29292 13.7064L8.29292 17.7064C8.48045 17.8939 8.73476 17.9992 8.99992 17.9992C9.26508 17.9992 9.51939 17.8939 9.70692 17.7064L19.7069 7.70643Z" fill="#A7DC22"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 726 B |
10
firka/assets/majesticons/checkSolid.svg
Normal file
@@ -0,0 +1,10 @@
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_2679_4048)">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.5 0.5C1.96957 0.5 1.46086 0.710714 1.08579 1.08579C0.710714 1.46086 0.5 1.96957 0.5 2.5V9.5C0.5 10.0304 0.710714 10.5391 1.08579 10.9142C1.46086 11.2893 1.96957 11.5 2.5 11.5H9.5C10.0304 11.5 10.5391 11.2893 10.9142 10.9142C11.2893 10.5391 11.5 10.0304 11.5 9.5V2.5C11.5 1.96957 11.2893 1.46086 10.9142 1.08579C10.5391 0.710714 10.0304 0.5 9.5 0.5H2.5ZM9.8535 3.8535C9.94458 3.7592 9.99498 3.6329 9.99384 3.5018C9.9927 3.3707 9.94011 3.24529 9.84741 3.15259C9.75471 3.05989 9.6293 3.0073 9.4982 3.00616C9.3671 3.00502 9.2408 3.05542 9.1465 3.1465L4.5 7.793L2.8535 6.1465C2.7592 6.05542 2.6329 6.00502 2.5018 6.00616C2.3707 6.0073 2.24529 6.05989 2.15259 6.15259C2.05989 6.24529 2.0073 6.3707 2.00616 6.5018C2.00502 6.6329 2.05542 6.7592 2.1465 6.8535L4.1465 8.8535C4.24026 8.94724 4.36742 8.99989 4.5 8.99989C4.63258 8.99989 4.75974 8.94724 4.8535 8.8535L9.8535 3.8535Z" fill="#A7DC22"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_2679_4048">
|
||||
<rect width="12" height="12" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -1,3 +1,3 @@
|
||||
<svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.5 3C13.5 2.73478 13.3946 2.48043 13.2071 2.29289C13.0196 2.10536 12.7652 2 12.5 2C12.2348 2 11.9804 2.10536 11.7929 2.29289C11.6054 2.48043 11.5 2.73478 11.5 3V4C11.5 4.26522 11.6054 4.51957 11.7929 4.70711C11.9804 4.89464 12.2348 5 12.5 5C12.7652 5 13.0196 4.89464 13.2071 4.70711C13.3946 4.51957 13.5 4.26522 13.5 4V3ZM6.207 4.293C6.0184 4.11084 5.7658 4.01005 5.5036 4.01233C5.2414 4.0146 4.99059 4.11977 4.80518 4.30518C4.61977 4.49059 4.5146 4.7414 4.51233 5.0036C4.51005 5.2658 4.61084 5.5184 4.793 5.707L5.793 6.707C5.9816 6.88916 6.2342 6.98995 6.4964 6.98767C6.7586 6.9854 7.00941 6.88023 7.19482 6.69482C7.38023 6.50941 7.4854 6.2586 7.48767 5.9964C7.48995 5.7342 7.38916 5.4816 7.207 5.293L6.207 4.293ZM20.207 4.293C20.0195 4.10553 19.7652 4.00021 19.5 4.00021C19.2348 4.00021 18.9805 4.10553 18.793 4.293L17.793 5.293C17.6108 5.4816 17.51 5.7342 17.5123 5.9964C17.5146 6.2586 17.6198 6.50941 17.8052 6.69482C17.9906 6.88023 18.2414 6.9854 18.5036 6.98767C18.7658 6.98995 19.0184 6.88916 19.207 6.707L20.207 5.707C20.3945 5.51947 20.4998 5.26516 20.4998 5C20.4998 4.73484 20.3945 4.48053 20.207 4.293ZM12.5 7C11.1739 7 9.90215 7.52678 8.96447 8.46447C8.02678 9.40215 7.5 10.6739 7.5 12C7.5 13.3261 8.02678 14.5979 8.96447 15.5355C9.90215 16.4732 11.1739 17 12.5 17C13.8261 17 15.0979 16.4732 16.0355 15.5355C16.9732 14.5979 17.5 13.3261 17.5 12C17.5 10.6739 16.9732 9.40215 16.0355 8.46447C15.0979 7.52678 13.8261 7 12.5 7ZM3.5 11C3.23478 11 2.98043 11.1054 2.79289 11.2929C2.60536 11.4804 2.5 11.7348 2.5 12C2.5 12.2652 2.60536 12.5196 2.79289 12.7071C2.98043 12.8946 3.23478 13 3.5 13H4.5C4.76522 13 5.01957 12.8946 5.20711 12.7071C5.39464 12.5196 5.5 12.2652 5.5 12C5.5 11.7348 5.39464 11.4804 5.20711 11.2929C5.01957 11.1054 4.76522 11 4.5 11H3.5ZM20.5 11C20.2348 11 19.9804 11.1054 19.7929 11.2929C19.6054 11.4804 19.5 11.7348 19.5 12C19.5 12.2652 19.6054 12.5196 19.7929 12.7071C19.9804 12.8946 20.2348 13 20.5 13H21.5C21.7652 13 22.0196 12.8946 22.2071 12.7071C22.3946 12.5196 22.5 12.2652 22.5 12C22.5 11.7348 22.3946 11.4804 22.2071 11.2929C22.0196 11.1054 21.7652 11 21.5 11H20.5ZM7.207 18.707C7.30251 18.6148 7.37869 18.5044 7.4311 18.3824C7.48351 18.2604 7.5111 18.1292 7.51225 17.9964C7.5134 17.8636 7.4881 17.7319 7.43782 17.609C7.38754 17.4862 7.31329 17.3745 7.2194 17.2806C7.1255 17.1867 7.01385 17.1125 6.89095 17.0622C6.76806 17.0119 6.63638 16.9866 6.5036 16.9877C6.37082 16.9889 6.2396 17.0165 6.1176 17.0689C5.99559 17.1213 5.88525 17.1975 5.793 17.293L4.793 18.293C4.69749 18.3852 4.62131 18.4956 4.5689 18.6176C4.51649 18.7396 4.4889 18.8708 4.48775 19.0036C4.4866 19.1364 4.5119 19.2681 4.56218 19.391C4.61246 19.5138 4.68671 19.6255 4.7806 19.7194C4.8745 19.8133 4.98615 19.8875 5.10905 19.9378C5.23194 19.9881 5.36362 20.0134 5.4964 20.0123C5.62918 20.0111 5.7604 19.9835 5.8824 19.9311C6.00441 19.8787 6.11475 19.8025 6.207 19.707L7.207 18.707ZM19.207 17.293C19.0184 17.1108 18.7658 17.01 18.5036 17.0123C18.2414 17.0146 17.9906 17.1198 17.8052 17.3052C17.6198 17.4906 17.5146 17.7414 17.5123 18.0036C17.51 18.2658 17.6108 18.5184 17.793 18.707L18.793 19.707C18.9816 19.8892 19.2342 19.99 19.4964 19.9877C19.7586 19.9854 20.0094 19.8802 20.1948 19.6948C20.3802 19.5094 20.4854 19.2586 20.4877 18.9964C20.49 18.7342 20.3892 18.4816 20.207 18.293L19.207 17.293ZM13.5 20C13.5 19.7348 13.3946 19.4804 13.2071 19.2929C13.0196 19.1054 12.7652 19 12.5 19C12.2348 19 11.9804 19.1054 11.7929 19.2929C11.6054 19.4804 11.5 19.7348 11.5 20V21C11.5 21.2652 11.6054 21.5196 11.7929 21.7071C11.9804 21.8946 12.2348 22 12.5 22C12.7652 22 13.0196 21.8946 13.2071 21.7071C13.3946 21.5196 13.5 21.2652 13.5 21V20Z" fill="#FFFFFF"/>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 3C13 2.73478 12.8946 2.48043 12.7071 2.29289C12.5196 2.10536 12.2652 2 12 2C11.7348 2 11.4804 2.10536 11.2929 2.29289C11.1054 2.48043 11 2.73478 11 3V4C11 4.26522 11.1054 4.51957 11.2929 4.70711C11.4804 4.89464 11.7348 5 12 5C12.2652 5 12.5196 4.89464 12.7071 4.70711C12.8946 4.51957 13 4.26522 13 4V3ZM5.707 4.293C5.5184 4.11084 5.2658 4.01005 5.0036 4.01233C4.7414 4.0146 4.49059 4.11977 4.30518 4.30518C4.11977 4.49059 4.0146 4.7414 4.01233 5.0036C4.01005 5.2658 4.11084 5.5184 4.293 5.707L5.293 6.707C5.4816 6.88916 5.7342 6.98995 5.9964 6.98767C6.2586 6.9854 6.50941 6.88023 6.69482 6.69482C6.88023 6.50941 6.9854 6.2586 6.98767 5.9964C6.98995 5.7342 6.88916 5.4816 6.707 5.293L5.707 4.293ZM19.707 4.293C19.5195 4.10553 19.2652 4.00021 19 4.00021C18.7348 4.00021 18.4805 4.10553 18.293 4.293L17.293 5.293C17.1108 5.4816 17.01 5.7342 17.0123 5.9964C17.0146 6.2586 17.1198 6.50941 17.3052 6.69482C17.4906 6.88023 17.7414 6.9854 18.0036 6.98767C18.2658 6.98995 18.5184 6.88916 18.707 6.707L19.707 5.707C19.8945 5.51947 19.9998 5.26516 19.9998 5C19.9998 4.73484 19.8945 4.48053 19.707 4.293ZM12 7C10.6739 7 9.40215 7.52678 8.46447 8.46447C7.52678 9.40215 7 10.6739 7 12C7 13.3261 7.52678 14.5979 8.46447 15.5355C9.40215 16.4732 10.6739 17 12 17C13.3261 17 14.5979 16.4732 15.5355 15.5355C16.4732 14.5979 17 13.3261 17 12C17 10.6739 16.4732 9.40215 15.5355 8.46447C14.5979 7.52678 13.3261 7 12 7ZM3 11C2.73478 11 2.48043 11.1054 2.29289 11.2929C2.10536 11.4804 2 11.7348 2 12C2 12.2652 2.10536 12.5196 2.29289 12.7071C2.48043 12.8946 2.73478 13 3 13H4C4.26522 13 4.51957 12.8946 4.70711 12.7071C4.89464 12.5196 5 12.2652 5 12C5 11.7348 4.89464 11.4804 4.70711 11.2929C4.51957 11.1054 4.26522 11 4 11H3ZM20 11C19.7348 11 19.4804 11.1054 19.2929 11.2929C19.1054 11.4804 19 11.7348 19 12C19 12.2652 19.1054 12.5196 19.2929 12.7071C19.4804 12.8946 19.7348 13 20 13H21C21.2652 13 21.5196 12.8946 21.7071 12.7071C21.8946 12.5196 22 12.2652 22 12C22 11.7348 21.8946 11.4804 21.7071 11.2929C21.5196 11.1054 21.2652 11 21 11H20ZM6.707 18.707C6.80251 18.6148 6.87869 18.5044 6.9311 18.3824C6.98351 18.2604 7.0111 18.1292 7.01225 17.9964C7.0134 17.8636 6.9881 17.7319 6.93782 17.609C6.88754 17.4862 6.81329 17.3745 6.7194 17.2806C6.6255 17.1867 6.51385 17.1125 6.39095 17.0622C6.26806 17.0119 6.13638 16.9866 6.0036 16.9877C5.87082 16.9889 5.7396 17.0165 5.6176 17.0689C5.49559 17.1213 5.38525 17.1975 5.293 17.293L4.293 18.293C4.19749 18.3852 4.12131 18.4956 4.0689 18.6176C4.01649 18.7396 3.9889 18.8708 3.98775 19.0036C3.9866 19.1364 4.0119 19.2681 4.06218 19.391C4.11246 19.5138 4.18671 19.6255 4.2806 19.7194C4.3745 19.8133 4.48615 19.8875 4.60905 19.9378C4.73194 19.9881 4.86362 20.0134 4.9964 20.0123C5.12918 20.0111 5.2604 19.9835 5.3824 19.9311C5.50441 19.8787 5.61475 19.8025 5.707 19.707L6.707 18.707ZM18.707 17.293C18.5184 17.1108 18.2658 17.01 18.0036 17.0123C17.7414 17.0146 17.4906 17.1198 17.3052 17.3052C17.1198 17.4906 17.0146 17.7414 17.0123 18.0036C17.01 18.2658 17.1108 18.5184 17.293 18.707L18.293 19.707C18.4816 19.8892 18.7342 19.99 18.9964 19.9877C19.2586 19.9854 19.5094 19.8802 19.6948 19.6948C19.8802 19.5094 19.9854 19.2586 19.9877 18.9964C19.99 18.7342 19.8892 18.4816 19.707 18.293L18.707 17.293ZM13 20C13 19.7348 12.8946 19.4804 12.7071 19.2929C12.5196 19.1054 12.2652 19 12 19C11.7348 19 11.4804 19.1054 11.2929 19.2929C11.1054 19.4804 11 19.7348 11 20V21C11 21.2652 11.1054 21.5196 11.2929 21.7071C11.4804 21.8946 11.7348 22 12 22C12.2652 22 12.5196 21.8946 12.7071 21.7071C12.8946 21.5196 13 21.2652 13 21V20Z" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.6 KiB |
10
firka/codegen-lock.yaml
Normal file
@@ -0,0 +1,10 @@
|
||||
icons:
|
||||
"flutter_launcher_icons.yaml": "993c1cd3a99db70747299601e556d19ec959b0a16fd9ff2dbf2386cb6f2a640d"
|
||||
"pubspec.yaml": "198608775541fab3b6ff8cc21545e12a3413455f6ed87355cfdb576a97efab2d"
|
||||
"assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983"
|
||||
"assets/images/logos/monochrome_logo.png": "c269a5e689622484d800a4fda5927591a0bf99d34790a4f146b93cf6edabd455"
|
||||
"assets/images/logos/colored_logo_without_mustache.png": "d11cff9f38985885873bfdd2d84e61f8fab03803eada94d4caac1545ef3685f3"
|
||||
"assets/images/logos/colored_logo_only_mustache.png": "bad6220c11bdfb1dfe04e5173bd2ebedd3999689d4b3a68fc63dc520c96dd33b"
|
||||
splash:
|
||||
"flutter_native_splash.yaml": "f1bddb74798b1539c4e9213ca9ae305d625ebb0ac5bcbe079b523437e0abc2c4"
|
||||
"assets/images/logos/splash.png": "88fbebc3d686cb9095bcce362029b69978b1b14270e465e91d962b1425db1152"
|
||||
1
firka/firebase.json
Normal file
@@ -0,0 +1 @@
|
||||
{"flutter":{"platforms":{"android":{"default":{"projectId":"firka-4633b","appId":"1:219357380322:android:5b776732799faa5c08a8bb","fileOutput":"android/app/google-services.json"}},"dart":{"lib/firebase_options.dart":{"projectId":"firka-4633b","configurations":{"android":"1:219357380322:android:5b776732799faa5c08a8bb"}}}}}}
|
||||
@@ -1,11 +1,10 @@
|
||||
flutter_launcher_icons:
|
||||
generate: true
|
||||
android: "launcher_icon"
|
||||
ios: false
|
||||
image_path: "assets/images/logos/colored_logo.webp"
|
||||
adaptive_icon_monochrome: "assets/images/logos/monochrome_logo.png"
|
||||
adaptive_icon_background: "assets/images/logos/colored_logo_without_mustache.png"
|
||||
adaptive_icon_foreground: "assets/images/logos/colored_logo_only_mustache.png"
|
||||
adaptive_icon_foreground_inset: 0
|
||||
min_sdk_android: 21
|
||||
ios: true
|
||||
remove_alpha_channel_ios: true
|
||||
|
||||
@@ -17,5 +17,6 @@ flutter_native_splash:
|
||||
icon_background_color: "#7ca120"
|
||||
icon_background_color_dark: "#7ca120"
|
||||
|
||||
ios: true
|
||||
android: true
|
||||
ios: false
|
||||
web: false
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
39
firka/ios/.gitignore
vendored
@@ -1,39 +0,0 @@
|
||||
**/dgph
|
||||
*.mode1v3
|
||||
*.mode2v3
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
*.perspectivev3
|
||||
**/*sync/
|
||||
.sconsign.dblite
|
||||
.tags*
|
||||
**/.vagrant/
|
||||
**/DerivedData/
|
||||
Icon?
|
||||
**/Pods/
|
||||
**/.symlinks/
|
||||
profile
|
||||
xcuserdata
|
||||
**/.generated/
|
||||
Flutter/App.framework
|
||||
Flutter/Flutter.framework
|
||||
Flutter/Flutter.podspec
|
||||
Flutter/Generated.xcconfig
|
||||
Flutter/ephemeral/
|
||||
Flutter/app.flx
|
||||
Flutter/app.zip
|
||||
Flutter/flutter_assets/
|
||||
Flutter/flutter_export_environment.sh
|
||||
ServiceDefinitions.json
|
||||
Runner/GeneratedPluginRegistrant.*
|
||||
|
||||
# Exceptions to above rules.
|
||||
!default.mode1v3
|
||||
!default.mode2v3
|
||||
!default.pbxuser
|
||||
!default.perspectivev3
|
||||
|
||||
/.DerivedData
|
||||
|
||||
# Developer-specific configuration
|
||||
.dev_config
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "Icon-1024.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "watchos",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 147 KiB |
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct CountdownRing: View {
|
||||
let totalMinutes: Int
|
||||
let remainingMinutes: Int
|
||||
let label: String
|
||||
var size: CGFloat = 80
|
||||
var lineWidth: CGFloat = 8
|
||||
var displayOffset: Int = 0 // Add to displayed minutes (e.g., +1)
|
||||
|
||||
private var clampedRemainingMinutes: Int {
|
||||
guard totalMinutes > 0 else { return 0 }
|
||||
return max(0, min(remainingMinutes, totalMinutes))
|
||||
}
|
||||
|
||||
var progress: Double {
|
||||
guard totalMinutes > 0 else { return 0 }
|
||||
return Double(totalMinutes - clampedRemainingMinutes) / Double(totalMinutes)
|
||||
}
|
||||
|
||||
var displayedMinutes: Int {
|
||||
max(0, remainingMinutes + displayOffset)
|
||||
}
|
||||
|
||||
var ringColor: Color {
|
||||
if clampedRemainingMinutes < 5 { return .red }
|
||||
if clampedRemainingMinutes < 10 { return .yellow }
|
||||
return .green
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Circle()
|
||||
.stroke(Color(white: 0.2), lineWidth: lineWidth)
|
||||
|
||||
Circle()
|
||||
.trim(from: 0, to: progress)
|
||||
.stroke(ringColor, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
|
||||
.rotationEffect(.degrees(-90))
|
||||
.animation(.easeInOut, value: progress)
|
||||
|
||||
VStack(spacing: 1) {
|
||||
Text("\(displayedMinutes)")
|
||||
.font(size > 60 ? .title2 : .headline)
|
||||
.fontWeight(.bold)
|
||||
Text(label)
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
.frame(width: size, height: size)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
VStack(spacing: 20) {
|
||||
CountdownRing(totalMinutes: 45, remainingMinutes: 30, label: "min")
|
||||
|
||||
CountdownRing(totalMinutes: 45, remainingMinutes: 8, label: "min")
|
||||
|
||||
CountdownRing(totalMinutes: 45, remainingMinutes: 3, label: "min")
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct FirkaCard<Content: View>: View {
|
||||
let content: Content
|
||||
var isHighlighted: Bool = false
|
||||
var backgroundColor: Color? = nil
|
||||
|
||||
init(
|
||||
isHighlighted: Bool = false,
|
||||
backgroundColor: Color? = nil,
|
||||
@ViewBuilder content: () -> Content
|
||||
) {
|
||||
self.isHighlighted = isHighlighted
|
||||
self.backgroundColor = backgroundColor
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
content
|
||||
.padding(12)
|
||||
.background(
|
||||
backgroundColor ??
|
||||
(isHighlighted ? Color.green.opacity(0.2) : Color(white: 0.12))
|
||||
)
|
||||
.cornerRadius(12)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
VStack(spacing: 12) {
|
||||
FirkaCard {
|
||||
Text("Normal Card")
|
||||
.foregroundColor(.primary)
|
||||
}
|
||||
|
||||
FirkaCard(isHighlighted: true) {
|
||||
Text("Highlighted Card")
|
||||
.foregroundColor(.primary)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GradeBadge: View {
|
||||
let grade: Int
|
||||
var size: CGFloat = 24
|
||||
|
||||
var color: Color {
|
||||
switch grade {
|
||||
case 5: return .green
|
||||
case 4: return .blue
|
||||
case 3: return .yellow
|
||||
case 2: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(color)
|
||||
.frame(width: size, height: size)
|
||||
|
||||
Text("\(grade)")
|
||||
.font(.system(size: size * 0.5, weight: .bold))
|
||||
.foregroundColor(.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
HStack(spacing: 12) {
|
||||
GradeBadge(grade: 5)
|
||||
GradeBadge(grade: 4)
|
||||
GradeBadge(grade: 3)
|
||||
GradeBadge(grade: 2)
|
||||
GradeBadge(grade: 1)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GradeRow: View {
|
||||
let grade: WidgetGrade
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .center, spacing: 8) {
|
||||
Text(grade.displayValue)
|
||||
.font(.caption)
|
||||
.fontWeight(.semibold)
|
||||
.foregroundColor(.white)
|
||||
.frame(width: 24, height: 24)
|
||||
.background(
|
||||
Circle()
|
||||
.fill(grade.gradeColor)
|
||||
)
|
||||
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
if let topic = grade.topic {
|
||||
Text(topic)
|
||||
.font(.caption2)
|
||||
.foregroundColor(.primary)
|
||||
.lineLimit(2)
|
||||
}
|
||||
|
||||
HStack(spacing: 4) {
|
||||
Text(grade.type.name)
|
||||
.font(.system(size: 10))
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
if let weight = grade.weightPercentage, weight != 100 {
|
||||
Text("(\(weight)%)")
|
||||
.font(.system(size: 10))
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 6)
|
||||
.background(Color(white: 0.15))
|
||||
.cornerRadius(6)
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct LessonCard: View {
|
||||
let lesson: WidgetLesson
|
||||
let isActive: Bool
|
||||
let colors: WidgetColors?
|
||||
|
||||
var backgroundColor: Color {
|
||||
if let colors = colors {
|
||||
return colors.cardColor
|
||||
}
|
||||
return Color(white: 0.15)
|
||||
}
|
||||
|
||||
var textPrimaryColor: Color {
|
||||
if let colors = colors {
|
||||
return colors.textPrimaryColor
|
||||
}
|
||||
return .primary
|
||||
}
|
||||
|
||||
var textSecondaryColor: Color {
|
||||
if let colors = colors {
|
||||
return colors.textSecondaryColor
|
||||
}
|
||||
return .secondary
|
||||
}
|
||||
|
||||
var textTertiaryColor: Color {
|
||||
if let colors = colors {
|
||||
return colors.textTertiaryColor
|
||||
}
|
||||
return .secondary.opacity(0.7)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
if let number = lesson.lessonNumber {
|
||||
Text("\(number)")
|
||||
.font(.headline)
|
||||
.fontWeight(.semibold)
|
||||
.foregroundColor(isActive ? .white : textPrimaryColor)
|
||||
.frame(width: 28, height: 28)
|
||||
.background(
|
||||
Circle()
|
||||
.fill(isActive ? Color.green : Color.clear)
|
||||
)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(lesson.displayName)
|
||||
.font(.headline)
|
||||
.fontWeight(.semibold)
|
||||
.foregroundColor(lesson.isCancelled ? .red :
|
||||
lesson.isSubstitution ? .orange : textPrimaryColor)
|
||||
.strikethrough(lesson.isCancelled, color: .red)
|
||||
.lineLimit(1)
|
||||
|
||||
Text(lesson.timeString)
|
||||
.font(.caption2)
|
||||
.foregroundColor(lesson.isCancelled ? .red.opacity(0.8) :
|
||||
lesson.isSubstitution ? .orange.opacity(0.8) : textSecondaryColor)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
}
|
||||
|
||||
if let room = lesson.roomName {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "door.right.hand.closed")
|
||||
.font(.caption2)
|
||||
Text(room)
|
||||
.font(.caption2)
|
||||
}
|
||||
.foregroundColor(lesson.isCancelled ? .red.opacity(0.7) :
|
||||
lesson.isSubstitution ? .orange.opacity(0.7) : textSecondaryColor)
|
||||
.lineLimit(1)
|
||||
}
|
||||
|
||||
if let teacher = lesson.teacher {
|
||||
Text(teacher)
|
||||
.font(.caption2)
|
||||
.foregroundColor(lesson.isCancelled ? .red.opacity(0.7) :
|
||||
lesson.isSubstitution ? .orange.opacity(0.7) : textTertiaryColor)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
.padding(10)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(backgroundColor)
|
||||
.cornerRadius(10)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 10)
|
||||
.stroke(
|
||||
isActive ? Color.green : Color.clear,
|
||||
lineWidth: isActive ? 2 : 0
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
VStack(spacing: 12) {
|
||||
LessonCard(
|
||||
lesson: WidgetLesson(
|
||||
uid: "1",
|
||||
date: "2026-02-01",
|
||||
start: Date(),
|
||||
end: Date().addingTimeInterval(3600),
|
||||
name: "Matematika",
|
||||
lessonNumber: 3,
|
||||
teacher: "Nagy János",
|
||||
substituteTeacher: nil,
|
||||
subject: WidgetSubject(uid: "math", name: "Matematika", category: nil, sortIndex: 1, teacherName: "Nagy János"),
|
||||
theme: nil,
|
||||
roomName: "201",
|
||||
isCancelled: false,
|
||||
isSubstitution: false
|
||||
),
|
||||
isActive: true,
|
||||
colors: nil
|
||||
)
|
||||
|
||||
LessonCard(
|
||||
lesson: WidgetLesson(
|
||||
uid: "2",
|
||||
date: "2026-02-01",
|
||||
start: Date().addingTimeInterval(7200),
|
||||
end: Date().addingTimeInterval(10800),
|
||||
name: "Angol",
|
||||
lessonNumber: 4,
|
||||
teacher: "Kovács Éva",
|
||||
substituteTeacher: nil,
|
||||
subject: WidgetSubject(uid: "eng", name: "Angol", category: nil, sortIndex: 2, teacherName: "Kovács Éva"),
|
||||
theme: nil,
|
||||
roomName: "105",
|
||||
isCancelled: false,
|
||||
isSubstitution: false
|
||||
),
|
||||
isActive: false,
|
||||
colors: nil
|
||||
)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct AverageProgressBar: View {
|
||||
let average: Double
|
||||
|
||||
var progress: Double {
|
||||
(average - 1) / 4
|
||||
}
|
||||
|
||||
var color: Color {
|
||||
switch average {
|
||||
case 4.5...: return .green
|
||||
case 3.5..<4.5: return .blue
|
||||
case 2.5..<3.5: return .yellow
|
||||
case 1.5..<2.5: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(Color(white: 0.3))
|
||||
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(color)
|
||||
.frame(width: geo.size.width * progress)
|
||||
}
|
||||
}
|
||||
.frame(height: 4)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
VStack(spacing: 16) {
|
||||
VStack(alignment: .leading) {
|
||||
Text("5.0 - Excellent")
|
||||
.font(.caption)
|
||||
AverageProgressBar(average: 5.0)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading) {
|
||||
Text("4.2 - Good")
|
||||
.font(.caption)
|
||||
AverageProgressBar(average: 4.2)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading) {
|
||||
Text("3.0 - Average")
|
||||
.font(.caption)
|
||||
AverageProgressBar(average: 3.0)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading) {
|
||||
Text("2.0 - Below Average")
|
||||
.font(.caption)
|
||||
AverageProgressBar(average: 2.0)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading) {
|
||||
Text("1.2 - Poor")
|
||||
.font(.caption)
|
||||
AverageProgressBar(average: 1.2)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct SubjectRow: View {
|
||||
let name: String
|
||||
let average: Double?
|
||||
let gradeCount: Int
|
||||
|
||||
var averageColor: Color {
|
||||
guard let avg = average else { return .gray }
|
||||
switch avg {
|
||||
case 4.5...: return .green
|
||||
case 3.5...: return .blue
|
||||
case 2.5...: return .yellow
|
||||
case 1.5...: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .center, spacing: 8) {
|
||||
Text(name)
|
||||
.font(.caption)
|
||||
.foregroundColor(.primary)
|
||||
|
||||
Spacer()
|
||||
|
||||
if let avg = average {
|
||||
Text(String(format: "%.2f", avg))
|
||||
.font(.caption)
|
||||
.fontWeight(.bold)
|
||||
.foregroundColor(averageColor)
|
||||
} else {
|
||||
Text("\(gradeCount)")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 6)
|
||||
.background(Color(white: 0.15))
|
||||
.cornerRadius(6)
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
import SwiftUI
|
||||
import WatchConnectivity
|
||||
internal import Combine
|
||||
|
||||
struct ContentView: View {
|
||||
var dataStore = DataStore.shared
|
||||
@State private var selectedTab = 0
|
||||
@State private var isRequestingToken = false
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
private let staleCheckTimer = Timer.publish(every: 30, on: .main, in: .common).autoconnect()
|
||||
|
||||
private let autoRefreshThreshold: TimeInterval = 10 * 60
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if dataStore.isRecoveringToken {
|
||||
VStack(spacing: 16) {
|
||||
ProgressView()
|
||||
.scaleEffect(1.2)
|
||||
Text("recovering_token".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
else if dataStore.needsReauth && dataStore.hasToken {
|
||||
ReauthRequiredView(onTokenReceived: {
|
||||
dataStore.resetRecoveryState()
|
||||
dataStore.checkTokenState()
|
||||
Task {
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
}
|
||||
})
|
||||
} else if !dataStore.hasToken && dataStore.data == nil {
|
||||
if isRequestingToken {
|
||||
ProgressView("connecting".localized)
|
||||
} else {
|
||||
PairingView(onRequestToken: requestToken)
|
||||
}
|
||||
} else {
|
||||
mainContent
|
||||
}
|
||||
}
|
||||
.task {
|
||||
dataStore.reconcileSharedSessionState()
|
||||
WatchL10n.shared.reconcileFromSharedState()
|
||||
dataStore.checkTokenState()
|
||||
dataStore.loadFromCache()
|
||||
if dataStore.hasToken {
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
} else {
|
||||
requestToken()
|
||||
}
|
||||
}
|
||||
.onChange(of: scenePhase) { oldPhase, newPhase in
|
||||
if newPhase == .active && oldPhase != .active {
|
||||
dataStore.reconcileSharedSessionState()
|
||||
WatchL10n.shared.reconcileFromSharedState()
|
||||
if shouldAutoRefresh {
|
||||
print("[Watch] App came to foreground, data is stale (>10 min), refreshing...")
|
||||
Task {
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
}
|
||||
} else {
|
||||
print("[Watch] App came to foreground, data is fresh (<10 min), skipping refresh")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onReceive(staleCheckTimer) { _ in
|
||||
guard scenePhase == .active else { return }
|
||||
dataStore.reconcileSharedSessionState()
|
||||
WatchL10n.shared.reconcileFromSharedState()
|
||||
|
||||
if !dataStore.hasToken {
|
||||
dataStore.checkTokenState()
|
||||
if dataStore.hasToken {
|
||||
print("[Watch] Token appeared (iCloud Keychain sync?), refreshing...")
|
||||
Task {
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if shouldAutoRefresh && !dataStore.isLoading {
|
||||
print("[Watch] Data became stale (>10 min), auto-refreshing...")
|
||||
Task {
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var shouldAutoRefresh: Bool {
|
||||
guard dataStore.hasToken else { return false }
|
||||
guard let lastUpdated = dataStore.lastUpdated else { return true }
|
||||
let elapsed = Date().timeIntervalSince(lastUpdated)
|
||||
return elapsed >= autoRefreshThreshold
|
||||
}
|
||||
|
||||
private func requestToken() {
|
||||
guard !isRequestingToken else { return }
|
||||
guard WCSession.default.activationState == .activated else {
|
||||
print("[Watch] Cannot request token: session not activated")
|
||||
return
|
||||
}
|
||||
guard WCSession.default.isReachable else {
|
||||
print("[Watch] Cannot request token: iPhone not reachable")
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] Requesting token from iPhone...")
|
||||
isRequestingToken = true
|
||||
WatchConnectivityManager.shared.requestTokenFromPhone()
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
|
||||
self.isRequestingToken = false
|
||||
}
|
||||
}
|
||||
|
||||
private var mainContent: some View {
|
||||
TabView(selection: $selectedTab) {
|
||||
HomeView(dataStore: dataStore)
|
||||
.tag(0)
|
||||
|
||||
TimetableView(dataStore: dataStore)
|
||||
.tag(1)
|
||||
|
||||
GradesView(dataStore: dataStore)
|
||||
.tag(2)
|
||||
|
||||
NavigationStack {
|
||||
SettingsView()
|
||||
}
|
||||
.tag(3)
|
||||
}
|
||||
.tabViewStyle(.verticalPage)
|
||||
}
|
||||
}
|
||||
|
||||
struct PairingView: View {
|
||||
var onRequestToken: (() -> Void)?
|
||||
|
||||
private var isWatchSystemPaired: Bool {
|
||||
guard WCSession.isSupported() else { return false }
|
||||
return WCSession.default.isCompanionAppInstalled
|
||||
}
|
||||
|
||||
private var titleKey: String {
|
||||
isWatchSystemPaired ? "login_on_iphone" : "pair_with_iphone"
|
||||
}
|
||||
|
||||
private var descriptionKey: String {
|
||||
isWatchSystemPaired ? "open_and_login_on_iphone" : "open_firka_on_iphone"
|
||||
}
|
||||
|
||||
private var iconName: String {
|
||||
isWatchSystemPaired
|
||||
? "person.crop.circle.badge.exclamationmark"
|
||||
: "iphone.and.arrow.right.inward"
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: iconName)
|
||||
.font(.system(size: 36))
|
||||
.foregroundColor(.blue)
|
||||
|
||||
Text(titleKey.localized)
|
||||
.font(.headline)
|
||||
|
||||
Text(descriptionKey.localized)
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.horizontal)
|
||||
|
||||
if isWatchSystemPaired {
|
||||
Button("sync_button".localized) {
|
||||
onRequestToken?()
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.app.firka.firkaa</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)app.firka.shared</string>
|
||||
</array>
|
||||
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
|
||||
<string>$(TeamIdentifierPrefix)app.firka.firkaa</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,35 +0,0 @@
|
||||
import SwiftUI
|
||||
import WatchKit
|
||||
|
||||
@main
|
||||
struct FirkaWatchApp: App {
|
||||
@WKApplicationDelegateAdaptor(WatchAppDelegate.self) var delegate
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class WatchAppDelegate: NSObject, WKApplicationDelegate {
|
||||
func applicationDidFinishLaunching() {
|
||||
print("[Watch] applicationDidFinishLaunching called")
|
||||
WatchConnectivityManager.shared.activate()
|
||||
}
|
||||
|
||||
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
|
||||
for task in backgroundTasks {
|
||||
switch task {
|
||||
case let refreshTask as WKApplicationRefreshBackgroundTask:
|
||||
Task {
|
||||
await BackgroundRefreshManager.shared.handleBackgroundRefresh()
|
||||
refreshTask.setTaskCompletedWithSnapshot(false)
|
||||
}
|
||||
default:
|
||||
task.setTaskCompletedWithSnapshot(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,464 +0,0 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import WidgetKit
|
||||
|
||||
enum WatchLanguage: String, CaseIterable, Codable {
|
||||
case hungarian = "hu"
|
||||
case english = "en"
|
||||
case german = "de"
|
||||
|
||||
var displayName: String {
|
||||
switch self {
|
||||
case .hungarian: return "Magyar"
|
||||
case .english: return "English"
|
||||
case .german: return "Deutsch"
|
||||
}
|
||||
}
|
||||
|
||||
var flag: String {
|
||||
switch self {
|
||||
case .hungarian: return "🇭🇺"
|
||||
case .english: return "🇬🇧"
|
||||
case .german: return "🇩🇪"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Observable
|
||||
class WatchL10n {
|
||||
static let shared = WatchL10n()
|
||||
|
||||
private let languageKey = "watch_language"
|
||||
private let syncWithiPhoneKey = "watch_sync_language_with_iphone"
|
||||
private let lastAppliedSharedLanguageVersionKey = "watch_last_applied_shared_language_version"
|
||||
private static let appGroupID = "group.app.firka.firkaa"
|
||||
private var appGroupDefaults: UserDefaults? {
|
||||
UserDefaults(suiteName: Self.appGroupID)
|
||||
}
|
||||
|
||||
var currentLanguage: WatchLanguage {
|
||||
didSet {
|
||||
UserDefaults.standard.set(currentLanguage.rawValue, forKey: languageKey)
|
||||
appGroupDefaults?.set(currentLanguage.rawValue, forKey: languageKey)
|
||||
}
|
||||
}
|
||||
|
||||
var syncWithiPhone: Bool {
|
||||
didSet {
|
||||
UserDefaults.standard.set(syncWithiPhone, forKey: syncWithiPhoneKey)
|
||||
appGroupDefaults?.set(syncWithiPhone, forKey: syncWithiPhoneKey)
|
||||
if syncWithiPhone {
|
||||
refreshFromiPhoneAndSharedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var strings: [String: String] = [:]
|
||||
|
||||
private init() {
|
||||
let savedLanguage = UserDefaults.standard.string(forKey: languageKey) ?? "hu"
|
||||
self.currentLanguage = WatchLanguage(rawValue: savedLanguage) ?? .hungarian
|
||||
if let storedSyncPref = UserDefaults.standard.object(forKey: syncWithiPhoneKey) as? Bool {
|
||||
self.syncWithiPhone = storedSyncPref
|
||||
} else {
|
||||
self.syncWithiPhone = true
|
||||
UserDefaults.standard.set(true, forKey: syncWithiPhoneKey)
|
||||
appGroupDefaults?.set(true, forKey: syncWithiPhoneKey)
|
||||
}
|
||||
appGroupDefaults?.set(currentLanguage.rawValue, forKey: languageKey)
|
||||
loadStrings()
|
||||
}
|
||||
|
||||
private func loadStrings() {
|
||||
strings = Self.stringsForLanguage(currentLanguage)
|
||||
}
|
||||
|
||||
func setLanguage(_ language: WatchLanguage) {
|
||||
if Thread.isMainThread {
|
||||
currentLanguage = language
|
||||
loadStrings()
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
} else {
|
||||
DispatchQueue.main.async { [self] in
|
||||
currentLanguage = language
|
||||
loadStrings()
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updateFromiPhone(languageCode: String, sharedStateVersion: Int64? = nil) {
|
||||
guard syncWithiPhone else { return }
|
||||
let lastAppliedVersion = lastAppliedSharedLanguageVersion()
|
||||
if let sharedStateVersion,
|
||||
sharedStateVersion > 0,
|
||||
sharedStateVersion < lastAppliedVersion {
|
||||
print("[WatchL10n] Ignoring stale WC language update (version: \(sharedStateVersion), lastApplied: \(lastAppliedVersion))")
|
||||
return
|
||||
}
|
||||
|
||||
if let language = WatchLanguage(rawValue: languageCode) {
|
||||
if language != currentLanguage {
|
||||
setLanguage(language)
|
||||
}
|
||||
if let sharedStateVersion, sharedStateVersion > 0 {
|
||||
setLastAppliedSharedLanguageVersion(max(lastAppliedVersion, sharedStateVersion))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func parseInt64(_ value: Any?) -> Int64? {
|
||||
if let value = value as? Int64 { return value }
|
||||
if let value = value as? Int { return Int64(value) }
|
||||
if let value = value as? Double { return Int64(value) }
|
||||
if let value = value as? String, let parsed = Int64(value) { return parsed }
|
||||
return nil
|
||||
}
|
||||
|
||||
private func lastAppliedSharedLanguageVersion() -> Int64 {
|
||||
parseInt64(UserDefaults.standard.object(forKey: lastAppliedSharedLanguageVersionKey)) ?? 0
|
||||
}
|
||||
|
||||
private func setLastAppliedSharedLanguageVersion(_ value: Int64) {
|
||||
UserDefaults.standard.set(value, forKey: lastAppliedSharedLanguageVersionKey)
|
||||
}
|
||||
|
||||
func resetLanguageVersionTracking() {
|
||||
setLastAppliedSharedLanguageVersion(0)
|
||||
print("[WatchL10n] Language version tracking reset for account switch")
|
||||
}
|
||||
|
||||
func reconcileFromSharedState() {
|
||||
guard syncWithiPhone else { return }
|
||||
guard let sharedState = SharedLanguageStateManager.shared.loadState() else { return }
|
||||
let lastAppliedVersion = lastAppliedSharedLanguageVersion()
|
||||
guard sharedState.stateVersion > lastAppliedVersion else { return }
|
||||
|
||||
if let language = WatchLanguage(rawValue: sharedState.languageCode) {
|
||||
if language != currentLanguage {
|
||||
setLanguage(language)
|
||||
}
|
||||
setLastAppliedSharedLanguageVersion(sharedState.stateVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func refreshFromiPhoneAndSharedState() {
|
||||
guard syncWithiPhone else { return }
|
||||
requestLanguageFromiPhone()
|
||||
reconcileFromSharedState()
|
||||
}
|
||||
|
||||
private func requestLanguageFromiPhone() {
|
||||
WatchConnectivityManager.shared.requestLanguageFromPhone()
|
||||
}
|
||||
|
||||
func string(_ key: String) -> String {
|
||||
return strings[key] ?? key
|
||||
}
|
||||
|
||||
func string(_ key: String, _ args: CVarArg...) -> String {
|
||||
let format = strings[key] ?? key
|
||||
return String(format: format, arguments: args)
|
||||
}
|
||||
|
||||
static func stringsForLanguage(_ language: WatchLanguage) -> [String: String] {
|
||||
switch language {
|
||||
case .hungarian:
|
||||
return hungarianStrings
|
||||
case .english:
|
||||
return englishStrings
|
||||
case .german:
|
||||
return germanStrings
|
||||
}
|
||||
}
|
||||
|
||||
private static let hungarianStrings: [String: String] = [
|
||||
// Home View
|
||||
"current_lesson": "Jelenlegi óra",
|
||||
"next": "Következő",
|
||||
"break": "Szünet",
|
||||
"next_lesson": "Következő: %@",
|
||||
"first_lesson": "Első órád",
|
||||
"today_lessons_count": "Ma %d órád van",
|
||||
"no_more_lessons": "Ma nincs több órád",
|
||||
"pair_with_iphone": "Párosítsd az iPhone-oddal",
|
||||
"open_firka_on_iphone": "Nyisd meg a Firka appot az iPhone-odon",
|
||||
"login_on_iphone": "Jelentkezz be iPhone-on",
|
||||
"open_and_login_on_iphone": "Nyisd meg a Firka appot iPhone-on, és lépj be egy fiókba",
|
||||
"updated": "Frissítve: %@",
|
||||
"minutes": "perc",
|
||||
"time_now": "most",
|
||||
"time_hours_minutes": "%d ó %d p",
|
||||
"time_hours": "%d óra",
|
||||
"time_minutes_only": "%d perc",
|
||||
"time_since_minutes_one": "1 perce",
|
||||
"time_since_minutes_many": "%d perce",
|
||||
"time_since_hours_one": "1 órája",
|
||||
"time_since_hours_many": "%d órája",
|
||||
"time_since_days_one": "1 napja",
|
||||
"time_since_days_many": "%d napja",
|
||||
|
||||
// Timetable View
|
||||
"free_day": "Szabad nap",
|
||||
"lesson_number": "%d. óra",
|
||||
"day_mon": "H",
|
||||
"day_tue": "K",
|
||||
"day_wed": "Sz",
|
||||
"day_thu": "Cs",
|
||||
"day_fri": "P",
|
||||
|
||||
// Grades View
|
||||
"grades_count": "%d jegy",
|
||||
"total_average": "Teljes átlag",
|
||||
"average": "Átlag:",
|
||||
"no_data": "Nincs adat",
|
||||
"no_grades": "Nincsenek jegyek",
|
||||
|
||||
// Lesson Detail
|
||||
"lesson_details": "Óra részletei",
|
||||
"cancelled": "Elmarad",
|
||||
"substitution": "Helyettesítés",
|
||||
"teacher": "Tanár",
|
||||
"room": "Terem",
|
||||
"topic": "Téma",
|
||||
|
||||
// Settings
|
||||
"settings": "Beállítások",
|
||||
"refresh_interval": "Frissítési időköz",
|
||||
"auto": "Automatikus",
|
||||
"15_minutes": "15 perc",
|
||||
"30_minutes": "30 perc",
|
||||
"1_hour": "1 óra",
|
||||
"version": "Verzió",
|
||||
"language": "Nyelv",
|
||||
"sync_with_iphone": "iPhone nyelvével",
|
||||
"clear_cache": "Cache törlése",
|
||||
"logout": "Kijelentkezés",
|
||||
|
||||
// Refresh
|
||||
"refresh": "Frissítés",
|
||||
"refreshing": "Frissítés...",
|
||||
"refresh_success": "Sikeres!",
|
||||
"refresh_failed": "Sikertelen",
|
||||
"error_api": "Kréta API hiba",
|
||||
"error_network": "Hálózati hiba",
|
||||
|
||||
// Date labels
|
||||
"tomorrow_first_lesson": "Holnap első órád",
|
||||
"day_first_lesson": "%@ első órád",
|
||||
"next_school_day": "Következő iskolai nap",
|
||||
|
||||
// Navigation
|
||||
"home": "Kezdőlap",
|
||||
"timetable": "Órarend",
|
||||
"grades": "Jegyek",
|
||||
|
||||
// Reauth
|
||||
"reauth_required": "Újrabelépés szükséges",
|
||||
"reauth_description": "A munkamenet lejárt. Lépj be újra az iPhone appban.",
|
||||
"sync_button": "Szinkronizálás",
|
||||
"syncing": "Szinkronizálás...",
|
||||
"sync_success": "Sikeres!",
|
||||
"sync_failed": "Sikertelen",
|
||||
"phone_not_reachable": "iPhone nem elérhető",
|
||||
"connecting": "Kapcsolódás...",
|
||||
"recovering_token": "Token helyreállítása...",
|
||||
]
|
||||
|
||||
private static let englishStrings: [String: String] = [
|
||||
// Home View
|
||||
"current_lesson": "Current Lesson",
|
||||
"next": "Next",
|
||||
"break": "Break",
|
||||
"next_lesson": "Next: %@",
|
||||
"first_lesson": "First Lesson",
|
||||
"today_lessons_count": "You have %d lessons today",
|
||||
"no_more_lessons": "No more lessons today",
|
||||
"pair_with_iphone": "Pair with iPhone",
|
||||
"open_firka_on_iphone": "Open Firka app on your iPhone",
|
||||
"login_on_iphone": "Sign in on iPhone",
|
||||
"open_and_login_on_iphone": "Open Firka on your iPhone and sign in to an account",
|
||||
"updated": "Updated: %@",
|
||||
"minutes": "min",
|
||||
"time_now": "now",
|
||||
"time_hours_minutes": "%dh %dm",
|
||||
"time_hours": "%d hours",
|
||||
"time_minutes_only": "%d min",
|
||||
"time_since_minutes_one": "1 min ago",
|
||||
"time_since_minutes_many": "%d mins ago",
|
||||
"time_since_hours_one": "1 hour ago",
|
||||
"time_since_hours_many": "%d hours ago",
|
||||
"time_since_days_one": "1 day ago",
|
||||
"time_since_days_many": "%d days ago",
|
||||
|
||||
// Timetable View
|
||||
"free_day": "Free Day",
|
||||
"lesson_number": "Lesson %d",
|
||||
"day_mon": "Mon",
|
||||
"day_tue": "Tue",
|
||||
"day_wed": "Wed",
|
||||
"day_thu": "Thu",
|
||||
"day_fri": "Fri",
|
||||
|
||||
// Grades View
|
||||
"grades_count": "%d grades",
|
||||
"total_average": "Total Average",
|
||||
"average": "Average:",
|
||||
"no_data": "No data",
|
||||
"no_grades": "No grades",
|
||||
|
||||
// Lesson Detail
|
||||
"lesson_details": "Lesson Details",
|
||||
"cancelled": "Cancelled",
|
||||
"substitution": "Substitution",
|
||||
"teacher": "Teacher",
|
||||
"room": "Room",
|
||||
"topic": "Topic",
|
||||
|
||||
// Settings
|
||||
"settings": "Settings",
|
||||
"refresh_interval": "Refresh Interval",
|
||||
"auto": "Auto",
|
||||
"15_minutes": "15 minutes",
|
||||
"30_minutes": "30 minutes",
|
||||
"1_hour": "1 hour",
|
||||
"version": "Version",
|
||||
"language": "Language",
|
||||
"sync_with_iphone": "Sync with iPhone",
|
||||
"clear_cache": "Clear Cache",
|
||||
"logout": "Log Out",
|
||||
|
||||
// Refresh
|
||||
"refresh": "Refresh",
|
||||
"refreshing": "Refreshing...",
|
||||
"refresh_success": "Success!",
|
||||
"refresh_failed": "Failed",
|
||||
"error_api": "Kréta API Error",
|
||||
"error_network": "Network Error",
|
||||
|
||||
// Date labels
|
||||
"tomorrow_first_lesson": "Tomorrow's first lesson",
|
||||
"day_first_lesson": "%@'s first lesson",
|
||||
"next_school_day": "Next school day",
|
||||
|
||||
// Navigation
|
||||
"home": "Home",
|
||||
"timetable": "Timetable",
|
||||
"grades": "Grades",
|
||||
|
||||
// Reauth
|
||||
"reauth_required": "Re-login Required",
|
||||
"reauth_description": "Your session has expired. Please log in again on your iPhone.",
|
||||
"sync_button": "Sync",
|
||||
"syncing": "Syncing...",
|
||||
"sync_success": "Success!",
|
||||
"sync_failed": "Failed",
|
||||
"phone_not_reachable": "iPhone not reachable",
|
||||
"connecting": "Connecting...",
|
||||
"recovering_token": "Recovering session...",
|
||||
]
|
||||
|
||||
private static let germanStrings: [String: String] = [
|
||||
// Home View
|
||||
"current_lesson": "Aktuelle Stunde",
|
||||
"next": "Nächste",
|
||||
"break": "Pause",
|
||||
"next_lesson": "Nächste: %@",
|
||||
"first_lesson": "Erste Stunde",
|
||||
"today_lessons_count": "Du hast heute %d Stunden",
|
||||
"no_more_lessons": "Keine Stunden mehr heute",
|
||||
"pair_with_iphone": "Mit iPhone koppeln",
|
||||
"open_firka_on_iphone": "Öffne Firka auf deinem iPhone",
|
||||
"login_on_iphone": "Auf iPhone anmelden",
|
||||
"open_and_login_on_iphone": "Öffne Firka auf deinem iPhone und melde dich mit einem Konto an",
|
||||
"updated": "Aktualisiert: %@",
|
||||
"minutes": "Min",
|
||||
"time_now": "jetzt",
|
||||
"time_hours_minutes": "%d Std %d Min",
|
||||
"time_hours": "%d Stunden",
|
||||
"time_minutes_only": "%d Min",
|
||||
"time_since_minutes_one": "vor 1 Min",
|
||||
"time_since_minutes_many": "vor %d Min",
|
||||
"time_since_hours_one": "vor 1 Std",
|
||||
"time_since_hours_many": "vor %d Std",
|
||||
"time_since_days_one": "vor 1 Tag",
|
||||
"time_since_days_many": "vor %d Tagen",
|
||||
|
||||
// Timetable View
|
||||
"free_day": "Freier Tag",
|
||||
"lesson_number": "%d. Stunde",
|
||||
"day_mon": "Mo",
|
||||
"day_tue": "Di",
|
||||
"day_wed": "Mi",
|
||||
"day_thu": "Do",
|
||||
"day_fri": "Fr",
|
||||
|
||||
// Grades View
|
||||
"grades_count": "%d Noten",
|
||||
"total_average": "Gesamtdurchschnitt",
|
||||
"average": "Durchschnitt:",
|
||||
"no_data": "Keine Daten",
|
||||
"no_grades": "Keine Noten",
|
||||
|
||||
// Lesson Detail
|
||||
"lesson_details": "Stundendetails",
|
||||
"cancelled": "Entfällt",
|
||||
"substitution": "Vertretung",
|
||||
"teacher": "Lehrer",
|
||||
"room": "Raum",
|
||||
"topic": "Thema",
|
||||
|
||||
// Settings
|
||||
"settings": "Einstellungen",
|
||||
"refresh_interval": "Aktualisierungsintervall",
|
||||
"auto": "Automatisch",
|
||||
"15_minutes": "15 Minuten",
|
||||
"30_minutes": "30 Minuten",
|
||||
"1_hour": "1 Stunde",
|
||||
"version": "Version",
|
||||
"language": "Sprache",
|
||||
"sync_with_iphone": "Mit iPhone synchronisieren",
|
||||
"clear_cache": "Cache löschen",
|
||||
"logout": "Abmelden",
|
||||
|
||||
// Refresh
|
||||
"refresh": "Aktualisieren",
|
||||
"refreshing": "Wird aktualisiert...",
|
||||
"refresh_success": "Erfolgreich!",
|
||||
"refresh_failed": "Fehlgeschlagen",
|
||||
"error_api": "Kréta API Fehler",
|
||||
"error_network": "Netzwerkfehler",
|
||||
|
||||
// Date labels
|
||||
"tomorrow_first_lesson": "Morgen erste Stunde",
|
||||
"day_first_lesson": "%@ erste Stunde",
|
||||
"next_school_day": "Nächster Schultag",
|
||||
|
||||
// Navigation
|
||||
"home": "Startseite",
|
||||
"timetable": "Stundenplan",
|
||||
"grades": "Noten",
|
||||
|
||||
// Reauth
|
||||
"reauth_required": "Erneute Anmeldung erforderlich",
|
||||
"reauth_description": "Ihre Sitzung ist abgelaufen. Bitte melden Sie sich erneut auf dem iPhone an.",
|
||||
"sync_button": "Synchronisieren",
|
||||
"syncing": "Synchronisierung...",
|
||||
"sync_success": "Erfolgreich!",
|
||||
"sync_failed": "Fehlgeschlagen",
|
||||
"phone_not_reachable": "iPhone nicht erreichbar",
|
||||
"connecting": "Verbindung...",
|
||||
"recovering_token": "Sitzung wiederherstellen...",
|
||||
]
|
||||
}
|
||||
|
||||
extension String {
|
||||
var localized: String {
|
||||
WatchL10n.shared.string(self)
|
||||
}
|
||||
|
||||
func localized(_ args: CVarArg...) -> String {
|
||||
let format = WatchL10n.shared.string(self)
|
||||
return String(format: format, arguments: args)
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import Foundation
|
||||
import WatchKit
|
||||
import WidgetKit
|
||||
|
||||
class BackgroundRefreshManager {
|
||||
static let shared = BackgroundRefreshManager()
|
||||
|
||||
private init() {}
|
||||
|
||||
func scheduleNextRefresh() {
|
||||
let interval = calculateOptimalRefreshInterval()
|
||||
|
||||
let preferredDate = Date().addingTimeInterval(interval)
|
||||
WKApplication.shared().scheduleBackgroundRefresh(
|
||||
withPreferredDate: preferredDate,
|
||||
userInfo: nil
|
||||
) { error in
|
||||
if let error = error {
|
||||
print("[BackgroundRefresh] Schedule error: \(error)")
|
||||
} else {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm"
|
||||
print("[BackgroundRefresh] Next refresh scheduled at: \(formatter.string(from: preferredDate)) (\(Int(interval/60)) min)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func calculateOptimalRefreshInterval() -> TimeInterval {
|
||||
let userRefreshMinutes = UserDefaults.standard.integer(forKey: "refreshInterval")
|
||||
let now = Date()
|
||||
let calendar = Calendar.current
|
||||
|
||||
let todayLessons = getTodayLessons()
|
||||
|
||||
guard !todayLessons.isEmpty else {
|
||||
return getDefaultInterval(userSetting: userRefreshMinutes, now: now, calendar: calendar)
|
||||
}
|
||||
|
||||
let sortedLessons = todayLessons.sorted { $0.start < $1.start }
|
||||
|
||||
guard let firstLesson = sortedLessons.first,
|
||||
let lastLesson = sortedLessons.last else {
|
||||
return getDefaultInterval(userSetting: userRefreshMinutes, now: now, calendar: calendar)
|
||||
}
|
||||
|
||||
let firstStart = firstLesson.start
|
||||
let lastEnd = lastLesson.end
|
||||
|
||||
let schoolStartBuffer = firstStart.addingTimeInterval(-30 * 60)
|
||||
|
||||
if now < schoolStartBuffer {
|
||||
let intervalUntilWakeUp = schoolStartBuffer.timeIntervalSince(now)
|
||||
let interval = max(intervalUntilWakeUp, 15 * 60)
|
||||
print("[BackgroundRefresh] Before school - next refresh in \(Int(interval/60)) min (30 min before first lesson)")
|
||||
return min(interval, 60 * 60) // Max 1 hour
|
||||
}
|
||||
|
||||
if now >= schoolStartBuffer && now <= lastEnd {
|
||||
let interval = TimeInterval((userRefreshMinutes > 0 ? userRefreshMinutes : 15) * 60)
|
||||
print("[BackgroundRefresh] During school - using \(Int(interval/60)) min interval")
|
||||
return interval
|
||||
}
|
||||
|
||||
let tomorrowLessons = getTomorrowLessons()
|
||||
if !tomorrowLessons.isEmpty,
|
||||
let tomorrowFirst = tomorrowLessons.sorted(by: { $0.start < $1.start }).first {
|
||||
|
||||
let tomorrowStartBuffer = tomorrowFirst.start.addingTimeInterval(-30 * 60)
|
||||
let timeUntilTomorrowWakeUp = tomorrowStartBuffer.timeIntervalSince(now)
|
||||
|
||||
if timeUntilTomorrowWakeUp > 2 * 60 * 60 {
|
||||
print("[BackgroundRefresh] After school - 1 hour interval (tomorrow's first lesson in \(Int(timeUntilTomorrowWakeUp/60)) min)")
|
||||
return 60 * 60
|
||||
} else {
|
||||
print("[BackgroundRefresh] After school, tomorrow soon - 30 min interval")
|
||||
return 30 * 60
|
||||
}
|
||||
}
|
||||
|
||||
print("[BackgroundRefresh] After school, no tomorrow lessons - 1 hour interval")
|
||||
return 60 * 60
|
||||
}
|
||||
|
||||
private func getDefaultInterval(userSetting: Int, now: Date, calendar: Calendar) -> TimeInterval {
|
||||
if userSetting > 0 {
|
||||
print("[BackgroundRefresh] No timetable - using user setting: \(userSetting) min")
|
||||
return TimeInterval(userSetting * 60)
|
||||
}
|
||||
|
||||
let hour = calendar.component(.hour, from: now)
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let isWeekday = weekday >= 2 && weekday <= 6
|
||||
|
||||
if isWeekday && hour >= 6 && hour <= 16 {
|
||||
print("[BackgroundRefresh] No timetable - weekday school hours: 15 min")
|
||||
return 15 * 60
|
||||
} else {
|
||||
print("[BackgroundRefresh] No timetable - off hours: 1 hour")
|
||||
return 60 * 60
|
||||
}
|
||||
}
|
||||
|
||||
private func getTodayLessons() -> [WidgetLesson] {
|
||||
guard let data = DataStore.shared.data else { return [] }
|
||||
return data.timetable.today
|
||||
}
|
||||
|
||||
private func getTomorrowLessons() -> [WidgetLesson] {
|
||||
guard let data = DataStore.shared.data else { return [] }
|
||||
return data.timetable.tomorrow
|
||||
}
|
||||
|
||||
func handleBackgroundRefresh() async {
|
||||
await DataStore.shared.refreshAllWithRecovery()
|
||||
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
|
||||
scheduleNextRefresh()
|
||||
}
|
||||
}
|
||||
@@ -1,551 +0,0 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import WidgetKit
|
||||
|
||||
// MARK: - Cache Wrapper
|
||||
|
||||
struct CachedWatchData: Codable {
|
||||
let widgetData: WidgetData
|
||||
let lastUpdated: Date
|
||||
}
|
||||
|
||||
// MARK: - DataStore
|
||||
|
||||
@Observable
|
||||
class DataStore {
|
||||
static let shared = DataStore()
|
||||
|
||||
var data: WidgetData?
|
||||
var lastUpdated: Date?
|
||||
var isLoading: Bool = false
|
||||
var error: String?
|
||||
|
||||
var isRecoveringToken: Bool = false
|
||||
|
||||
private(set) var recoveryAttempted: Bool = false
|
||||
|
||||
private(set) var hasToken: Bool = false
|
||||
|
||||
var needsReauth: Bool {
|
||||
(error == "token_expired" || error == "no_token") && recoveryAttempted && !isRecoveringToken
|
||||
}
|
||||
|
||||
private let appGroupID = "group.app.firka.firkaa"
|
||||
private let cacheFileName = "watch_data.json"
|
||||
private let lastHandledSessionStateVersionKey = "firka.watch.last_handled_session_state_version"
|
||||
private let lastHandledSessionActiveStudentIdNormKey = "firka.watch.last_handled_session_active_student_id_norm"
|
||||
|
||||
private init() {
|
||||
checkTokenState()
|
||||
loadFromCache()
|
||||
}
|
||||
|
||||
|
||||
var hasValidToken: Bool {
|
||||
TokenManager.shared.loadToken() != nil
|
||||
}
|
||||
|
||||
func checkTokenState() {
|
||||
hasToken = TokenManager.shared.loadToken() != nil
|
||||
print("[Watch] Token state updated: hasToken = \(hasToken)")
|
||||
}
|
||||
|
||||
private func parseInt64(_ value: Any?) -> Int64? {
|
||||
if let value = value as? Int64 { return value }
|
||||
if let value = value as? Int { return Int64(value) }
|
||||
if let value = value as? Double { return Int64(value) }
|
||||
if let value = value as? String, let parsed = Int64(value) { return parsed }
|
||||
return nil
|
||||
}
|
||||
|
||||
private func lastHandledSessionStateVersion() -> Int64 {
|
||||
parseInt64(UserDefaults.standard.object(forKey: lastHandledSessionStateVersionKey)) ?? 0
|
||||
}
|
||||
|
||||
private func setLastHandledSessionStateVersion(_ value: Int64) {
|
||||
UserDefaults.standard.set(value, forKey: lastHandledSessionStateVersionKey)
|
||||
}
|
||||
|
||||
private func lastHandledSessionActiveStudentIdNorm() -> Int64? {
|
||||
parseInt64(UserDefaults.standard.object(forKey: lastHandledSessionActiveStudentIdNormKey))
|
||||
}
|
||||
|
||||
private func setLastHandledSessionActiveStudentIdNorm(_ value: Int64?) {
|
||||
if let value {
|
||||
UserDefaults.standard.set(value, forKey: lastHandledSessionActiveStudentIdNormKey)
|
||||
} else {
|
||||
UserDefaults.standard.removeObject(forKey: lastHandledSessionActiveStudentIdNormKey)
|
||||
}
|
||||
}
|
||||
|
||||
func reconcileSharedSessionState() {
|
||||
guard let state = SharedSessionStateManager.shared.loadState() else {
|
||||
return
|
||||
}
|
||||
|
||||
let lastVersion = lastHandledSessionStateVersion()
|
||||
guard state.stateVersion > lastVersion else {
|
||||
return
|
||||
}
|
||||
|
||||
if !state.hasAnyAccount {
|
||||
print("[Watch] Shared session state: no active iPhone account, clearing watch state")
|
||||
clearAll()
|
||||
resetRecoveryState()
|
||||
setLastHandledSessionStateVersion(state.stateVersion)
|
||||
setLastHandledSessionActiveStudentIdNorm(nil)
|
||||
return
|
||||
}
|
||||
|
||||
if let activeStudentIdNorm = state.activeStudentIdNorm {
|
||||
let lastHandledActiveStudentIdNorm = lastHandledSessionActiveStudentIdNorm()
|
||||
if lastHandledActiveStudentIdNorm != activeStudentIdNorm {
|
||||
print("[Watch] Shared session switched active account to \(activeStudentIdNorm), clearing stale cache")
|
||||
clearCache()
|
||||
data = nil
|
||||
lastUpdated = nil
|
||||
error = nil
|
||||
recoveryAttempted = false
|
||||
WatchL10n.shared.resetLanguageVersionTracking()
|
||||
}
|
||||
setLastHandledSessionActiveStudentIdNorm(activeStudentIdNorm)
|
||||
} else {
|
||||
setLastHandledSessionActiveStudentIdNorm(nil)
|
||||
}
|
||||
|
||||
setLastHandledSessionStateVersion(state.stateVersion)
|
||||
checkTokenState()
|
||||
}
|
||||
|
||||
// MARK: - Cache Loading
|
||||
|
||||
func loadFromCache() {
|
||||
if let widgetData = WidgetData.load() {
|
||||
self.data = widgetData
|
||||
self.lastUpdated = widgetData.lastUpdated
|
||||
return
|
||||
}
|
||||
|
||||
guard let cachedData = loadWatchCache() else {
|
||||
return
|
||||
}
|
||||
|
||||
self.data = cachedData.widgetData
|
||||
self.lastUpdated = cachedData.lastUpdated
|
||||
}
|
||||
|
||||
private func loadWatchCache() -> CachedWatchData? {
|
||||
guard let containerURL = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: appGroupID
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let fileURL = containerURL.appendingPathComponent(cacheFileName)
|
||||
|
||||
guard let cacheData = try? Data(contentsOf: fileURL) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
|
||||
return try? decoder.decode(CachedWatchData.self, from: cacheData)
|
||||
}
|
||||
|
||||
private func saveToCache(_ data: WidgetData) {
|
||||
guard let containerURL = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: appGroupID
|
||||
) else {
|
||||
return
|
||||
}
|
||||
|
||||
let fileURL = containerURL.appendingPathComponent(cacheFileName)
|
||||
let cached = CachedWatchData(widgetData: data, lastUpdated: Date())
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .iso8601
|
||||
|
||||
do {
|
||||
let encodedData = try encoder.encode(cached)
|
||||
try encodedData.write(to: fileURL)
|
||||
} catch {
|
||||
self.error = "Failed to save cache"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cache Management
|
||||
|
||||
func clearCache() {
|
||||
guard let containerURL = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: appGroupID
|
||||
) else { return }
|
||||
|
||||
let fileURL = containerURL.appendingPathComponent(cacheFileName)
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
|
||||
data = nil
|
||||
lastUpdated = nil
|
||||
|
||||
print("[Watch] Cache cleared")
|
||||
}
|
||||
|
||||
func clearAll() {
|
||||
clearCache()
|
||||
error = nil
|
||||
isLoading = false
|
||||
checkTokenState()
|
||||
|
||||
print("[Watch] All data cleared")
|
||||
}
|
||||
|
||||
func clearError() {
|
||||
error = nil
|
||||
print("[Watch] Error cleared")
|
||||
}
|
||||
|
||||
func setReauthRequired() {
|
||||
error = "token_expired"
|
||||
print("[Watch] Reauth required state set")
|
||||
}
|
||||
|
||||
func resetRecoveryState() {
|
||||
recoveryAttempted = false
|
||||
error = nil
|
||||
print("[Watch] Recovery state reset")
|
||||
}
|
||||
|
||||
func attemptTokenRecovery() async -> Bool {
|
||||
guard !isRecoveringToken else {
|
||||
print("[Watch] Token recovery already in progress")
|
||||
return false
|
||||
}
|
||||
|
||||
isRecoveringToken = true
|
||||
recoveryAttempted = false
|
||||
error = nil
|
||||
print("[Watch] Starting token recovery via central method...")
|
||||
|
||||
defer {
|
||||
isRecoveringToken = false
|
||||
}
|
||||
|
||||
if let token = TokenManager.shared.loadToken(), !TokenManager.shared.isTokenExpired() {
|
||||
print("[Watch] Recovery: Token is already valid")
|
||||
checkTokenState()
|
||||
return true
|
||||
}
|
||||
|
||||
if let _ = await TokenManager.shared.recoverToken() {
|
||||
print("[Watch] Recovery: Central recovery succeeded")
|
||||
checkTokenState()
|
||||
return true
|
||||
}
|
||||
|
||||
print("[Watch] Recovery: All attempts failed")
|
||||
recoveryAttempted = true
|
||||
self.error = "token_expired"
|
||||
return false
|
||||
}
|
||||
|
||||
private func refreshComplications() {
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
print("[Watch] Complications refreshed")
|
||||
}
|
||||
|
||||
// MARK: - Proactive Token Refresh
|
||||
|
||||
func refreshTokenProactively() async {
|
||||
guard hasValidToken else { return }
|
||||
await TokenManager.shared.refreshTokenProactively()
|
||||
checkTokenState()
|
||||
}
|
||||
|
||||
// MARK: - Data Refresh
|
||||
|
||||
func refreshAll() async {
|
||||
guard !isLoading else {
|
||||
print("[Watch] DataStore.refreshAll() already in progress, skipping duplicate call")
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] DataStore.refreshAll() called")
|
||||
isLoading = true
|
||||
error = nil
|
||||
|
||||
defer { isLoading = false }
|
||||
|
||||
await TokenManager.shared.refreshTokenProactively()
|
||||
|
||||
guard hasValidToken else {
|
||||
print("[Watch] No valid token, setting error = no_token")
|
||||
error = "no_token"
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let (startOfWeek, endOfWeek) = getCurrentWeekDateRange()
|
||||
|
||||
async let timetableTask = KretaAPIClient.shared.fetchTimetable(
|
||||
from: startOfWeek,
|
||||
to: endOfWeek
|
||||
)
|
||||
async let gradesTask = KretaAPIClient.shared.fetchGrades()
|
||||
|
||||
let (lessons, grades) = try await (timetableTask, gradesTask)
|
||||
|
||||
let timetableData = buildTimetableData(from: lessons)
|
||||
let averagesData = buildAveragesData(from: grades)
|
||||
|
||||
let widgetData = WidgetData(
|
||||
lastUpdated: Date(),
|
||||
locale: Locale.current.language.languageCode?.identifier ?? "hu",
|
||||
theme: "dark",
|
||||
timetable: timetableData,
|
||||
grades: grades,
|
||||
averages: averagesData
|
||||
)
|
||||
|
||||
self.data = widgetData
|
||||
self.lastUpdated = Date()
|
||||
|
||||
saveToCache(widgetData)
|
||||
|
||||
refreshComplications()
|
||||
|
||||
print("[Watch] refreshAll() completed successfully")
|
||||
|
||||
} catch let error as APIError {
|
||||
handleAPIError(error)
|
||||
} catch {
|
||||
print("[Watch] refreshAll() network error: \(error)")
|
||||
self.error = "network"
|
||||
}
|
||||
}
|
||||
|
||||
private var isRecoveryInProgress: Bool = false
|
||||
|
||||
func refreshAllWithRecovery() async {
|
||||
guard !isRecoveryInProgress && !isLoading else {
|
||||
print("[Watch] refreshAllWithRecovery() already in progress or refreshAll() running, skipping duplicate call")
|
||||
return
|
||||
}
|
||||
isRecoveryInProgress = true
|
||||
defer { isRecoveryInProgress = false }
|
||||
|
||||
reconcileSharedSessionState()
|
||||
WatchL10n.shared.refreshFromiPhoneAndSharedState()
|
||||
|
||||
let sharedActiveStudentIdNorm = SharedSessionStateManager.shared.loadState()?.activeStudentIdNorm
|
||||
let localStudentIdNorm = TokenManager.shared.loadToken()?.studentIdNorm
|
||||
let shouldRequestTokenFromPhone =
|
||||
!hasValidToken ||
|
||||
(sharedActiveStudentIdNorm != nil && localStudentIdNorm != sharedActiveStudentIdNorm)
|
||||
|
||||
if shouldRequestTokenFromPhone {
|
||||
WatchConnectivityManager.shared.requestTokenFromPhone()
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
checkTokenState()
|
||||
}
|
||||
|
||||
await refreshAll()
|
||||
|
||||
guard error == "token_expired" || error == "no_token" else {
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] Token issue after refreshAll(), starting auto-recovery flow...")
|
||||
let recovered = await attemptTokenRecovery()
|
||||
if recovered {
|
||||
await refreshAll()
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles API errors and maps them to user-friendly messages
|
||||
private func handleAPIError(_ error: APIError) {
|
||||
print("[Watch] handleAPIError: \(error)")
|
||||
switch error {
|
||||
case .tokenError(let tokenError):
|
||||
switch tokenError {
|
||||
case .noToken:
|
||||
print("[Watch] Setting error = no_token")
|
||||
self.error = "no_token"
|
||||
case .refreshExpired, .invalidGrant:
|
||||
print("[Watch] Setting error = token_expired")
|
||||
self.error = "token_expired"
|
||||
case .invalidResponse, .networkError:
|
||||
print("[Watch] Setting error = network (token error)")
|
||||
self.error = "network"
|
||||
}
|
||||
case .unauthorized:
|
||||
print("[Watch] Setting error = token_expired (unauthorized)")
|
||||
self.error = "token_expired"
|
||||
case .requestFailed(let statusCode):
|
||||
if statusCode >= 500 {
|
||||
print("[Watch] Setting error = api_error (server error \(statusCode))")
|
||||
self.error = "api_error"
|
||||
} else {
|
||||
print("[Watch] Setting error = network (request failed \(statusCode))")
|
||||
self.error = "network"
|
||||
}
|
||||
case .decodingFailed, .invalidURL:
|
||||
print("[Watch] Setting error = network")
|
||||
self.error = "network"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data Processing
|
||||
|
||||
private func buildTimetableData(from lessons: [WidgetLesson]) -> TimetableData {
|
||||
let today = Date()
|
||||
let todayString = formatDateForComparison(today)
|
||||
let tomorrowString = formatDateForComparison(today.addingTimeInterval(86400))
|
||||
|
||||
let todayLessons = lessons.filter { $0.date == todayString }.sorted { $0.start < $1.start }
|
||||
let tomorrowLessons = lessons.filter { $0.date == tomorrowString }.sorted { $0.start < $1.start }
|
||||
|
||||
var nextSchoolDayLessons: [WidgetLesson]? = nil
|
||||
var nextSchoolDayDateString: String? = nil
|
||||
|
||||
for daysOffset in 2...14 {
|
||||
let checkDate = today.addingTimeInterval(TimeInterval(daysOffset * 86400))
|
||||
let checkDateString = formatDateForComparison(checkDate)
|
||||
let checkLessons = lessons.filter { $0.date == checkDateString }
|
||||
|
||||
if !checkLessons.isEmpty {
|
||||
nextSchoolDayLessons = checkLessons.sorted { $0.start < $1.start }
|
||||
nextSchoolDayDateString = checkDateString
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
let currentBreak: BreakInfo? = nil
|
||||
|
||||
return TimetableData(
|
||||
today: todayLessons,
|
||||
tomorrow: tomorrowLessons,
|
||||
nextSchoolDay: nextSchoolDayLessons,
|
||||
nextSchoolDayDate: nextSchoolDayDateString,
|
||||
currentBreak: currentBreak,
|
||||
allLessons: lessons
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds AveragesData from grades (matching Flutter's calculation)
|
||||
private func buildAveragesData(from grades: [WidgetGrade]) -> AveragesData {
|
||||
guard !grades.isEmpty else {
|
||||
return AveragesData(overall: nil, subjects: [])
|
||||
}
|
||||
|
||||
var subjectGradesMap: [String: [(value: Int, weight: Double)]] = [:]
|
||||
|
||||
for grade in grades {
|
||||
if let numeric = grade.normalizedNumericValue {
|
||||
let key = grade.subject.uid
|
||||
let weight = Double(grade.weightPercentage ?? 100) / 100.0
|
||||
subjectGradesMap[key, default: []].append((value: numeric, weight: weight))
|
||||
}
|
||||
}
|
||||
|
||||
var subjectAverages: [SubjectAverage] = []
|
||||
|
||||
for (uid, gradeValues) in subjectGradesMap {
|
||||
if let firstGrade = grades.first(where: { $0.subject.uid == uid }) {
|
||||
var weightedSum = 0.0
|
||||
var totalWeight = 0.0
|
||||
|
||||
for (value, weight) in gradeValues {
|
||||
weightedSum += Double(value) * weight
|
||||
totalWeight += weight
|
||||
}
|
||||
|
||||
let average = totalWeight > 0 ? weightedSum / totalWeight : Double.nan
|
||||
|
||||
if !average.isNaN {
|
||||
subjectAverages.append(
|
||||
SubjectAverage(
|
||||
uid: uid,
|
||||
name: firstGrade.subject.name,
|
||||
average: average,
|
||||
gradeCount: gradeValues.count
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let overall: Double?
|
||||
if !subjectAverages.isEmpty {
|
||||
let sumOfAverages = subjectAverages.reduce(0.0) { $0 + $1.average }
|
||||
overall = sumOfAverages / Double(subjectAverages.count)
|
||||
} else {
|
||||
overall = nil
|
||||
}
|
||||
|
||||
return AveragesData(overall: overall, subjects: subjectAverages)
|
||||
}
|
||||
|
||||
private func getCurrentWeekDateRange() -> (start: Date, end: Date) {
|
||||
let calendar = Calendar.current
|
||||
let today = Date()
|
||||
|
||||
let weekday = calendar.component(.weekday, from: today)
|
||||
let daysToMonday = weekday == 1 ? -6 : (2 - weekday)
|
||||
let monday = calendar.date(byAdding: .day, value: daysToMonday, to: today)!
|
||||
|
||||
let nextSunday = calendar.date(byAdding: .day, value: 13, to: monday)!
|
||||
|
||||
return (monday, nextSunday)
|
||||
}
|
||||
|
||||
private func formatDateForComparison(_ date: Date) -> String {
|
||||
let calendar = Calendar.current
|
||||
let components = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
return String(format: "%04d-%02d-%02d",
|
||||
components.year ?? 0,
|
||||
components.month ?? 0,
|
||||
components.day ?? 0)
|
||||
}
|
||||
|
||||
// MARK: - Computed Helpers
|
||||
|
||||
var timeSinceUpdate: String? {
|
||||
guard let lastUpdated = lastUpdated else { return nil }
|
||||
|
||||
let elapsed = Date().timeIntervalSince(lastUpdated)
|
||||
|
||||
if elapsed < 60 {
|
||||
return "time_now".localized
|
||||
}
|
||||
|
||||
// Minutes
|
||||
let minutes = Int(elapsed / 60)
|
||||
if minutes < 60 {
|
||||
return minutes == 1
|
||||
? "time_since_minutes_one".localized
|
||||
: "time_since_minutes_many".localized(minutes)
|
||||
}
|
||||
|
||||
// Hours
|
||||
let hours = Int(elapsed / 3600)
|
||||
if hours < 24 {
|
||||
return hours == 1
|
||||
? "time_since_hours_one".localized
|
||||
: "time_since_hours_many".localized(hours)
|
||||
}
|
||||
|
||||
// Days
|
||||
let days = Int(elapsed / 86400)
|
||||
return days == 1
|
||||
? "time_since_days_one".localized
|
||||
: "time_since_days_many".localized(days)
|
||||
}
|
||||
|
||||
/// Returns true if data is stale (> 1 hour old or never updated)
|
||||
var isStale: Bool {
|
||||
guard let lastUpdated = lastUpdated else { return true }
|
||||
|
||||
let elapsed = Date().timeIntervalSince(lastUpdated)
|
||||
return elapsed > 3600 // 1 hour
|
||||
}
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
import Foundation
|
||||
import WatchConnectivity
|
||||
|
||||
class WatchConnectivityManager: NSObject, WCSessionDelegate {
|
||||
static let shared = WatchConnectivityManager()
|
||||
private let lastAppliedTokenUpdateKey = "watch_last_applied_token_update_ms"
|
||||
private let minPhoneTokenRequestInterval: TimeInterval = 5
|
||||
private var lastPhoneTokenRequestAt: Date?
|
||||
|
||||
private override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
private var lastAppliedTokenUpdateMs: Int64 {
|
||||
get {
|
||||
Int64(UserDefaults.standard.double(forKey: lastAppliedTokenUpdateKey))
|
||||
}
|
||||
set {
|
||||
UserDefaults.standard.set(Double(newValue), forKey: lastAppliedTokenUpdateKey)
|
||||
}
|
||||
}
|
||||
|
||||
private func extractSentAtMs(from authDict: [String: Any]) -> Int64? {
|
||||
if let value = authDict["sentAtMs"] as? Int64 {
|
||||
return value
|
||||
}
|
||||
if let value = authDict["sentAtMs"] as? Int {
|
||||
return Int64(value)
|
||||
}
|
||||
if let value = authDict["sentAtMs"] as? Double {
|
||||
return Int64(value)
|
||||
}
|
||||
if let value = authDict["sentAtMs"] as? String,
|
||||
let parsed = Int64(value) {
|
||||
return parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func parseInt64(_ value: Any?) -> Int64? {
|
||||
if let value = value as? Int64 {
|
||||
return value
|
||||
}
|
||||
if let value = value as? Int {
|
||||
return Int64(value)
|
||||
}
|
||||
if let value = value as? Double {
|
||||
return Int64(value)
|
||||
}
|
||||
if let value = value as? String, let parsed = Int64(value) {
|
||||
return parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func activate() {
|
||||
print("[Watch] WatchConnectivityManager.activate() called")
|
||||
if WCSession.isSupported() {
|
||||
print("[Watch] WCSession is supported, activating...")
|
||||
WCSession.default.delegate = self
|
||||
WCSession.default.activate()
|
||||
} else {
|
||||
print("[Watch] WCSession is NOT supported!")
|
||||
}
|
||||
}
|
||||
|
||||
func session(
|
||||
_ session: WCSession,
|
||||
activationDidCompleteWith activationState: WCSessionActivationState,
|
||||
error: Error?
|
||||
) {
|
||||
print("[Watch] Session activation completed with state: \(activationState.rawValue)")
|
||||
if let error = error {
|
||||
print("[Watch] Activation error: \(error.localizedDescription)")
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
if activationState == .activated {
|
||||
let context = session.receivedApplicationContext
|
||||
if !context.isEmpty {
|
||||
self.processApplicationContext(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func session(
|
||||
_ session: WCSession,
|
||||
didReceiveApplicationContext applicationContext: [String: Any]
|
||||
) {
|
||||
print("[Watch] didReceiveApplicationContext called")
|
||||
DispatchQueue.main.async {
|
||||
self.processApplicationContext(applicationContext)
|
||||
}
|
||||
}
|
||||
|
||||
func session(
|
||||
_ session: WCSession,
|
||||
didReceiveUserInfo userInfo: [String: Any] = [:]
|
||||
) {
|
||||
print("[Watch] didReceiveUserInfo called")
|
||||
DispatchQueue.main.async {
|
||||
self.processUserInfo(userInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func session(
|
||||
_ session: WCSession,
|
||||
didReceiveMessage message: [String: Any],
|
||||
replyHandler: @escaping ([String: Any]) -> Void
|
||||
) {
|
||||
print("[Watch] didReceiveMessage called: \(message)")
|
||||
|
||||
if let messageId = message["id"] as? String, messageId == "token_update" {
|
||||
if let authDict = message["auth"] as? [String: Any] {
|
||||
print("[Watch] Received immediate token_update via sendMessage")
|
||||
processAuthData(authDict)
|
||||
replyHandler(["success": true])
|
||||
} else {
|
||||
replyHandler(["error": "no_auth"])
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let action = message["action"] as? String else {
|
||||
replyHandler(["error": "no_action"])
|
||||
return
|
||||
}
|
||||
|
||||
switch action {
|
||||
case "getToken":
|
||||
handleGetTokenRequest(replyHandler: replyHandler)
|
||||
default:
|
||||
replyHandler(["error": "unknown_action"])
|
||||
}
|
||||
}
|
||||
|
||||
private func handleGetTokenRequest(replyHandler: @escaping ([String: Any]) -> Void) {
|
||||
guard TokenManager.shared.loadToken() != nil else {
|
||||
print("[Watch] No token to send to iPhone")
|
||||
replyHandler(["error": "no_token"])
|
||||
return
|
||||
}
|
||||
|
||||
if TokenManager.shared.isTokenExpired() {
|
||||
print("[Watch] Token expired, attempting refresh before sending to iPhone...")
|
||||
Task {
|
||||
do {
|
||||
let freshToken = try await KretaAPIClient.shared.getValidToken()
|
||||
print("[Watch] Token refresh succeeded, sending fresh token to iPhone")
|
||||
|
||||
var tokenData: [String: Any] = [
|
||||
"studentId": freshToken.studentId,
|
||||
"studentIdNorm": freshToken.studentIdNorm,
|
||||
"iss": freshToken.iss,
|
||||
"idToken": freshToken.idToken,
|
||||
"accessToken": freshToken.accessToken,
|
||||
"refreshToken": freshToken.refreshToken,
|
||||
"expiryDate": Int64(freshToken.expiryDate.timeIntervalSince1970 * 1000)
|
||||
]
|
||||
if let tokenVersion = freshToken.effectiveTokenVersion {
|
||||
tokenData["tokenVersion"] = tokenVersion
|
||||
}
|
||||
tokenData["updatedAtMs"] = freshToken.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000)
|
||||
|
||||
replyHandler(["token": tokenData])
|
||||
} catch {
|
||||
print("[Watch] Token refresh failed after all retries: \(error)")
|
||||
replyHandler(["error": "refresh_failed"])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let token = TokenManager.shared.loadToken() else {
|
||||
replyHandler(["error": "no_token"])
|
||||
return
|
||||
}
|
||||
|
||||
var tokenData: [String: Any] = [
|
||||
"studentId": token.studentId,
|
||||
"studentIdNorm": token.studentIdNorm,
|
||||
"iss": token.iss,
|
||||
"idToken": token.idToken,
|
||||
"accessToken": token.accessToken,
|
||||
"refreshToken": token.refreshToken,
|
||||
"expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000)
|
||||
]
|
||||
if let tokenVersion = token.effectiveTokenVersion {
|
||||
tokenData["tokenVersion"] = tokenVersion
|
||||
}
|
||||
tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000)
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm:ss"
|
||||
formatter.timeZone = TimeZone.current
|
||||
print("[Watch] Sending token to iPhone, expiry: \(formatter.string(from: token.expiryDate))")
|
||||
replyHandler(["token": tokenData])
|
||||
}
|
||||
|
||||
func requestTokenFromPhone() {
|
||||
guard WCSession.default.activationState == .activated else {
|
||||
print("[Watch] Cannot request token: session not activated")
|
||||
return
|
||||
}
|
||||
|
||||
guard WCSession.default.isReachable else {
|
||||
print("[Watch] Cannot request token: iPhone not reachable")
|
||||
return
|
||||
}
|
||||
|
||||
let now = Date()
|
||||
if let lastPhoneTokenRequestAt,
|
||||
now.timeIntervalSince(lastPhoneTokenRequestAt) < minPhoneTokenRequestInterval {
|
||||
print("[Watch] Skipping token request due to cooldown")
|
||||
return
|
||||
}
|
||||
lastPhoneTokenRequestAt = now
|
||||
|
||||
print("[Watch] Requesting token from iPhone...")
|
||||
|
||||
WCSession.default.sendMessage(
|
||||
["action": "requestToken"],
|
||||
replyHandler: { response in
|
||||
print("[Watch] Received response from iPhone")
|
||||
DispatchQueue.main.async {
|
||||
if let authDict = response["auth"] as? [String: Any] {
|
||||
print("[Watch] Token received from iPhone")
|
||||
self.processAuthData(authDict)
|
||||
} else if let error = response["error"] as? String {
|
||||
print("[Watch] Token request error: \(error)")
|
||||
}
|
||||
}
|
||||
},
|
||||
errorHandler: { error in
|
||||
print("[Watch] Token request failed: \(error.localizedDescription)")
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func processApplicationContext(_ context: [String: Any]) {
|
||||
if (context["force_logout"] as? Bool) == true {
|
||||
print("[Watch] Received force_logout via applicationContext")
|
||||
handleForceLogoutFromPhone()
|
||||
return
|
||||
}
|
||||
|
||||
if let authDict = context["auth"] as? [String: Any] {
|
||||
print("[Watch] Received auth from iPhone")
|
||||
processAuthData(authDict)
|
||||
}
|
||||
|
||||
if let language = context["language"] as? String {
|
||||
let sharedStateVersion =
|
||||
parseInt64(context["language_state_version"]) ??
|
||||
parseInt64(context["languageStateVersion"])
|
||||
print("[Watch] Received language from iPhone: \(language)")
|
||||
WatchL10n.shared.updateFromiPhone(
|
||||
languageCode: language,
|
||||
sharedStateVersion: sharedStateVersion
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func processUserInfo(_ userInfo: [String: Any]) {
|
||||
if let messageId = userInfo["id"] as? String {
|
||||
switch messageId {
|
||||
case "token_update":
|
||||
if let authDict = userInfo["auth"] as? [String: Any] {
|
||||
print("[Watch] Received token_update via userInfo")
|
||||
processAuthData(authDict)
|
||||
}
|
||||
case "language_update":
|
||||
if let language = userInfo["language"] as? String {
|
||||
let sharedStateVersion =
|
||||
parseInt64(userInfo["language_state_version"]) ??
|
||||
parseInt64(userInfo["languageStateVersion"])
|
||||
print("[Watch] Received language_update via userInfo: \(language)")
|
||||
WatchL10n.shared.updateFromiPhone(
|
||||
languageCode: language,
|
||||
sharedStateVersion: sharedStateVersion
|
||||
)
|
||||
}
|
||||
case "reauth_required":
|
||||
print("[Watch] Received reauth_required notification from iPhone")
|
||||
DataStore.shared.setReauthRequired()
|
||||
case "force_logout":
|
||||
print("[Watch] Received force_logout notification from iPhone")
|
||||
handleForceLogoutFromPhone()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleForceLogoutFromPhone() {
|
||||
TokenManager.shared.deleteToken()
|
||||
_ = SharedSessionStateManager.shared.publishState(
|
||||
hasAnyAccount: false,
|
||||
activeStudentIdNorm: nil
|
||||
)
|
||||
DataStore.shared.clearAll()
|
||||
DataStore.shared.resetRecoveryState()
|
||||
DataStore.shared.checkTokenState()
|
||||
}
|
||||
|
||||
func sendTokenToiPhoneInBackground() {
|
||||
guard WCSession.default.activationState == .activated else {
|
||||
print("[Watch] Cannot send token: session not activated")
|
||||
return
|
||||
}
|
||||
|
||||
guard let token = TokenManager.shared.loadToken() else {
|
||||
print("[Watch] No token to send to iPhone")
|
||||
return
|
||||
}
|
||||
|
||||
var tokenData: [String: Any] = [
|
||||
"studentId": token.studentId,
|
||||
"studentIdNorm": token.studentIdNorm,
|
||||
"iss": token.iss,
|
||||
"idToken": token.idToken,
|
||||
"accessToken": token.accessToken,
|
||||
"refreshToken": token.refreshToken,
|
||||
"expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000)
|
||||
]
|
||||
if let tokenVersion = token.effectiveTokenVersion {
|
||||
tokenData["tokenVersion"] = tokenVersion
|
||||
}
|
||||
tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000)
|
||||
|
||||
do {
|
||||
try WCSession.default.updateApplicationContext(["auth": tokenData])
|
||||
print("[Watch] Token sent via applicationContext")
|
||||
} catch {
|
||||
print("[Watch] Failed to update applicationContext: \(error)")
|
||||
}
|
||||
|
||||
WCSession.default.transferUserInfo([
|
||||
"id": "token_update_from_watch",
|
||||
"auth": tokenData
|
||||
])
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm:ss"
|
||||
formatter.timeZone = TimeZone.current
|
||||
print("[Watch] Token sent to iPhone (background), expiry: \(formatter.string(from: token.expiryDate))")
|
||||
}
|
||||
|
||||
func requestLanguageFromPhone() {
|
||||
guard WCSession.default.activationState == .activated else {
|
||||
print("[Watch] Cannot request language: session not activated")
|
||||
return
|
||||
}
|
||||
|
||||
guard WCSession.default.isReachable else {
|
||||
print("[Watch] Cannot request language: iPhone not reachable")
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] Requesting language from iPhone...")
|
||||
|
||||
WCSession.default.sendMessage(
|
||||
["action": "requestLanguage"],
|
||||
replyHandler: { response in
|
||||
print("[Watch] Received language response from iPhone")
|
||||
DispatchQueue.main.async {
|
||||
if let language = response["language"] as? String {
|
||||
let sharedStateVersion =
|
||||
self.parseInt64(response["language_state_version"]) ??
|
||||
self.parseInt64(response["languageStateVersion"])
|
||||
print("[Watch] Language received from iPhone: \(language)")
|
||||
WatchL10n.shared.updateFromiPhone(
|
||||
languageCode: language,
|
||||
sharedStateVersion: sharedStateVersion
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
errorHandler: { error in
|
||||
print("[Watch] Language request failed: \(error.localizedDescription)")
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func processAuthData(_ authDict: [String: Any]) {
|
||||
print("[Watch] processAuthData called")
|
||||
do {
|
||||
let incomingSentAtMs = extractSentAtMs(from: authDict) ?? 0
|
||||
let previousSentAtMs = lastAppliedTokenUpdateMs
|
||||
|
||||
if incomingSentAtMs > 0 && incomingSentAtMs < previousSentAtMs {
|
||||
print("[Watch] Ignoring stale token_update (sentAtMs: \(incomingSentAtMs), lastApplied: \(previousSentAtMs))")
|
||||
return
|
||||
}
|
||||
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: authDict)
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .custom { decoder in
|
||||
let container = try decoder.singleValueContainer()
|
||||
let timestamp = try container.decode(Int64.self)
|
||||
return Date(timeIntervalSince1970: Double(timestamp) / 1000.0)
|
||||
}
|
||||
|
||||
let token = try decoder.decode(WatchToken.self, from: jsonData)
|
||||
let currentToken = TokenManager.shared.loadToken()
|
||||
|
||||
let isAccountSwitch = currentToken != nil && !token.isSameAccount(as: currentToken!)
|
||||
let shouldForceAccountSwitch: Bool
|
||||
if isAccountSwitch {
|
||||
if incomingSentAtMs > 0 {
|
||||
shouldForceAccountSwitch = true
|
||||
} else {
|
||||
shouldForceAccountSwitch = token.isNewer(than: currentToken!)
|
||||
}
|
||||
} else {
|
||||
shouldForceAccountSwitch = false
|
||||
}
|
||||
|
||||
if incomingSentAtMs <= 0,
|
||||
let currentToken,
|
||||
!isAccountSwitch,
|
||||
!token.isNewer(than: currentToken) {
|
||||
print("[Watch] Ignoring stale token_update without sentAtMs (same account, not newer)")
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] Token decoded, saving... (sentAtMs: \(incomingSentAtMs), forceSwitch: \(shouldForceAccountSwitch))")
|
||||
|
||||
try TokenManager.shared.saveToken(
|
||||
token,
|
||||
syncToSharedKeychain: false,
|
||||
forceAccountSwitch: shouldForceAccountSwitch
|
||||
)
|
||||
print("[Watch] Token saved successfully")
|
||||
_ = SharedSessionStateManager.shared.publishState(
|
||||
hasAnyAccount: true,
|
||||
activeStudentIdNorm: token.studentIdNorm
|
||||
)
|
||||
if incomingSentAtMs > 0 {
|
||||
lastAppliedTokenUpdateMs = max(previousSentAtMs, incomingSentAtMs)
|
||||
}
|
||||
|
||||
DataStore.shared.clearError()
|
||||
DataStore.shared.resetRecoveryState()
|
||||
DataStore.shared.checkTokenState()
|
||||
|
||||
Task {
|
||||
await DataStore.shared.refreshAllWithRecovery()
|
||||
print("[Watch] Data refresh completed")
|
||||
}
|
||||
} catch {
|
||||
print("[Watch] Failed to process auth data: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GradeSubjectView: View {
|
||||
let subjectName: String
|
||||
let grades: [WidgetGrade]
|
||||
let average: Double
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
FirkaCard {
|
||||
HStack {
|
||||
Text("average".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
Text(String(format: "%.2f", average))
|
||||
.font(.headline)
|
||||
.fontWeight(.bold)
|
||||
.foregroundColor(averageColor(average))
|
||||
}
|
||||
}
|
||||
|
||||
ForEach(groupedGrades, id: \.date) { group in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(formatDate(group.date))
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
ForEach(group.grades) { grade in
|
||||
gradeRow(grade)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
.navigationTitle(subjectName)
|
||||
}
|
||||
|
||||
private var groupedGrades: [(date: Date, grades: [WidgetGrade])] {
|
||||
let calendar = Calendar.current
|
||||
let grouped = Dictionary(grouping: grades) { grade in
|
||||
calendar.startOfDay(for: grade.recordDate)
|
||||
}
|
||||
return grouped
|
||||
.map { (date: $0.key, grades: $0.value) }
|
||||
.sorted { $0.date > $1.date }
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func gradeRow(_ grade: WidgetGrade) -> some View {
|
||||
FirkaCard {
|
||||
HStack(alignment: .top, spacing: 10) {
|
||||
if let normalizedValue = grade.normalizedNumericValue {
|
||||
if grade.isPercentageGrade, let rawValue = grade.numericValue {
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(gradeColor(normalizedValue))
|
||||
.frame(width: 32, height: 32)
|
||||
Text("\(rawValue)%")
|
||||
.font(.system(size: 10, weight: .bold))
|
||||
.foregroundColor(.white)
|
||||
}
|
||||
} else {
|
||||
GradeBadge(grade: normalizedValue)
|
||||
}
|
||||
} else {
|
||||
Text(grade.displayValue)
|
||||
.font(.caption)
|
||||
.fontWeight(.bold)
|
||||
.padding(6)
|
||||
.background(Color.gray)
|
||||
.cornerRadius(12)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(grade.displayTypeWithWeight)
|
||||
.font(.subheadline)
|
||||
.fontWeight(.medium)
|
||||
|
||||
if let topic = grade.topic, !topic.isEmpty {
|
||||
Text(topic)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.lineLimit(2)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func gradeColor(_ value: Int) -> Color {
|
||||
switch value {
|
||||
case 5: return .green
|
||||
case 4: return .blue
|
||||
case 3: return .yellow
|
||||
case 2: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
private func formatDate(_ date: Date) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy. MM. dd."
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
|
||||
private func averageColor(_ avg: Double) -> Color {
|
||||
switch avg {
|
||||
case 4.5...: return .green
|
||||
case 3.5..<4.5: return .blue
|
||||
case 2.5..<3.5: return .yellow
|
||||
case 1.5..<2.5: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GradesView: View {
|
||||
let dataStore: DataStore
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
if dataStore.data == nil {
|
||||
ContentUnavailableView("no_data".localized, systemImage: "graduationcap")
|
||||
} else if subjects.isEmpty {
|
||||
ContentUnavailableView("no_grades".localized, systemImage: "graduationcap")
|
||||
} else {
|
||||
ScrollView {
|
||||
VStack(spacing: 8) {
|
||||
ForEach(subjects, id: \.uid) { subject in
|
||||
NavigationLink {
|
||||
GradeSubjectView(
|
||||
subjectName: subject.name,
|
||||
grades: gradesFor(subject.uid),
|
||||
average: subject.average
|
||||
)
|
||||
} label: {
|
||||
subjectRow(subject)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
|
||||
if let overall = dataStore.data?.averages.overall {
|
||||
overallAverageCard(overall)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var subjects: [SubjectAverage] {
|
||||
(dataStore.data?.averages.subjects ?? []).sorted { $0.name < $1.name }
|
||||
}
|
||||
|
||||
private func gradesFor(_ uid: String) -> [WidgetGrade] {
|
||||
dataStore.data?.grades.filter { $0.subject.uid == uid } ?? []
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func subjectRow(_ subject: SubjectAverage) -> some View {
|
||||
FirkaCard {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Text(subject.name)
|
||||
.font(.subheadline)
|
||||
.fontWeight(.medium)
|
||||
.lineLimit(1)
|
||||
|
||||
Spacer()
|
||||
|
||||
Text(String(format: "%.2f", subject.average))
|
||||
.font(.subheadline)
|
||||
.fontWeight(.bold)
|
||||
.foregroundColor(averageColor(subject.average))
|
||||
}
|
||||
|
||||
HStack(spacing: 8) {
|
||||
AverageProgressBar(average: subject.average)
|
||||
|
||||
Text("grades_count".localized(subject.gradeCount))
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func overallAverageCard(_ average: Double) -> some View {
|
||||
FirkaCard {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text("total_average".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
HStack {
|
||||
Text(String(format: "%.2f", average))
|
||||
.font(.title3)
|
||||
.fontWeight(.bold)
|
||||
.foregroundColor(averageColor(average))
|
||||
|
||||
Spacer()
|
||||
|
||||
AverageProgressBar(average: average)
|
||||
.frame(width: 60)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.top, 8)
|
||||
}
|
||||
|
||||
private func averageColor(_ avg: Double) -> Color {
|
||||
switch avg {
|
||||
case 4.5...: return .green
|
||||
case 3.5..<4.5: return .blue
|
||||
case 2.5..<3.5: return .yellow
|
||||
case 1.5..<2.5: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,598 +0,0 @@
|
||||
import SwiftUI
|
||||
import WatchConnectivity
|
||||
internal import Combine
|
||||
|
||||
struct HomeView: View {
|
||||
let dataStore: DataStore
|
||||
@State private var currentTime = Date()
|
||||
|
||||
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 12) {
|
||||
if let breakInfo = dataStore.data?.timetable.currentBreak {
|
||||
breakView(breakInfo)
|
||||
} else if !dataStore.hasToken && dataStore.data == nil {
|
||||
noTokenView
|
||||
} else if let current = currentLesson {
|
||||
currentLessonView(current)
|
||||
} else if let next = nextLesson {
|
||||
if isBreakBetweenLessons {
|
||||
breakBetweenView(next)
|
||||
} else {
|
||||
beforeSchoolView(next)
|
||||
}
|
||||
} else {
|
||||
noMoreLessonsView
|
||||
}
|
||||
|
||||
refreshButton
|
||||
|
||||
if dataStore.lastUpdated != nil {
|
||||
lastUpdatedView
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
.onReceive(timer) { _ in
|
||||
currentTime = Date()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Refresh Button
|
||||
|
||||
@State private var refreshStatus: RefreshStatus = .idle
|
||||
@State private var wasLoadingFromBackground: Bool = false
|
||||
@State private var lastUpdateTime: Date? = nil
|
||||
|
||||
enum RefreshStatus {
|
||||
case idle, loading, success, failure
|
||||
}
|
||||
|
||||
private var refreshButton: some View {
|
||||
Button(action: {
|
||||
guard !dataStore.isLoading else { return }
|
||||
Task {
|
||||
refreshStatus = .loading
|
||||
await dataStore.refreshAllWithRecovery()
|
||||
if dataStore.error == nil && dataStore.data != nil {
|
||||
refreshStatus = .success
|
||||
} else {
|
||||
refreshStatus = .failure
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
refreshStatus = .idle
|
||||
}
|
||||
}) {
|
||||
HStack(spacing: 6) {
|
||||
if dataStore.isLoading && refreshStatus != .loading {
|
||||
ProgressView()
|
||||
.scaleEffect(0.8)
|
||||
} else {
|
||||
switch refreshStatus {
|
||||
case .idle:
|
||||
Image(systemName: "arrow.clockwise")
|
||||
case .loading:
|
||||
ProgressView()
|
||||
.scaleEffect(0.8)
|
||||
case .success:
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.foregroundColor(.green)
|
||||
case .failure:
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
.foregroundColor(.red)
|
||||
}
|
||||
}
|
||||
Text(refreshStatusText)
|
||||
}
|
||||
.font(.caption)
|
||||
.foregroundColor(.blue)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(dataStore.isLoading || refreshStatus == .loading)
|
||||
.padding(.top, 8)
|
||||
.onChange(of: dataStore.isLoading) { oldValue, newValue in
|
||||
if newValue && refreshStatus != .loading {
|
||||
wasLoadingFromBackground = true
|
||||
}
|
||||
if !newValue && wasLoadingFromBackground && refreshStatus != .loading {
|
||||
wasLoadingFromBackground = false
|
||||
if dataStore.error == nil && dataStore.data != nil {
|
||||
refreshStatus = .success
|
||||
} else if dataStore.error != nil {
|
||||
refreshStatus = .failure
|
||||
}
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
if refreshStatus == .success || refreshStatus == .failure {
|
||||
refreshStatus = .idle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.onChange(of: dataStore.lastUpdated) { oldValue, newValue in
|
||||
guard let oldValue, let newValue else { return }
|
||||
guard newValue > oldValue else { return }
|
||||
guard dataStore.error == nil else { return }
|
||||
guard refreshStatus != .loading else { return }
|
||||
|
||||
refreshStatus = .success
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
if refreshStatus == .success {
|
||||
refreshStatus = .idle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var refreshStatusText: String {
|
||||
if dataStore.isLoading && refreshStatus != .loading {
|
||||
return "refreshing".localized
|
||||
}
|
||||
|
||||
switch refreshStatus {
|
||||
case .idle: return "refresh".localized
|
||||
case .loading: return "refreshing".localized
|
||||
case .success: return "refresh_success".localized
|
||||
case .failure:
|
||||
if let error = dataStore.error {
|
||||
switch error {
|
||||
case "api_error": return "error_api".localized
|
||||
case "network": return "error_network".localized
|
||||
case "token_expired", "no_token": return "reauth_required".localized
|
||||
default: return "refresh_failed".localized
|
||||
}
|
||||
}
|
||||
return "refresh_failed".localized
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Computed Properties
|
||||
|
||||
private var now: Date { currentTime }
|
||||
|
||||
private var todayLessons: [WidgetLesson] {
|
||||
let todayStr = formatDateForHomeView(currentTime)
|
||||
|
||||
if let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty {
|
||||
return allLessons
|
||||
.filter { $0.date == todayStr }
|
||||
.sorted { $0.start < $1.start }
|
||||
}
|
||||
|
||||
return dataStore.data?.timetable.today ?? []
|
||||
}
|
||||
|
||||
private var currentLesson: WidgetLesson? {
|
||||
todayLessons.first { currentTime >= $0.start && currentTime <= $0.end }
|
||||
}
|
||||
|
||||
private var nextLesson: WidgetLesson? {
|
||||
todayLessons
|
||||
.filter { $0.start > currentTime }
|
||||
.sorted { $0.start < $1.start }
|
||||
.first
|
||||
}
|
||||
|
||||
private var previousLesson: WidgetLesson? {
|
||||
todayLessons
|
||||
.filter { $0.end < currentTime }
|
||||
.sorted { $0.end > $1.end }
|
||||
.first
|
||||
}
|
||||
|
||||
private var isBreakBetweenLessons: Bool {
|
||||
guard let prev = previousLesson, let next = nextLesson else { return false }
|
||||
return currentTime > prev.end && currentTime < next.start
|
||||
}
|
||||
|
||||
// MARK: - Current Lesson View (with CountdownRing)
|
||||
|
||||
@ViewBuilder
|
||||
private func currentLessonView(_ lesson: WidgetLesson) -> some View {
|
||||
VStack(spacing: 10) {
|
||||
Text("current_lesson".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
let totalMinutes = Int(lesson.end.timeIntervalSince(lesson.start) / 60)
|
||||
let remaining = max(0, Int(lesson.end.timeIntervalSince(now) / 60))
|
||||
|
||||
HStack(spacing: 10) {
|
||||
CountdownRing(
|
||||
totalMinutes: totalMinutes,
|
||||
remainingMinutes: remaining,
|
||||
label: "minutes".localized,
|
||||
size: 56,
|
||||
lineWidth: 6,
|
||||
displayOffset: 1
|
||||
)
|
||||
.id("lesson-\(lesson.start.timeIntervalSince1970)")
|
||||
FirkaCard(
|
||||
isHighlighted: true,
|
||||
backgroundColor: lessonCardBackgroundColor(
|
||||
for: lesson,
|
||||
isHighlighted: true
|
||||
)
|
||||
) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
lessonTitleWithStatus(
|
||||
lesson,
|
||||
font: .subheadline,
|
||||
weight: .semibold,
|
||||
lineLimit: 2
|
||||
)
|
||||
|
||||
HStack(spacing: 6) {
|
||||
if let room = lesson.roomName {
|
||||
Label(room, systemImage: "door.right.hand.closed")
|
||||
}
|
||||
Text(lesson.timeString)
|
||||
}
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
// Next lesson preview
|
||||
if let next = nextLesson {
|
||||
Text("next".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
lessonTitleWithStatus(
|
||||
next,
|
||||
font: .subheadline,
|
||||
weight: .regular,
|
||||
lineLimit: 2
|
||||
)
|
||||
if let room = next.roomName {
|
||||
Text(room)
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
Text(next.start, style: .time)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Break Between Lessons (with CountdownRing)
|
||||
|
||||
@ViewBuilder
|
||||
private func breakBetweenView(_ next: WidgetLesson) -> some View {
|
||||
VStack(spacing: 10) {
|
||||
Text("break".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
let remaining = max(0, Int(ceil(next.start.timeIntervalSince(now) / 60)))
|
||||
let totalBreakMinutes: Int = {
|
||||
guard let previous = previousLesson else { return max(remaining, 1) }
|
||||
let breakSeconds = max(60, next.start.timeIntervalSince(previous.end))
|
||||
return max(1, Int(ceil(breakSeconds / 60)))
|
||||
}()
|
||||
|
||||
HStack(spacing: 10) {
|
||||
CountdownRing(
|
||||
totalMinutes: totalBreakMinutes,
|
||||
remainingMinutes: remaining,
|
||||
label: "minutes".localized,
|
||||
size: 56,
|
||||
lineWidth: 6,
|
||||
displayOffset: 1
|
||||
)
|
||||
.id("break-\(next.start.timeIntervalSince1970)")
|
||||
|
||||
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: next)) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(spacing: 4) {
|
||||
Text("next_lesson".localized(next.displayName))
|
||||
.font(.subheadline)
|
||||
.fontWeight(.semibold)
|
||||
.lineLimit(2)
|
||||
}
|
||||
|
||||
HStack(spacing: 6) {
|
||||
if let room = next.roomName {
|
||||
Label(room, systemImage: "door.right.hand.closed")
|
||||
}
|
||||
Text(next.start, style: .time)
|
||||
}
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Before School View
|
||||
|
||||
@ViewBuilder
|
||||
private func beforeSchoolView(_ first: WidgetLesson) -> some View {
|
||||
VStack(spacing: 12) {
|
||||
Text("first_lesson".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: first)) {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
lessonTitleWithStatus(
|
||||
first,
|
||||
font: .headline,
|
||||
weight: .regular,
|
||||
lineLimit: 2
|
||||
)
|
||||
|
||||
HStack {
|
||||
if let room = first.roomName {
|
||||
Label(room, systemImage: "door.right.hand.closed")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Text(relativeTimeString(to: first.start))
|
||||
.font(.caption)
|
||||
.foregroundColor(.blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !todayLessons.isEmpty {
|
||||
Text("today_lessons_count".localized(todayLessons.count))
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - No More Lessons View
|
||||
|
||||
private var noMoreLessonsView: some View {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.font(.system(size: 44))
|
||||
.foregroundColor(.green)
|
||||
|
||||
Text("no_more_lessons".localized)
|
||||
.font(.headline)
|
||||
|
||||
if let (nextLesson, dayLabel) = nextSchoolDayFirstLesson {
|
||||
Text(dayLabel)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.padding(.top, 8)
|
||||
|
||||
FirkaCard(backgroundColor: lessonCardBackgroundColor(for: nextLesson)) {
|
||||
HStack {
|
||||
lessonTitleWithStatus(
|
||||
nextLesson,
|
||||
font: .subheadline,
|
||||
weight: .regular,
|
||||
lineLimit: 2
|
||||
)
|
||||
Spacer()
|
||||
Text(nextLesson.start, style: .time)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var nextSchoolDayFirstLesson: (lesson: WidgetLesson, label: String)? {
|
||||
guard let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty else {
|
||||
if let tomorrow = dataStore.data?.timetable.tomorrow.first {
|
||||
return (tomorrow, "tomorrow_first_lesson".localized)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
let calendar = Calendar.current
|
||||
let now = currentTime
|
||||
let todayStr = formatDateForHomeView(now)
|
||||
|
||||
let futureLessons = allLessons.filter { $0.date > todayStr }
|
||||
.sorted { $0.date < $1.date || ($0.date == $1.date && $0.start < $1.start) }
|
||||
|
||||
guard let firstFuture = futureLessons.first else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let label = labelForDate(firstFuture.date, relativeTo: now)
|
||||
|
||||
return (firstFuture, label)
|
||||
}
|
||||
|
||||
private func formatDateForHomeView(_ date: Date) -> String {
|
||||
let calendar = Calendar.current
|
||||
let components = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
return String(format: "%04d-%02d-%02d",
|
||||
components.year ?? 0,
|
||||
components.month ?? 0,
|
||||
components.day ?? 0)
|
||||
}
|
||||
|
||||
private func labelForDate(_ dateStr: String, relativeTo: Date) -> String {
|
||||
let calendar = Calendar.current
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd"
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.timeZone = TimeZone.current
|
||||
|
||||
guard let targetDate = formatter.date(from: dateStr) else {
|
||||
return "next_school_day".localized
|
||||
}
|
||||
|
||||
let today = calendar.startOfDay(for: relativeTo)
|
||||
let target = calendar.startOfDay(for: targetDate)
|
||||
|
||||
let daysDiff = calendar.dateComponents([.day], from: today, to: target).day ?? 0
|
||||
|
||||
switch daysDiff {
|
||||
case 1:
|
||||
return "tomorrow_first_lesson".localized
|
||||
case 2...6:
|
||||
let dayFormatter = DateFormatter()
|
||||
let langCode = WatchL10n.shared.currentLanguage.rawValue
|
||||
dayFormatter.locale = Locale(identifier: langCode)
|
||||
dayFormatter.dateFormat = "EEEE"
|
||||
let dayName = dayFormatter.string(from: targetDate).capitalized
|
||||
return "day_first_lesson".localized(dayName)
|
||||
default:
|
||||
return "next_school_day".localized
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func lessonTitleWithStatus(
|
||||
_ lesson: WidgetLesson,
|
||||
font: Font,
|
||||
weight: Font.Weight = .regular,
|
||||
lineLimit: Int = 2
|
||||
) -> some View {
|
||||
Text(lesson.displayName)
|
||||
.font(font)
|
||||
.fontWeight(weight)
|
||||
.lineLimit(lineLimit)
|
||||
.foregroundColor(lessonPrimaryTextColor(for: lesson))
|
||||
}
|
||||
|
||||
private func lessonPrimaryTextColor(for lesson: WidgetLesson) -> Color {
|
||||
if lesson.isCancelled {
|
||||
return .red
|
||||
}
|
||||
if lesson.isSubstitution {
|
||||
return .yellow
|
||||
}
|
||||
return .primary
|
||||
}
|
||||
|
||||
private func lessonCardBackgroundColor(
|
||||
for lesson: WidgetLesson,
|
||||
isHighlighted: Bool = false
|
||||
) -> Color {
|
||||
if lesson.isCancelled {
|
||||
return Color.red.opacity(0.16)
|
||||
}
|
||||
if lesson.isSubstitution {
|
||||
return Color.yellow.opacity(0.16)
|
||||
}
|
||||
if isHighlighted {
|
||||
return Color.green.opacity(0.2)
|
||||
}
|
||||
return Color(white: 0.12)
|
||||
}
|
||||
|
||||
// MARK: - Break/Vacation View
|
||||
|
||||
@ViewBuilder
|
||||
private func breakView(_ breakInfo: BreakInfo) -> some View {
|
||||
VStack(spacing: 12) {
|
||||
let icon = SeasonalIconHelper.iconName(for: breakInfo.nameKey, season: nil)
|
||||
let color = SeasonalIconHelper.iconColor(for: breakInfo.nameKey, season: nil)
|
||||
|
||||
Image(systemName: icon)
|
||||
.font(.system(size: 44))
|
||||
.foregroundColor(color)
|
||||
|
||||
Text(breakInfo.name)
|
||||
.font(.headline)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - No Token View
|
||||
|
||||
private var isWatchSystemPaired: Bool {
|
||||
guard WCSession.isSupported() else { return false }
|
||||
return WCSession.default.isCompanionAppInstalled
|
||||
}
|
||||
|
||||
private var noTokenTitleKey: String {
|
||||
isWatchSystemPaired ? "login_on_iphone" : "pair_with_iphone"
|
||||
}
|
||||
|
||||
private var noTokenDescriptionKey: String {
|
||||
isWatchSystemPaired ? "open_and_login_on_iphone" : "open_firka_on_iphone"
|
||||
}
|
||||
|
||||
private var noTokenIconName: String {
|
||||
isWatchSystemPaired
|
||||
? "person.crop.circle.badge.exclamationmark"
|
||||
: "iphone.and.arrow.right.inward"
|
||||
}
|
||||
|
||||
private var noTokenView: some View {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: noTokenIconName)
|
||||
.font(.system(size: 44))
|
||||
.foregroundColor(.blue)
|
||||
|
||||
Text(noTokenTitleKey.localized)
|
||||
.font(.headline)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
Text(noTokenDescriptionKey.localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Last Updated View
|
||||
|
||||
private var lastUpdatedView: some View {
|
||||
HStack(spacing: 4) {
|
||||
if dataStore.isStale {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.foregroundColor(.yellow)
|
||||
}
|
||||
if let text = dataStore.timeSinceUpdate {
|
||||
Text("updated".localized(text))
|
||||
}
|
||||
}
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
.padding(.top, 8)
|
||||
}
|
||||
|
||||
// MARK: - Relative Time Helper
|
||||
|
||||
private func relativeTimeString(to date: Date) -> String {
|
||||
let now = currentTime
|
||||
let interval = date.timeIntervalSince(now)
|
||||
|
||||
guard interval > 0 else {
|
||||
return "time_now".localized
|
||||
}
|
||||
|
||||
let totalMinutes = Int(interval / 60)
|
||||
let hours = totalMinutes / 60
|
||||
let minutes = totalMinutes % 60
|
||||
|
||||
if hours > 0 && minutes > 0 {
|
||||
return "time_hours_minutes".localized(hours, minutes)
|
||||
} else if hours > 0 {
|
||||
return "time_hours".localized(hours)
|
||||
} else {
|
||||
return "time_minutes_only".localized(minutes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct LessonDetailView: View {
|
||||
let lesson: WidgetLesson
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
if let number = lesson.lessonNumber {
|
||||
Text("lesson_number".localized(number))
|
||||
.font(.caption)
|
||||
.foregroundColor(.blue)
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 4)
|
||||
.background(Color.blue.opacity(0.2))
|
||||
.cornerRadius(8)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Text("\(formatTime(lesson.start)) - \(formatTime(lesson.end))")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
Text(lesson.displayName)
|
||||
.font(.headline)
|
||||
.lineLimit(3)
|
||||
|
||||
if lesson.isCancelled || lesson.isSubstitution {
|
||||
HStack(spacing: 8) {
|
||||
if lesson.isCancelled {
|
||||
Label("cancelled".localized, systemImage: "xmark.circle.fill")
|
||||
.font(.caption2)
|
||||
.foregroundColor(.red)
|
||||
}
|
||||
if lesson.isSubstitution {
|
||||
Label("substitution".localized, systemImage: "person.2.fill")
|
||||
.font(.caption2)
|
||||
.foregroundColor(.orange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
if lesson.isSubstitution, let substitute = lesson.substituteTeacher {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Label("teacher".localized, systemImage: "person.fill")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
if let original = lesson.teacher {
|
||||
HStack(spacing: 4) {
|
||||
Text(original)
|
||||
.strikethrough()
|
||||
.foregroundColor(.secondary)
|
||||
Text("→")
|
||||
.foregroundColor(.orange)
|
||||
Text(substitute)
|
||||
.foregroundColor(.orange)
|
||||
}
|
||||
.font(.subheadline)
|
||||
} else {
|
||||
Text(substitute)
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.orange)
|
||||
}
|
||||
}
|
||||
} else if let teacher = lesson.teacher {
|
||||
detailRow(icon: "person.fill", label: "teacher".localized, value: teacher)
|
||||
}
|
||||
|
||||
if let room = lesson.roomName {
|
||||
detailRow(icon: "door.right.hand.closed", label: "room".localized, value: room)
|
||||
}
|
||||
|
||||
if let theme = lesson.theme, !theme.isEmpty {
|
||||
detailRow(icon: "doc.text.fill", label: "topic".localized, value: theme)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
.navigationTitle("lesson_details".localized)
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func detailRow(icon: String, label: String, value: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Label(label, systemImage: icon)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
Text(value)
|
||||
.font(.subheadline)
|
||||
.lineLimit(5)
|
||||
}
|
||||
}
|
||||
|
||||
private func formatTime(_ date: Date) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm"
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
import SwiftUI
|
||||
import WatchConnectivity
|
||||
|
||||
struct ReauthRequiredView: View {
|
||||
@State private var isSyncing = false
|
||||
@State private var syncStatus: SyncStatus = .idle
|
||||
var onTokenReceived: (() -> Void)?
|
||||
|
||||
enum SyncStatus {
|
||||
case idle
|
||||
case syncing
|
||||
case success
|
||||
case failed
|
||||
case phoneNotReachable
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 16) {
|
||||
Image(systemName: statusIcon)
|
||||
.font(.system(size: 44))
|
||||
.foregroundColor(statusColor)
|
||||
.symbolEffect(.pulse, isActive: syncStatus == .syncing)
|
||||
|
||||
Text("reauth_required".localized)
|
||||
.font(.headline)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
Text("reauth_description".localized)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.horizontal, 8)
|
||||
|
||||
if let statusMessage = statusMessage {
|
||||
Text(statusMessage)
|
||||
.font(.caption2)
|
||||
.foregroundColor(statusMessageColor)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
|
||||
Button(action: syncWithiPhone) {
|
||||
HStack {
|
||||
if syncStatus == .syncing {
|
||||
ProgressView()
|
||||
.scaleEffect(0.8)
|
||||
} else {
|
||||
Image(systemName: "arrow.triangle.2.circlepath")
|
||||
}
|
||||
Text("sync_button".localized)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(syncStatus == .success ? .green : .blue)
|
||||
.disabled(syncStatus == .syncing)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
private var statusIcon: String {
|
||||
switch syncStatus {
|
||||
case .idle:
|
||||
return "exclamationmark.arrow.circlepath"
|
||||
case .syncing:
|
||||
return "arrow.triangle.2.circlepath"
|
||||
case .success:
|
||||
return "checkmark.circle.fill"
|
||||
case .failed:
|
||||
return "xmark.circle.fill"
|
||||
case .phoneNotReachable:
|
||||
return "iphone.slash"
|
||||
}
|
||||
}
|
||||
|
||||
private var statusColor: Color {
|
||||
switch syncStatus {
|
||||
case .idle:
|
||||
return .orange
|
||||
case .syncing:
|
||||
return .blue
|
||||
case .success:
|
||||
return .green
|
||||
case .failed:
|
||||
return .red
|
||||
case .phoneNotReachable:
|
||||
return .gray
|
||||
}
|
||||
}
|
||||
|
||||
private var statusMessage: String? {
|
||||
switch syncStatus {
|
||||
case .idle:
|
||||
return nil
|
||||
case .syncing:
|
||||
return "syncing".localized
|
||||
case .success:
|
||||
return "sync_success".localized
|
||||
case .failed:
|
||||
return "sync_failed".localized
|
||||
case .phoneNotReachable:
|
||||
return "phone_not_reachable".localized
|
||||
}
|
||||
}
|
||||
|
||||
private var statusMessageColor: Color {
|
||||
switch syncStatus {
|
||||
case .success:
|
||||
return .green
|
||||
case .failed, .phoneNotReachable:
|
||||
return .red
|
||||
default:
|
||||
return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private func syncWithiPhone() {
|
||||
guard WCSession.default.activationState == .activated else {
|
||||
syncStatus = .failed
|
||||
return
|
||||
}
|
||||
|
||||
guard WCSession.default.isReachable else {
|
||||
syncStatus = .phoneNotReachable
|
||||
return
|
||||
}
|
||||
|
||||
syncStatus = .syncing
|
||||
|
||||
WCSession.default.sendMessage(
|
||||
["action": "requestToken"],
|
||||
replyHandler: { response in
|
||||
DispatchQueue.main.async {
|
||||
if let authDict = response["auth"] as? [String: Any] {
|
||||
print("[Watch] Token received from iPhone via reauth sync")
|
||||
self.processAuthData(authDict)
|
||||
|
||||
if !TokenManager.shared.isTokenExpired() {
|
||||
self.syncStatus = .success
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
|
||||
self.onTokenReceived?()
|
||||
}
|
||||
} else {
|
||||
print("[Watch] Received token is already expired - iPhone needs reauth")
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
} else if let error = response["error"] as? String {
|
||||
print("[Watch] iPhone returned error: \(error)")
|
||||
|
||||
if error == "needsReauth" || error == "no_token" {
|
||||
self.sendWatchTokenToiPhone()
|
||||
} else {
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
} else {
|
||||
print("[Watch] No token in response - iPhone may need reauth")
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
},
|
||||
errorHandler: { error in
|
||||
DispatchQueue.main.async {
|
||||
print("[Watch] Reauth sync failed: \(error.localizedDescription)")
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 15) {
|
||||
if self.syncStatus == .syncing {
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func sendWatchTokenToiPhone() {
|
||||
guard TokenManager.shared.loadToken() != nil else {
|
||||
print("[Watch] No token to send to iPhone")
|
||||
syncStatus = .failed
|
||||
return
|
||||
}
|
||||
|
||||
if TokenManager.shared.isTokenExpired() {
|
||||
print("[Watch] Watch token is expired - attempting to refresh with retries...")
|
||||
Task {
|
||||
do {
|
||||
_ = try await KretaAPIClient.shared.getValidToken()
|
||||
print("[Watch] Token refresh succeeded! Now sending to iPhone...")
|
||||
await MainActor.run {
|
||||
self.sendRefreshedTokenToiPhone()
|
||||
}
|
||||
} catch {
|
||||
print("[Watch] Token refresh failed after all retries: \(error)")
|
||||
await MainActor.run {
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
sendRefreshedTokenToiPhone()
|
||||
}
|
||||
|
||||
private func sendRefreshedTokenToiPhone() {
|
||||
guard let token = TokenManager.shared.loadToken() else {
|
||||
print("[Watch] No token after refresh")
|
||||
syncStatus = .failed
|
||||
return
|
||||
}
|
||||
|
||||
print("[Watch] Sending Watch token to iPhone...")
|
||||
|
||||
var tokenData: [String: Any] = [
|
||||
"studentId": token.studentId,
|
||||
"studentIdNorm": token.studentIdNorm,
|
||||
"iss": token.iss,
|
||||
"idToken": token.idToken,
|
||||
"accessToken": token.accessToken,
|
||||
"refreshToken": token.refreshToken,
|
||||
"expiryDate": Int64(token.expiryDate.timeIntervalSince1970 * 1000)
|
||||
]
|
||||
if let tokenVersion = token.effectiveTokenVersion {
|
||||
tokenData["tokenVersion"] = tokenVersion
|
||||
}
|
||||
tokenData["updatedAtMs"] = token.effectiveUpdatedAtMs ?? Int64(Date().timeIntervalSince1970 * 1000)
|
||||
|
||||
WCSession.default.sendMessage(
|
||||
["action": "receiveTokenFromWatch", "token": tokenData],
|
||||
replyHandler: { response in
|
||||
DispatchQueue.main.async {
|
||||
if let success = response["success"] as? Bool, success {
|
||||
print("[Watch] iPhone accepted our token!")
|
||||
self.syncStatus = .success
|
||||
|
||||
DataStore.shared.clearError()
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
|
||||
self.onTokenReceived?()
|
||||
}
|
||||
} else if let error = response["error"] as? String {
|
||||
print("[Watch] iPhone rejected our token: \(error)")
|
||||
self.syncStatus = .failed
|
||||
} else {
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
},
|
||||
errorHandler: { error in
|
||||
DispatchQueue.main.async {
|
||||
print("[Watch] Failed to send token to iPhone: \(error)")
|
||||
self.syncStatus = .failed
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func processAuthData(_ authDict: [String: Any]) {
|
||||
do {
|
||||
func parseInt64(_ value: Any?) -> Int64? {
|
||||
if let value = value as? Int64 { return value }
|
||||
if let value = value as? Int { return Int64(value) }
|
||||
if let value = value as? Double { return Int64(value) }
|
||||
if let value = value as? String, let parsed = Int64(value) { return parsed }
|
||||
return nil
|
||||
}
|
||||
|
||||
let incomingSentAtMs = parseInt64(authDict["sentAtMs"]) ?? 0
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: authDict)
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .custom { decoder in
|
||||
let container = try decoder.singleValueContainer()
|
||||
let timestamp = try container.decode(Int64.self)
|
||||
return Date(timeIntervalSince1970: Double(timestamp) / 1000.0)
|
||||
}
|
||||
|
||||
let token = try decoder.decode(WatchToken.self, from: jsonData)
|
||||
let currentToken = TokenManager.shared.loadToken()
|
||||
let shouldForceAccountSwitch: Bool
|
||||
if incomingSentAtMs > 0,
|
||||
let currentToken,
|
||||
!token.isSameAccount(as: currentToken) {
|
||||
shouldForceAccountSwitch = true
|
||||
} else {
|
||||
shouldForceAccountSwitch = false
|
||||
}
|
||||
|
||||
try TokenManager.shared.saveToken(
|
||||
token,
|
||||
syncToSharedKeychain: false,
|
||||
forceAccountSwitch: shouldForceAccountSwitch
|
||||
)
|
||||
|
||||
DataStore.shared.checkTokenState()
|
||||
DataStore.shared.clearError()
|
||||
|
||||
print("[Watch] Token saved via reauth sync")
|
||||
} catch {
|
||||
print("[Watch] Failed to process auth data: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ReauthRequiredView()
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct SettingsView: View {
|
||||
@AppStorage("refreshInterval") private var refreshInterval: Int = 0
|
||||
@State private var l10n = WatchL10n.shared
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
Section("language".localized) {
|
||||
Toggle("sync_with_iphone".localized, isOn: Binding(
|
||||
get: { l10n.syncWithiPhone },
|
||||
set: { l10n.syncWithiPhone = $0 }
|
||||
))
|
||||
|
||||
if !l10n.syncWithiPhone {
|
||||
Picker("language".localized, selection: Binding(
|
||||
get: { l10n.currentLanguage },
|
||||
set: { l10n.setLanguage($0) }
|
||||
)) {
|
||||
ForEach(WatchLanguage.allCases, id: \.self) { lang in
|
||||
HStack {
|
||||
Text(lang.flag)
|
||||
Text(lang.displayName)
|
||||
}
|
||||
.tag(lang)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Section("refresh".localized) {
|
||||
Picker("refresh_interval".localized, selection: $refreshInterval) {
|
||||
Text("auto".localized).tag(0)
|
||||
Text("15_minutes".localized).tag(15)
|
||||
Text("30_minutes".localized).tag(30)
|
||||
Text("1_hour".localized).tag(60)
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
Button("clear_cache".localized) {
|
||||
clearCache()
|
||||
}
|
||||
|
||||
Button("logout".localized, role: .destructive) {
|
||||
logout()
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
HStack {
|
||||
Text("version".localized)
|
||||
Spacer()
|
||||
Text(appVersion)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("settings".localized)
|
||||
}
|
||||
|
||||
private var appVersion: String {
|
||||
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"
|
||||
}
|
||||
|
||||
private func clearCache() {
|
||||
DataStore.shared.clearCache()
|
||||
}
|
||||
|
||||
private func logout() {
|
||||
TokenManager.shared.deleteToken()
|
||||
_ = SharedSessionStateManager.shared.publishState(
|
||||
hasAnyAccount: false,
|
||||
activeStudentIdNorm: nil
|
||||
)
|
||||
DataStore.shared.clearAll()
|
||||
}
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct TimetableView: View {
|
||||
let dataStore: DataStore
|
||||
|
||||
@State private var selectedDay: Int = 0
|
||||
@State private var weekOffset: Int = 0
|
||||
|
||||
private var dayLabels: [String] {
|
||||
[
|
||||
"day_mon".localized,
|
||||
"day_tue".localized,
|
||||
"day_wed".localized,
|
||||
"day_thu".localized,
|
||||
"day_fri".localized
|
||||
]
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
VStack(spacing: 0) {
|
||||
daySelector
|
||||
|
||||
Divider()
|
||||
.padding(.vertical, 4)
|
||||
|
||||
lessonsContent
|
||||
}
|
||||
.onAppear {
|
||||
updateWeekAndDay()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func updateWeekAndDay() {
|
||||
let calendar = Calendar.current
|
||||
let now = Date()
|
||||
|
||||
if shouldShowNextWeek() {
|
||||
weekOffset = 1
|
||||
selectedDay = findFirstSchoolDay(weekOffset: 1)
|
||||
return
|
||||
}
|
||||
|
||||
weekOffset = 0
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let todayIndex = weekday - 2
|
||||
|
||||
if todayIndex < 0 || todayIndex > 4 {
|
||||
selectedDay = findFirstSchoolDay(weekOffset: 0)
|
||||
return
|
||||
}
|
||||
|
||||
if areTodayLessonsDone(dayIndex: todayIndex) {
|
||||
if let nextDay = findNextSchoolDay(after: todayIndex) {
|
||||
selectedDay = nextDay
|
||||
} else {
|
||||
selectedDay = todayIndex
|
||||
}
|
||||
} else {
|
||||
selectedDay = todayIndex
|
||||
}
|
||||
}
|
||||
|
||||
private func areTodayLessonsDone(dayIndex: Int) -> Bool {
|
||||
let todayLessons = lessonsForDay(dayIndex)
|
||||
guard !todayLessons.isEmpty else { return true }
|
||||
|
||||
let now = Date()
|
||||
let lastLesson = todayLessons.sorted { $0.end > $1.end }.first
|
||||
return lastLesson.map { now > $0.end } ?? true
|
||||
}
|
||||
|
||||
private func findNextSchoolDay(after dayIndex: Int) -> Int? {
|
||||
for day in (dayIndex + 1)...4 {
|
||||
if !lessonsForDay(day).isEmpty {
|
||||
return day
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func findFirstSchoolDay(weekOffset: Int) -> Int {
|
||||
let oldOffset = self.weekOffset
|
||||
for day in 0...4 {
|
||||
let lessons = lessonsForDayWithOffset(day, weekOffset: weekOffset)
|
||||
if !lessons.isEmpty {
|
||||
return day
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
private func lessonsForDayWithOffset(_ day: Int, weekOffset: Int) -> [WidgetLesson] {
|
||||
guard let data = dataStore.data else { return [] }
|
||||
|
||||
let allLessons: [WidgetLesson]
|
||||
if let all = data.timetable.allLessons, !all.isEmpty {
|
||||
allLessons = all
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
|
||||
let targetDateStr = getDateStringForDayWithOffset(day, weekOffset: weekOffset)
|
||||
return allLessons.filter { $0.date == targetDateStr }
|
||||
}
|
||||
|
||||
private func getDateStringForDayWithOffset(_ day: Int, weekOffset: Int) -> String {
|
||||
let calendar = Calendar.current
|
||||
let now = Date()
|
||||
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday)
|
||||
|
||||
guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now) else {
|
||||
return ""
|
||||
}
|
||||
|
||||
let totalDaysToAdd = day + (weekOffset * 7)
|
||||
guard let targetDate = calendar.date(byAdding: .day, value: totalDaysToAdd, to: monday) else {
|
||||
return ""
|
||||
}
|
||||
|
||||
return formatDate(targetDate)
|
||||
}
|
||||
|
||||
private func shouldShowNextWeek() -> Bool {
|
||||
guard let allLessons = dataStore.data?.timetable.allLessons, !allLessons.isEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let now = Date()
|
||||
let calendar = Calendar.current
|
||||
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday)
|
||||
guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now),
|
||||
let friday = calendar.date(byAdding: .day, value: 4, to: monday) else {
|
||||
return false
|
||||
}
|
||||
let fridayString = formatDate(friday)
|
||||
let mondayString = formatDate(monday)
|
||||
|
||||
let currentWeekLessons = allLessons.filter { lesson in
|
||||
lesson.date >= mondayString && lesson.date <= fridayString
|
||||
}
|
||||
|
||||
guard !currentWeekLessons.isEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let lastLesson = currentWeekLessons
|
||||
.sorted { $0.date > $1.date || ($0.date == $1.date && $0.end > $1.end) }
|
||||
.first
|
||||
|
||||
guard let last = lastLesson else {
|
||||
return false
|
||||
}
|
||||
|
||||
return now > last.end
|
||||
}
|
||||
|
||||
// MARK: - Day Selector
|
||||
|
||||
private var daySelector: some View {
|
||||
HStack(spacing: 6) {
|
||||
ForEach(0..<5, id: \.self) { day in
|
||||
Button(action: { selectedDay = day }) {
|
||||
Text(dayLabels[day])
|
||||
.font(.system(size: 14, weight: .semibold))
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(height: 32)
|
||||
.foregroundColor(selectedDay == day ? .white : .primary)
|
||||
.background(selectedDay == day ? Color.blue : Color.clear)
|
||||
.cornerRadius(8)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.stroke(isToday(day) && selectedDay != day ? Color.blue : Color.clear, lineWidth: 2)
|
||||
)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
|
||||
private func isToday(_ day: Int) -> Bool {
|
||||
guard weekOffset == 0 else { return false }
|
||||
let weekday = Calendar.current.component(.weekday, from: Date())
|
||||
return day == weekday - 2
|
||||
}
|
||||
|
||||
// MARK: - Lessons Content
|
||||
|
||||
@ViewBuilder
|
||||
private var lessonsContent: some View {
|
||||
let lessons = lessonsForDay(selectedDay)
|
||||
|
||||
if lessons.isEmpty {
|
||||
freeDayView
|
||||
} else {
|
||||
ScrollView {
|
||||
VStack(spacing: 6) {
|
||||
ForEach(lessons) { lesson in
|
||||
NavigationLink {
|
||||
LessonDetailView(lesson: lesson)
|
||||
} label: {
|
||||
lessonRow(lesson)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func lessonsForDay(_ day: Int) -> [WidgetLesson] {
|
||||
guard let data = dataStore.data else { return [] }
|
||||
|
||||
let allLessons: [WidgetLesson]
|
||||
if let all = data.timetable.allLessons, !all.isEmpty {
|
||||
allLessons = all
|
||||
} else {
|
||||
var combined: [WidgetLesson] = []
|
||||
combined.append(contentsOf: data.timetable.today)
|
||||
combined.append(contentsOf: data.timetable.tomorrow)
|
||||
if let nextSchoolDay = data.timetable.nextSchoolDay {
|
||||
combined.append(contentsOf: nextSchoolDay)
|
||||
}
|
||||
allLessons = combined
|
||||
}
|
||||
|
||||
let targetDateStr = getDateStringForDay(day)
|
||||
|
||||
let uniqueDates = Set(allLessons.map { $0.date }).sorted()
|
||||
print("[Watch] lessonsForDay: day=\(day), weekOffset=\(weekOffset), targetDate=\(targetDateStr), lessons=\(allLessons.count)")
|
||||
print("[Watch] Unique dates in lessons: \(uniqueDates)")
|
||||
|
||||
if let first = allLessons.first {
|
||||
let cal = Calendar.current
|
||||
let comp = cal.dateComponents([.year, .month, .day, .hour, .minute], from: first.start)
|
||||
print("[Watch] First lesson: date=\(first.date), start=\(comp.year!)-\(comp.month!)-\(comp.day!) \(comp.hour!):\(comp.minute!)")
|
||||
}
|
||||
|
||||
let filtered = allLessons.filter { $0.date == targetDateStr }
|
||||
print("[Watch] Filtered lessons: \(filtered.count) for \(targetDateStr)")
|
||||
|
||||
return filtered.sorted { ($0.lessonNumber ?? 0) < ($1.lessonNumber ?? 0) }
|
||||
}
|
||||
|
||||
private func getDateStringForDay(_ day: Int) -> String {
|
||||
let calendar = Calendar.current
|
||||
let now = Date()
|
||||
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let daysFromMonday = (weekday == 1) ? -6 : (2 - weekday)
|
||||
|
||||
guard let monday = calendar.date(byAdding: .day, value: daysFromMonday, to: now) else {
|
||||
return ""
|
||||
}
|
||||
|
||||
let totalDaysToAdd = day + (weekOffset * 7)
|
||||
guard let targetDate = calendar.date(byAdding: .day, value: totalDaysToAdd, to: monday) else {
|
||||
return ""
|
||||
}
|
||||
|
||||
return formatDate(targetDate)
|
||||
}
|
||||
|
||||
private func formatDate(_ date: Date) -> String {
|
||||
let calendar = Calendar.current
|
||||
let components = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
return String(format: "%04d-%02d-%02d",
|
||||
components.year ?? 0,
|
||||
components.month ?? 0,
|
||||
components.day ?? 0)
|
||||
}
|
||||
|
||||
private var freeDayView: some View {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: "sun.max.fill")
|
||||
.font(.system(size: 40))
|
||||
.foregroundColor(.yellow)
|
||||
|
||||
Text("free_day".localized)
|
||||
.font(.headline)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.padding()
|
||||
}
|
||||
|
||||
// MARK: - Lesson Row
|
||||
|
||||
@ViewBuilder
|
||||
private func lessonRow(_ lesson: WidgetLesson) -> some View {
|
||||
FirkaCard(isHighlighted: lesson.isCurrentlyActive) {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
if let number = lesson.lessonNumber {
|
||||
Text("\(number).")
|
||||
.font(.subheadline)
|
||||
.fontWeight(.bold)
|
||||
.foregroundColor(.blue)
|
||||
.frame(width: 24, alignment: .leading)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
HStack(spacing: 4) {
|
||||
Text(lesson.displayName)
|
||||
.font(.subheadline)
|
||||
.fontWeight(.medium)
|
||||
.lineLimit(1)
|
||||
|
||||
if let statusIcon = lessonStatusIconName(for: lesson) {
|
||||
Image(systemName: statusIcon)
|
||||
.font(.caption2)
|
||||
.foregroundColor(lessonStatusColor(for: lesson))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Text(lesson.start, style: .time)
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
HStack(spacing: 4) {
|
||||
if let teacher = lesson.teacher {
|
||||
Text(teacher)
|
||||
.lineLimit(1)
|
||||
}
|
||||
if let room = lesson.roomName {
|
||||
Text("•")
|
||||
Text(room)
|
||||
}
|
||||
}
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func lessonStatusIconName(for lesson: WidgetLesson) -> String? {
|
||||
if lesson.isCancelled {
|
||||
return "xmark.circle.fill"
|
||||
}
|
||||
if lesson.isSubstitution {
|
||||
return "exclamationmark.circle.fill"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func lessonStatusColor(for lesson: WidgetLesson) -> Color {
|
||||
lesson.isCancelled ? .red : .yellow
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
struct TimetableView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
TimetableView(dataStore: DataStore.shared)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"platform" : "watchos",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
#if os(watchOS)
|
||||
import WidgetKit
|
||||
import SwiftUI
|
||||
|
||||
// MARK: - Complication Localization Helper
|
||||
|
||||
private struct ComplicationL10n {
|
||||
private static let appGroupID = "group.app.firka.firkaa"
|
||||
|
||||
enum Language: String {
|
||||
case hungarian = "hu"
|
||||
case english = "en"
|
||||
case german = "de"
|
||||
}
|
||||
|
||||
static var currentLanguage: Language {
|
||||
guard let defaults = UserDefaults(suiteName: appGroupID) else {
|
||||
return .hungarian
|
||||
}
|
||||
let code = defaults.string(forKey: "watch_language") ?? "hu"
|
||||
return Language(rawValue: code) ?? .hungarian
|
||||
}
|
||||
|
||||
static func string(_ key: String) -> String {
|
||||
switch currentLanguage {
|
||||
case .hungarian: return hungarianStrings[key] ?? key
|
||||
case .english: return englishStrings[key] ?? key
|
||||
case .german: return germanStrings[key] ?? key
|
||||
}
|
||||
}
|
||||
|
||||
private static let hungarianStrings: [String: String] = [
|
||||
"current_lesson": "Jelenlegi óra",
|
||||
"next": "Következő",
|
||||
"no_more_lessons": "Nincs több óra",
|
||||
"average_abbrev": "Átl",
|
||||
"next_lesson_title": "Következő óra",
|
||||
"average_title": "Átlag",
|
||||
"lesson_inline": "Óra (inline)"
|
||||
]
|
||||
|
||||
private static let englishStrings: [String: String] = [
|
||||
"current_lesson": "Current Lesson",
|
||||
"next": "Next",
|
||||
"no_more_lessons": "No more lessons",
|
||||
"average_abbrev": "Avg",
|
||||
"next_lesson_title": "Next Lesson",
|
||||
"average_title": "Average",
|
||||
"lesson_inline": "Lesson (inline)"
|
||||
]
|
||||
|
||||
private static let germanStrings: [String: String] = [
|
||||
"current_lesson": "Aktuelle Stunde",
|
||||
"next": "Nächste",
|
||||
"no_more_lessons": "Keine Stunden mehr",
|
||||
"average_abbrev": "Ø",
|
||||
"next_lesson_title": "Nächste Stunde",
|
||||
"average_title": "Durchschnitt",
|
||||
"lesson_inline": "Stunde (inline)"
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Watch Cache Loader
|
||||
|
||||
private struct WatchCacheLoader {
|
||||
private static let appGroupID = "group.app.firka.firkaa"
|
||||
private static let cacheFileName = "watch_data.json"
|
||||
|
||||
static func loadWidgetData() -> WidgetData? {
|
||||
guard let containerURL = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: appGroupID
|
||||
) else {
|
||||
print("[WatchComplication] No App Group container")
|
||||
return nil
|
||||
}
|
||||
|
||||
let fileURL = containerURL.appendingPathComponent(cacheFileName)
|
||||
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
print("[WatchComplication] Cache file not found: \(fileURL.path)")
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let data = try? Data(contentsOf: fileURL) else {
|
||||
print("[WatchComplication] Could not read cache file")
|
||||
return nil
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
|
||||
struct CachedWatchData: Codable {
|
||||
let widgetData: WidgetData
|
||||
let lastUpdated: Date
|
||||
}
|
||||
|
||||
do {
|
||||
let cached = try decoder.decode(CachedWatchData.self, from: data)
|
||||
print("[WatchComplication] Loaded cache from \(cached.lastUpdated)")
|
||||
return cached.widgetData
|
||||
} catch {
|
||||
print("[WatchComplication] Failed to decode: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Timeline Entry
|
||||
|
||||
struct FirkaTimelineEntry: TimelineEntry {
|
||||
let date: Date
|
||||
let data: WidgetData?
|
||||
}
|
||||
|
||||
// MARK: - Timeline Provider
|
||||
|
||||
struct FirkaTimelineProvider: TimelineProvider {
|
||||
func placeholder(in context: Context) -> FirkaTimelineEntry {
|
||||
FirkaTimelineEntry(date: Date(), data: nil)
|
||||
}
|
||||
|
||||
func getSnapshot(in context: Context, completion: @escaping (FirkaTimelineEntry) -> Void) {
|
||||
let data = WatchCacheLoader.loadWidgetData()
|
||||
completion(FirkaTimelineEntry(date: Date(), data: data))
|
||||
}
|
||||
|
||||
func getTimeline(in context: Context, completion: @escaping (Timeline<FirkaTimelineEntry>) -> Void) {
|
||||
let data = WatchCacheLoader.loadWidgetData()
|
||||
let entry = FirkaTimelineEntry(date: Date(), data: data)
|
||||
|
||||
let calendar = Calendar.current
|
||||
let now = Date()
|
||||
let hour = calendar.component(.hour, from: now)
|
||||
let weekday = calendar.component(.weekday, from: now)
|
||||
let isSchoolHours = (weekday >= 2 && weekday <= 6) && (hour >= 6 && hour <= 16)
|
||||
|
||||
let refreshInterval: TimeInterval = isSchoolHours ? 15 * 60 : 60 * 60
|
||||
let nextRefresh = now.addingTimeInterval(refreshInterval)
|
||||
|
||||
let timeline = Timeline(entries: [entry], policy: .after(nextRefresh))
|
||||
completion(timeline)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Next Lesson Complication (accessoryRectangular)
|
||||
|
||||
struct NextLessonComplication: Widget {
|
||||
let kind = "NextLessonComplication"
|
||||
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in
|
||||
NextLessonView(entry: entry)
|
||||
.containerBackground(.fill.tertiary, for: .widget)
|
||||
}
|
||||
.configurationDisplayName(ComplicationL10n.string("next_lesson_title"))
|
||||
.description("Shows the current or next lesson.")
|
||||
.supportedFamilies([.accessoryRectangular])
|
||||
}
|
||||
}
|
||||
|
||||
private struct NextLessonView: View {
|
||||
let entry: FirkaTimelineEntry
|
||||
|
||||
private var now: Date { Date() }
|
||||
|
||||
private var todayLessons: [WidgetLesson] {
|
||||
(entry.data?.timetable.today ?? []).sorted { $0.start < $1.start }
|
||||
}
|
||||
|
||||
private var currentLesson: WidgetLesson? {
|
||||
todayLessons.first { now >= $0.start && now <= $0.end }
|
||||
}
|
||||
|
||||
private var nextLesson: WidgetLesson? {
|
||||
todayLessons.first { $0.start > now }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
if let breakInfo = entry.data?.timetable.currentBreak {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: SeasonalIconHelper.iconName(for: breakInfo.nameKey, season: nil))
|
||||
.font(.caption)
|
||||
Text(breakInfo.name)
|
||||
.font(.headline)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
} else if let lesson = currentLesson {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(ComplicationL10n.string("current_lesson"))
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
Text(lesson.displayName)
|
||||
.font(.headline)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 4) {
|
||||
if let room = lesson.roomName {
|
||||
Image(systemName: "door.right.hand.closed")
|
||||
.font(.caption2)
|
||||
Text(room)
|
||||
.font(.caption2)
|
||||
}
|
||||
Text("→ \(lesson.end, formatter: Self.timeFormatter)")
|
||||
.font(.caption2)
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
} else if let lesson = nextLesson {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(ComplicationL10n.string("next"))
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
Text(lesson.displayName)
|
||||
.font(.headline)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 4) {
|
||||
if let room = lesson.roomName {
|
||||
Image(systemName: "door.right.hand.closed")
|
||||
.font(.caption2)
|
||||
Text(room)
|
||||
.font(.caption2)
|
||||
}
|
||||
Text(lesson.start, formatter: Self.timeFormatter)
|
||||
.font(.caption2)
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
} else if entry.data != nil {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.font(.title3)
|
||||
.foregroundStyle(.green)
|
||||
Text(ComplicationL10n.string("no_more_lessons"))
|
||||
.font(.headline)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
} else {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Image(systemName: "book.fill")
|
||||
.font(.title3)
|
||||
Text("Firka")
|
||||
.font(.headline)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private static let timeFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.dateFormat = "HH:mm"
|
||||
return f
|
||||
}()
|
||||
}
|
||||
|
||||
// MARK: - Average Complication (accessoryCircular)
|
||||
|
||||
struct AverageComplication: Widget {
|
||||
let kind = "AverageComplication"
|
||||
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in
|
||||
AverageView(entry: entry)
|
||||
.containerBackground(.fill.tertiary, for: .widget)
|
||||
}
|
||||
.configurationDisplayName(ComplicationL10n.string("average_title"))
|
||||
.description("Shows the overall grade average.")
|
||||
.supportedFamilies([.accessoryCircular])
|
||||
}
|
||||
}
|
||||
|
||||
private struct AverageView: View {
|
||||
let entry: FirkaTimelineEntry
|
||||
|
||||
private var averageColor: Color {
|
||||
guard let avg = entry.data?.averages.overall else { return .gray }
|
||||
switch avg {
|
||||
case 4.5...: return .green
|
||||
case 3.5..<4.5: return .blue
|
||||
case 2.5..<3.5: return .yellow
|
||||
case 1.5..<2.5: return .orange
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
if let average = entry.data?.averages.overall {
|
||||
Gauge(value: average, in: 1...5) {
|
||||
Text(ComplicationL10n.string("average_abbrev"))
|
||||
} currentValueLabel: {
|
||||
Text(String(format: "%.1f", average))
|
||||
.font(.system(.body, design: .rounded, weight: .bold))
|
||||
}
|
||||
.gaugeStyle(.accessoryCircular)
|
||||
.tint(averageColor)
|
||||
} else {
|
||||
ZStack {
|
||||
AccessoryWidgetBackground()
|
||||
Text("—")
|
||||
.font(.title3)
|
||||
.fontWeight(.bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Inline Complication (accessoryInline)
|
||||
|
||||
struct InlineComplication: Widget {
|
||||
let kind = "InlineComplication"
|
||||
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(kind: kind, provider: FirkaTimelineProvider()) { entry in
|
||||
InlineView(entry: entry)
|
||||
.containerBackground(.fill.tertiary, for: .widget)
|
||||
}
|
||||
.configurationDisplayName(ComplicationL10n.string("lesson_inline"))
|
||||
.description("One-line summary of the next lesson.")
|
||||
.supportedFamilies([.accessoryInline])
|
||||
}
|
||||
}
|
||||
|
||||
private struct InlineView: View {
|
||||
let entry: FirkaTimelineEntry
|
||||
|
||||
private var now: Date { Date() }
|
||||
|
||||
private var todayLessons: [WidgetLesson] {
|
||||
(entry.data?.timetable.today ?? []).sorted { $0.start < $1.start }
|
||||
}
|
||||
|
||||
private var currentOrNextLesson: WidgetLesson? {
|
||||
todayLessons.first { now >= $0.start && now <= $0.end }
|
||||
?? todayLessons.first { $0.start > now }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
if let breakInfo = entry.data?.timetable.currentBreak {
|
||||
Text(breakInfo.name)
|
||||
} else if let lesson = currentOrNextLesson {
|
||||
Text("\(lesson.displayName) \(lesson.start, formatter: Self.timeFormatter)")
|
||||
} else if entry.data != nil {
|
||||
Text(ComplicationL10n.string("no_more_lessons"))
|
||||
} else {
|
||||
Text("Firka")
|
||||
}
|
||||
}
|
||||
|
||||
private static let timeFormatter: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.dateFormat = "HH:mm"
|
||||
return f
|
||||
}()
|
||||
}
|
||||
|
||||
// MARK: - Widget Bundle
|
||||
|
||||
@main
|
||||
struct FirkaWatchWidgets: WidgetBundle {
|
||||
var body: some Widget {
|
||||
NextLessonComplication()
|
||||
AverageComplication()
|
||||
InlineComplication()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.widgetkit-extension</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||