Compare commits
153 Commits
8f28fa328c
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad75a80805 | ||
|
|
0ce7db23de | ||
|
|
0317f47b88 | ||
|
|
5a2616bf71 | ||
|
|
9753717a25 | ||
|
|
cf4e27ad30 | ||
| d96c4b66bb | |||
| 68ddffd808 | |||
| 483c8de0c0 | |||
| 4850923305 | |||
| 489a3a1d24 | |||
| 4b0bf5a22d | |||
| e07b0264b8 | |||
| 32d8481217 | |||
| d0c3938510 | |||
| 636c2ea68d | |||
| b986d8b660 | |||
| 613db488b1 | |||
| 5d5c3c4c6f | |||
| 9f36569d2a | |||
| 9fc73e3c5c | |||
| bd53ba6c9b | |||
| 8d95c71fae | |||
| befaa45cdf | |||
| 5570f73cb4 | |||
| 59b470a64c | |||
| 4811519ced | |||
| 3580dc2ef8 | |||
| eb1312398d | |||
| a70457528b | |||
| 6bbdbadac4 | |||
| 911a1970e4 | |||
| 65ab5caa69 | |||
| a9624df915 | |||
| 52f6ebcfd3 | |||
| 635fdd5497 | |||
| a11f118861 | |||
| 5c205a9844 | |||
| f620bfe76c | |||
| b99051dbfc | |||
| c58f34f499 | |||
| 1e7dceb995 | |||
| 022915378e | |||
| 589e722310 | |||
| 12cce27e9d | |||
| 826312b503 | |||
| e071fc15d1 | |||
| 94b819ffbd | |||
| 299a769f74 | |||
| 4abf995fde | |||
| e261f73c30 | |||
| fc9907f33d | |||
| 2d2c2fbef9 | |||
|
|
d5c3d02dfa | ||
|
|
40a1e8f459 | ||
| 0c4bc4cd40 | |||
| 28fb054571 | |||
| b0c8f1f4b3 | |||
| 2ea0549258 | |||
| c0ea4fde7a | |||
| d56422ba0d | |||
| 3fa00fa6b6 | |||
| ef14b9dc0e | |||
|
|
9238869568 | ||
| 6f04f9e9b8 | |||
| b6c8bb3267 | |||
| 5ef21222aa | |||
| c0a8c696a3 | |||
| f4a7fe7923 | |||
| c2f3af7be1 | |||
| 3440ea2eef | |||
| 34475f35b0 | |||
| 091647dbe4 | |||
| 36ca357392 | |||
| dbbc119fd5 | |||
| 448be1ae10 | |||
| 23beb6e31f | |||
| c122eb4ff9 | |||
| 8568aa5678 | |||
| 12dea89cd4 | |||
| 67965610ce | |||
| 7cede065c3 | |||
| ae4862a653 | |||
| 30f493ddc4 | |||
| 50eb96377e | |||
| 61c795e362 | |||
| 7c65a696aa | |||
| a341833441 | |||
| 8bf3cc72be | |||
| 33028cdf38 | |||
| f01b9d4fd5 | |||
| 41ff65d50b | |||
| ae9ef1603a | |||
| 1d8d341f2d | |||
| 633926bf2d | |||
| a6344e42fa | |||
| 9cb2265a97 | |||
| 971a35b738 | |||
| 69ee75966d | |||
| 177bf3bf38 | |||
| 5b794b199c | |||
| a000481cd9 | |||
| ae79a44df9 | |||
|
|
70213e376c | ||
|
|
146124228a | ||
|
|
9a99a6869a | ||
|
|
61953b68d2 | ||
|
|
69dde9281d | ||
|
|
86c7641c60 | ||
|
|
71f1412164 | ||
|
|
7c344be550 | ||
|
|
e620f3e564 | ||
|
|
2719e6bf77 | ||
|
|
55de7d1645 | ||
|
|
0b78712e64 | ||
|
|
6c67d22fb8 | ||
|
|
5403d1324d | ||
|
|
a071cafacd | ||
|
|
dbf0d18e5c | ||
|
|
12e3fa5bff | ||
|
|
72cfa9b5eb | ||
|
|
51831e94e4 | ||
|
|
aa8b3d5e16 | ||
|
|
b83cbef7fc | ||
|
|
35e1e2c6ab | ||
|
|
874f5d4297 | ||
|
|
71ef509021 | ||
|
|
16b7d2f70a | ||
|
|
402067d624 | ||
|
|
f76b5fbcca | ||
|
|
d395529282 | ||
|
|
1038b49092 | ||
|
|
d06a3dee69 | ||
|
|
d617efec80 | ||
|
|
beb4127ef8 | ||
|
|
1f57281004 | ||
|
|
f866052905 | ||
|
|
deb013a30e | ||
|
|
8a3f77d565 | ||
|
|
1ea46ede0a | ||
|
|
79f59b6938 | ||
|
|
e2b98125fc | ||
|
|
8c877e43db | ||
|
|
02acf0e59b | ||
|
|
04870205f9 | ||
|
|
bcc95ed0af | ||
| 88fd491281 | |||
|
|
9a435235b6 | ||
|
|
e583c77a7e | ||
|
|
8dbcc1e2a9 | ||
|
|
f631d52d5a | ||
|
|
768d0904a8 | ||
|
|
c21ff3e15f |
15
.gitmodules
vendored
@@ -1,18 +1,9 @@
|
||||
[submodule "firka/vendor/isar_generator"]
|
||||
path = firka/vendor/isar_generator
|
||||
url = https://git.qwit.cloud/firka/isar_generator
|
||||
[submodule "firka/vendor/isar"]
|
||||
path = firka/vendor/isar
|
||||
url = https://git.qwit.cloud/firka/isar
|
||||
[submodule "firka/vendor/isar_flutter_libs"]
|
||||
path = firka/vendor/isar_flutter_libs
|
||||
url = https://git.qwit.cloud/firka/isar_flutter_libs
|
||||
[submodule "firka/lib/l10n"]
|
||||
path = firka/lib/l10n
|
||||
url = https://github.com/QwIT-Development/firka-localization
|
||||
[submodule "firka_wear/vendor/wear_plus"]
|
||||
path = firka_wear/vendor/wear_plus
|
||||
url = https://git.firka.app/firka/wear_plus
|
||||
[submodule "firka/android/app/src/main/java/org/brotli"]
|
||||
path = firka/android/app/src/main/java/org/brotli
|
||||
url = https://git.firka.app/firka/org_brotli
|
||||
[submodule "firka_wear/lib/l10n"]
|
||||
path = firka_wear/lib/l10n
|
||||
url = https://github.com/qwit-development/firka-localization
|
||||
|
||||
5
firka/.env.example
Normal file
@@ -0,0 +1,5 @@
|
||||
# Backend Configuration
|
||||
# Development: http://192.168.X.YYY:3000/api/v1
|
||||
# Production: https://your-domain.com/api/v1
|
||||
BACKEND_BASE_URL=http://192.168.X.YYY:3000/api/v1
|
||||
BACKEND_API_KEY=development_api_key_12345
|
||||
5
firka/.gitignore
vendored
@@ -49,4 +49,7 @@ app.*.map.json
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
coverage
|
||||
coverage
|
||||
|
||||
# Generated files
|
||||
*.g.dart
|
||||
@@ -4,7 +4,7 @@
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "05db9689081f091050f01aed79f04dce0c750154"
|
||||
revision: "adc901062556672b4138e18a4dc62a4be8f4b3c2"
|
||||
channel: "stable"
|
||||
|
||||
project_type: app
|
||||
@@ -13,11 +13,11 @@ project_type: app
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 05db9689081f091050f01aed79f04dce0c750154
|
||||
base_revision: 05db9689081f091050f01aed79f04dce0c750154
|
||||
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
|
||||
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
|
||||
- platform: ios
|
||||
create_revision: 05db9689081f091050f01aed79f04dce0c750154
|
||||
base_revision: 05db9689081f091050f01aed79f04dce0c750154
|
||||
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
|
||||
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
|
||||
|
||||
# User provided section
|
||||
|
||||
|
||||
@@ -1,36 +1,18 @@
|
||||
import org.apache.commons.io.FileUtils
|
||||
import java.io.FileInputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.Properties
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Future
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipFile
|
||||
import java.util.zip.ZipOutputStream
|
||||
import java.util.zip.ZipOutputStream.DEFLATED
|
||||
import java.util.zip.ZipOutputStream.STORED
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.2.0"
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
fun loadProperties(file: File): Properties {
|
||||
val properties = Properties()
|
||||
FileInputStream(file).use { inputStream ->
|
||||
properties.load(inputStream)
|
||||
}
|
||||
return properties
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.firka.naplo"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = "27.0.12077973"
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
@@ -49,8 +31,8 @@ android {
|
||||
applicationId = "app.firka.naplo"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = 29
|
||||
targetSdk = 36
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
@@ -59,7 +41,7 @@ android {
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (propsFile.exists()) {
|
||||
val props = loadProperties(propsFile)
|
||||
val props = Properties().apply { FileInputStream(propsFile).use { load(it) } }
|
||||
val store = File(secretsDir, props["storeFile"].toString())
|
||||
|
||||
signingConfigs {
|
||||
@@ -68,6 +50,10 @@ android {
|
||||
storePassword = props["storePassword"] as String
|
||||
keyPassword = props["keyPassword"] as String
|
||||
keyAlias = props["keyAlias"] as String
|
||||
// Use APK Signature Scheme v3 (and v4 for streaming verification). See:
|
||||
// https://source.android.com/docs/security/features/apksigning/v3
|
||||
enableV3Signing = true
|
||||
enableV4Signing = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,808 +75,25 @@ android {
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
implementation("androidx.wear:wear-ongoing:1.0.0")
|
||||
implementation("androidx.glance:glance-appwidget:1.1.1")
|
||||
implementation("com.google.android.gms:play-services-wearable:18.1.0")
|
||||
}
|
||||
|
||||
// Ensure .env exists before Flutter bundles assets (copy from .env.example if missing)
|
||||
val envFile = file("${project.projectDir}/../../.env")
|
||||
val envExampleFile = file("${project.projectDir}/../../.env.example")
|
||||
tasks.register("ensureEnv") {
|
||||
doLast {
|
||||
if (!envFile.exists() && envExampleFile.exists()) {
|
||||
envExampleFile.copyTo(envFile, overwrite = false)
|
||||
println("Created .env from .env.example for asset bundling.")
|
||||
}
|
||||
}
|
||||
}
|
||||
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
|
||||
dependsOn("ensureEnv")
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
tasks.register("transformAndResignDebugApk") {
|
||||
group = "build"
|
||||
description = "Transform and resign APK with debug key"
|
||||
|
||||
dependsOn("assembleDebug")
|
||||
|
||||
doLast {
|
||||
if (System.getenv("TRANSFORM_APK") != null
|
||||
&& System.getenv("TRANSFORM_APK") == "true") {
|
||||
transformApks(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("transformAndResignReleaseApk") {
|
||||
group = "build"
|
||||
description = "Transform and resign APK with release key"
|
||||
|
||||
dependsOn("assembleRelease")
|
||||
|
||||
doLast {
|
||||
checkReleaseKey()
|
||||
if (System.getenv("TRANSFORM_APK") != null
|
||||
&& System.getenv("TRANSFORM_APK") == "true") {
|
||||
transformApks(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("transformAndResignReleaseBundle") {
|
||||
group = "build"
|
||||
description = "Transform and resign bundle with release key"
|
||||
|
||||
dependsOn("bundleRelease")
|
||||
|
||||
doLast {
|
||||
if (System.getenv("TRANSFORM_AAB") != null
|
||||
&& System.getenv("TRANSFORM_AAB") == "true") {
|
||||
transformAppBundle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
tasks.findByName("assembleDebug")?.finalizedBy("transformAndResignDebugApk")
|
||||
tasks.findByName("assembleRelease")?.finalizedBy("transformAndResignReleaseApk")
|
||||
tasks.findByName("bundleRelease")?.finalizedBy("transformAndResignReleaseBundle")
|
||||
}
|
||||
|
||||
fun checkReleaseKey() {
|
||||
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (propsFile.exists()) {
|
||||
val props = loadProperties(propsFile)
|
||||
val store = File(secretsDir, props["storeFile"].toString())
|
||||
|
||||
println(
|
||||
"Signing with:\n" +
|
||||
"\t- store: ${store.name}\n" +
|
||||
"\t- key: ${props["keyAlias"]}"
|
||||
)
|
||||
} else {
|
||||
throw Exception("Release keystore not found!")
|
||||
}
|
||||
}
|
||||
|
||||
fun transformApks(debug: Boolean, i : Int = 0) {
|
||||
try {
|
||||
_transformApks(debug)
|
||||
} catch (e: Exception) {
|
||||
if (i < 5) {
|
||||
e.printStackTrace()
|
||||
|
||||
println("Retrying: ${i + 1}")
|
||||
transformApks(debug, i + 1)
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun _transformApks(debug: Boolean) {
|
||||
println("Starting APK transformation process...")
|
||||
|
||||
val buildDir = project.buildDir
|
||||
val apkDir = File(buildDir, "outputs/flutter-apk")
|
||||
val apks = getApks(debug)
|
||||
var c = 0
|
||||
apks
|
||||
.forEach { c++; transformAndSignApk(apkDir, it.nameWithoutExtension, debug) }
|
||||
|
||||
println("Transformed: $c apks")
|
||||
}
|
||||
|
||||
fun transformAndSignApk(apkDir: File, name: String, debug: Boolean) {
|
||||
val originalApk = File(apkDir, "$name.apk")
|
||||
val transformedApk = File(apkDir, "$name-transformed.apk")
|
||||
val finalApk = File(apkDir, "$name-resigned.apk")
|
||||
val finalIdsig = File(apkDir, "$name-resigned.apk.idsig")
|
||||
|
||||
if (!originalApk.exists()) {
|
||||
throw GradleException("Original APK not found at: ${originalApk.absolutePath}")
|
||||
}
|
||||
|
||||
if (transformedApk.exists()) transformedApk.delete()
|
||||
if (finalApk.exists()) finalApk.delete()
|
||||
|
||||
println("Original APK: ${originalApk.absolutePath}")
|
||||
|
||||
try {
|
||||
println("Transforming APK...")
|
||||
transformApk(originalApk, transformedApk, if (debug) { "6" } else {"Z"})
|
||||
|
||||
if (debug) {
|
||||
println("Signing with debug key...")
|
||||
signWithDebugKey(transformedApk, finalApk)
|
||||
} else {
|
||||
println("Signing with release key...")
|
||||
signWithReleaseKey(transformedApk, finalApk)
|
||||
}
|
||||
|
||||
if (finalApk.exists()) {
|
||||
originalApk.delete()
|
||||
finalIdsig.delete()
|
||||
finalApk.renameTo(originalApk)
|
||||
println("APK successfully transformed")
|
||||
println("Final APK: ${originalApk.absolutePath}")
|
||||
}
|
||||
|
||||
transformedApk.delete()
|
||||
} catch (e: Exception) {
|
||||
throw GradleException("Failed to transform and resign APK: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun transformApk(input: File, output: File, compressionLevel: String = "Z") {
|
||||
val tempDir = File(project.buildDir, "tmp/apk-transform")
|
||||
val cacheDir = File(project.buildDir, "cache")
|
||||
val optipngCacheDir = File(cacheDir, "optipng")
|
||||
val assetCompressionDir = File(cacheDir, "assets")
|
||||
tempDir.deleteRecursively()
|
||||
tempDir.mkdirs()
|
||||
if (!optipngCacheDir.exists()) optipngCacheDir.mkdirs()
|
||||
if (!assetCompressionDir.exists()) assetCompressionDir.mkdirs()
|
||||
|
||||
val brotli = findToolInPath("brotli")
|
||||
?: throw Exception("Brotli not found in path")
|
||||
val optipng = findToolInPath("optipng")
|
||||
|
||||
if (optipng == null || optipng.isEmpty()) {
|
||||
println("Optipng was not found in PATH, optimizing images will be skipped.")
|
||||
}
|
||||
|
||||
copy {
|
||||
from(zipTree(input))
|
||||
into(tempDir)
|
||||
}
|
||||
|
||||
val metaInf = File(tempDir, "META-INF")
|
||||
val metaInfFiles = metaInf.listFiles()
|
||||
for (file in metaInfFiles!!) {
|
||||
if (file.name.endsWith("MF") || file.name.endsWith("SF")
|
||||
|| file.name.endsWith("RSA")) {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
val arches = File(tempDir, "lib").listFiles()
|
||||
val compressedLibs = mutableMapOf<String, String>()
|
||||
for (arch in arches!!) {
|
||||
val libFlutter = File(arch, "libflutter.so")
|
||||
|
||||
if (!libFlutter.exists()) continue
|
||||
|
||||
val compressedFlutter = File(arch, "libflutter-br.so")
|
||||
|
||||
compressedLibs["libflutter.so"] = libFlutter.sha256()
|
||||
|
||||
println("Compressing ${arch.name}/libflutter.so with brotli")
|
||||
exec {
|
||||
commandLine(
|
||||
brotli,
|
||||
"-$compressionLevel",
|
||||
libFlutter.absolutePath,
|
||||
"-o", compressedFlutter.absolutePath
|
||||
)
|
||||
}
|
||||
libFlutter.delete()
|
||||
|
||||
val json = groovy.json.JsonBuilder(compressedLibs)
|
||||
File(arch, "index.so").writeText(json.toString())
|
||||
}
|
||||
|
||||
val topDirL = tempDir.absolutePath.length + 1
|
||||
val zos = ZipOutputStream(output.outputStream())
|
||||
|
||||
val coreCount = Runtime.getRuntime().availableProcessors()
|
||||
val flutterResources = tempDir.walkTopDown().filter{f -> f.absolutePath.contains("flutter_assets")}
|
||||
val pngFiles = tempDir.walkTopDown().filter{f -> f.name.endsWith(".png")}
|
||||
|
||||
val assetIndex = mutableMapOf<String, String>()
|
||||
val indexReadWriteLock = ReentrantReadWriteLock()
|
||||
|
||||
if (compressionLevel == "Z") {
|
||||
if (optipng != null) {
|
||||
val executor = Executors.newFixedThreadPool(coreCount)
|
||||
val futures = mutableListOf<Future<*>>()
|
||||
|
||||
pngFiles.forEach { pngFile ->
|
||||
val cacheFile = File(optipngCacheDir, pngFile.sha256())
|
||||
|
||||
if (cacheFile.exists()) {
|
||||
cacheFile.copyTo(pngFile, true)
|
||||
} else {
|
||||
val future = executor.submit {
|
||||
exec {
|
||||
commandLine(
|
||||
optipng,
|
||||
"-zm", "9",
|
||||
"-zw", "32k",
|
||||
"-o9",
|
||||
pngFile.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
pngFile.copyTo(cacheFile, true)
|
||||
}
|
||||
|
||||
futures.add(future)
|
||||
}
|
||||
}
|
||||
|
||||
futures.forEach { it.get() }
|
||||
executor.shutdown()
|
||||
}
|
||||
|
||||
val executor = Executors.newFixedThreadPool(coreCount)
|
||||
val futures = mutableListOf<Future<*>>()
|
||||
|
||||
val blacklist = listOf(
|
||||
// "AssetManifest.bin",
|
||||
"AssetManifest.json",
|
||||
"FontManifest.json",
|
||||
"isolate_snapshot_data",
|
||||
"kernel_blob.bin",
|
||||
"NativeAssetsManifest.json",
|
||||
"NOTICES.Z",
|
||||
"vm_snapshot_data",
|
||||
"fonts",
|
||||
"shaders"
|
||||
)
|
||||
|
||||
flutterResources.forEach { f ->
|
||||
val relName = f.absolutePath.substring(topDirL).replace("\\", "/")
|
||||
if (f.isDirectory) return@forEach
|
||||
|
||||
val cacheFileRaw = File(assetCompressionDir, f.sha256()+".r")
|
||||
val cacheFileGz = File(assetCompressionDir, f.sha256()+".gz")
|
||||
val cacheFileBr = File(assetCompressionDir, f.sha256()+".br")
|
||||
|
||||
if (cacheFileRaw.exists() || cacheFileGz.exists() || cacheFileBr.exists()) {
|
||||
if (cacheFileRaw.exists()) {
|
||||
cacheFileRaw.copyTo(f, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "r"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
} else if (cacheFileGz.exists()) {
|
||||
cacheFileGz.copyTo(f, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "g"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
} else {
|
||||
cacheFileBr.copyTo(f, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "b"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
}
|
||||
} else {
|
||||
val future = executor.submit {
|
||||
val brTmp = File(f.absolutePath + ".br.tmp")
|
||||
val gzTmp = File(f.absolutePath + ".gz.tmp")
|
||||
|
||||
var blacklisted = false
|
||||
for (f in blacklist) {
|
||||
if (relName.contains(f)) {
|
||||
blacklisted = true
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!blacklisted) {
|
||||
println("$relName: Testing with brotli")
|
||||
exec {
|
||||
commandLine(
|
||||
brotli,
|
||||
"-$compressionLevel",
|
||||
f.absolutePath,
|
||||
"-o", brTmp.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
println("$relName: Testing with gzip")
|
||||
ant.invokeMethod(
|
||||
"gzip", mapOf(
|
||||
"src" to f.absolutePath,
|
||||
"destfile" to gzTmp.absolutePath,
|
||||
)
|
||||
)
|
||||
|
||||
println("$brTmp: ${brTmp.length()}")
|
||||
println("$gzTmp: ${gzTmp.length()}")
|
||||
if (f.length() < gzTmp.length() && f.length() < brTmp.length()) {
|
||||
println("$relName: Raw file wins")
|
||||
|
||||
f.copyTo(cacheFileRaw, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "r"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
} else {
|
||||
if (brTmp.length() < gzTmp.length()) {
|
||||
println("$relName: Brotli wins")
|
||||
|
||||
f.delete()
|
||||
brTmp.copyTo(f, true)
|
||||
brTmp.copyTo(cacheFileBr, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "b"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
} else {
|
||||
println("$relName: Gzip wins")
|
||||
|
||||
f.delete()
|
||||
gzTmp.copyTo(f, true)
|
||||
gzTmp.copyTo(cacheFileGz, true)
|
||||
|
||||
indexReadWriteLock.writeLock().lock()
|
||||
assetIndex[relName] = "g"
|
||||
indexReadWriteLock.writeLock().unlock()
|
||||
}
|
||||
}
|
||||
|
||||
brTmp.delete()
|
||||
gzTmp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
futures.add(future)
|
||||
}
|
||||
}
|
||||
|
||||
futures.forEach { it.get() }
|
||||
executor.shutdown()
|
||||
}
|
||||
|
||||
tempDir.walkTopDown().forEach { f ->
|
||||
if (f.absolutePath == tempDir.absolutePath) return@forEach
|
||||
|
||||
var relName = f.absolutePath.substring(topDirL).replace("\\", "/")
|
||||
if (f.isDirectory && !relName.endsWith("/")) relName += "/"
|
||||
|
||||
if (compressionLevel == "Z") {
|
||||
if (relName == "assets/flutter_assets/assets/firka.i") return@forEach
|
||||
}
|
||||
|
||||
println(relName)
|
||||
|
||||
val compress = !relName.endsWith(".so") && !relName.endsWith(".arsc")
|
||||
zos.setMethod(if (compress) { DEFLATED } else { STORED })
|
||||
val entry = ZipEntry(relName)
|
||||
if (!compress) {
|
||||
entry.size = f.length()
|
||||
entry.crc = FileUtils.checksumCRC32(f)
|
||||
}
|
||||
zos.putNextEntry(entry)
|
||||
if (f.isFile) {
|
||||
zos.write(f.readBytes())
|
||||
}
|
||||
zos.closeEntry()
|
||||
}
|
||||
if (compressionLevel == "Z") {
|
||||
zos.setMethod(DEFLATED)
|
||||
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
|
||||
|
||||
val indexUncompressed = File(tempDir, "index.json")
|
||||
indexReadWriteLock.readLock().lock()
|
||||
val json = groovy.json.JsonBuilder(assetIndex)
|
||||
indexReadWriteLock.readLock().unlock()
|
||||
indexUncompressed.writeText(json.toString())
|
||||
|
||||
val indexCompressed = File(tempDir, "index.json.br")
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
brotli,
|
||||
"-$compressionLevel",
|
||||
indexUncompressed.absolutePath,
|
||||
"-o", indexCompressed.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
zos.write(indexCompressed.readBytes())
|
||||
indexUncompressed.delete()
|
||||
indexCompressed.delete()
|
||||
|
||||
zos.closeEntry()
|
||||
}
|
||||
zos.close()
|
||||
|
||||
tempDir.deleteRecursively()
|
||||
println("APK transformed successfully")
|
||||
}
|
||||
|
||||
fun transformAppBundle() {
|
||||
val buildDir = project.buildDir
|
||||
val bundle = File(buildDir, "outputs/bundle/release/app-release.aab")
|
||||
val bundleTmp = File(buildDir, "outputs/bundle/release/tmp.zip")
|
||||
|
||||
val apks = getApks(false)
|
||||
val apkCount = apks.count { it.name.startsWith("app-") && it.name.endsWith("-release.apk") }
|
||||
|
||||
if (!bundle.exists()) {
|
||||
throw Exception("Bundle not found at: $bundle")
|
||||
}
|
||||
|
||||
if (apkCount < 3) {
|
||||
throw Exception("Excepected 3 apks per abi but only found $apkCount")
|
||||
}
|
||||
|
||||
val aabTempDir = File(project.buildDir, "tmp/aab-transform")
|
||||
aabTempDir.deleteRecursively()
|
||||
aabTempDir.mkdirs()
|
||||
|
||||
val apksUnzipped = File(project.buildDir, "tmp/apks-unzipped")
|
||||
apksUnzipped.deleteRecursively()
|
||||
|
||||
val arm32TempDir = File(apksUnzipped, "armeabi-v7a")
|
||||
arm32TempDir.mkdirs()
|
||||
val arm64TempDir = File(apksUnzipped, "arm64-v8a")
|
||||
arm64TempDir.mkdirs()
|
||||
val x86TempDir = File(apksUnzipped, "x86_64")
|
||||
x86TempDir.mkdirs()
|
||||
|
||||
copy {
|
||||
from(zipTree(bundle))
|
||||
into(aabTempDir)
|
||||
}
|
||||
copy {
|
||||
from(zipTree(apks.first { it.name.contains("armeabi-v7a") }))
|
||||
into(arm32TempDir)
|
||||
}
|
||||
copy {
|
||||
from(zipTree(apks.first { it.name.contains("arm64-v8a") }))
|
||||
into(arm64TempDir)
|
||||
}
|
||||
copy {
|
||||
from(zipTree(apks.first { it.name.contains("x86_64") }))
|
||||
into(x86TempDir)
|
||||
}
|
||||
|
||||
val libs = File(aabTempDir, "base/lib").listFiles()!!
|
||||
|
||||
for (dstLibs in libs) {
|
||||
println("Copying lib: ${dstLibs.name}")
|
||||
val srcDir = File(apksUnzipped, dstLibs.name)
|
||||
if (!srcDir.exists()) {
|
||||
continue
|
||||
}
|
||||
val srcLibs = File(srcDir, "lib/${dstLibs.name}/")
|
||||
|
||||
dstLibs.listFiles()!!.forEach { it.delete() }
|
||||
srcLibs.listFiles()!!.forEach { it.copyTo(File(dstLibs, it.name)) }
|
||||
}
|
||||
|
||||
val zos = ZipOutputStream(bundleTmp.outputStream())
|
||||
val bundleZip = ZipFile(bundle)
|
||||
val bundleEntries = bundleZip.entries()
|
||||
|
||||
val brotli = findToolInPath("brotli")
|
||||
?: throw Exception("Brotli not found in path")
|
||||
val optipng = findToolInPath("optipng")
|
||||
?: throw Exception("Optipng not found in path")
|
||||
|
||||
val indexReadWriteLock = ReentrantReadWriteLock()
|
||||
val assetIndex = mutableMapOf<String, String>()
|
||||
|
||||
while (bundleEntries.hasMoreElements()) {
|
||||
val entry = bundleEntries.nextElement()
|
||||
|
||||
/*
|
||||
if (entry.name == "base/assets/flutter_assets/assets/firka.i") {
|
||||
println("Patching: ${entry.name}")
|
||||
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
|
||||
|
||||
val indexUncompressed = File(aabTempDir, "index.json")
|
||||
indexReadWriteLock.readLock().lock()
|
||||
val json = groovy.json.JsonBuilder(assetIndex)
|
||||
indexReadWriteLock.readLock().unlock()
|
||||
indexUncompressed.writeText(json.toString())
|
||||
|
||||
val indexCompressed = File(aabTempDir, "index.json.br")
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
brotli,
|
||||
"-Z",
|
||||
indexUncompressed.absolutePath,
|
||||
"-o", indexCompressed.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
zos.write(indexCompressed.readBytes())
|
||||
indexUncompressed.delete()
|
||||
indexCompressed.delete()
|
||||
|
||||
zos.closeEntry()
|
||||
continue
|
||||
}
|
||||
if (entry.name.startsWith("base/lib")) {
|
||||
println("Patching: ${entry.name}")
|
||||
zos.putNextEntry(ZipEntry(entry.name))
|
||||
|
||||
|
||||
|
||||
zos.closeEntry()
|
||||
continue
|
||||
}
|
||||
*/
|
||||
|
||||
println("Adding: ${entry.name}")
|
||||
|
||||
zos.putNextEntry(ZipEntry(entry.name))
|
||||
|
||||
if (!entry.isDirectory) {
|
||||
val data = bundleZip.getInputStream(entry).readAllBytes()
|
||||
zos.write(data)
|
||||
}
|
||||
zos.closeEntry()
|
||||
}
|
||||
bundleZip.close()
|
||||
zos.close()
|
||||
|
||||
bundle.delete()
|
||||
signBundle(bundleTmp, bundle)
|
||||
bundleTmp.delete()
|
||||
|
||||
aabTempDir.deleteRecursively()
|
||||
println("AAB transformed successfully")
|
||||
|
||||
}
|
||||
|
||||
fun File.sha256(): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
val digest = md.digest(this.readBytes())
|
||||
return digest.fold("") { str, it -> str + "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun getApks(debug: Boolean): List<File> {
|
||||
val buildDir = project.buildDir
|
||||
val apkDir = File(buildDir, "outputs/flutter-apk")
|
||||
val apks = apkDir.listFiles()!!
|
||||
val flavor = if (debug) { "debug" } else { "release" }
|
||||
|
||||
return apks
|
||||
.filter { apk -> apk.name.startsWith("app-") && apk.name.endsWith("-$flavor.apk") }
|
||||
.toList()
|
||||
}
|
||||
|
||||
fun getDebugKeystorePath(): String {
|
||||
val userHome = System.getProperty("user.home")
|
||||
val debugKeystore = File(userHome, ".android/debug.keystore")
|
||||
|
||||
if (!debugKeystore.exists()) {
|
||||
throw GradleException("Debug keystore not found at: ${debugKeystore.absolutePath}")
|
||||
}
|
||||
|
||||
return debugKeystore.absolutePath
|
||||
}
|
||||
|
||||
fun getDefaultAndroidSdkPath(): String? {
|
||||
val os = System.getProperty("os.name").lowercase()
|
||||
val userHome = System.getProperty("user.home")
|
||||
val zipAlign = File("/usr/bin/zipalign")
|
||||
|
||||
if (zipAlign.exists()) {
|
||||
return "/usr/bin"
|
||||
}
|
||||
|
||||
return when {
|
||||
os.contains("win") ->
|
||||
"$userHome\\AppData\\Local\\Android\\Sdk"
|
||||
os.contains("mac") ->
|
||||
"$userHome/Library/Android/sdk"
|
||||
os.contains("linux") ->
|
||||
"$userHome/Android/Sdk"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
fun findToolInPath(toolName: String): String? {
|
||||
val pathEnvironment = System.getenv("PATH")
|
||||
val pathDirs = pathEnvironment.split(File.pathSeparator)
|
||||
|
||||
val executableNames = when {
|
||||
System.getProperty("os.name").lowercase().contains("win") ->
|
||||
listOf("$toolName.exe", toolName)
|
||||
else ->
|
||||
listOf(toolName)
|
||||
}
|
||||
|
||||
for (pathDir in pathDirs) {
|
||||
for (execName in executableNames) {
|
||||
val possibleTool = File(pathDir, execName)
|
||||
if (possibleTool.exists() && possibleTool.canExecute()) {
|
||||
return possibleTool.absolutePath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
fun findToolInSdkPath(toolName: String): String? {
|
||||
var androidHome : String? = System.getenv("ANDROID_HOME")
|
||||
?: System.getenv("ANDROID_SDK_ROOT")
|
||||
|
||||
if (androidHome == null) androidHome = getDefaultAndroidSdkPath()
|
||||
|
||||
if (androidHome != null) {
|
||||
val buildTools = File(androidHome, "build-tools")
|
||||
if (buildTools.exists()) {
|
||||
val latestVersion = buildTools.listFiles()
|
||||
?.filter { it.isDirectory }
|
||||
?.filter { it.name != "debian" }
|
||||
?.maxByOrNull { it.name }
|
||||
|
||||
if (latestVersion != null) {
|
||||
val toolExec = File(latestVersion, toolName)
|
||||
if (toolExec.exists()) {
|
||||
return toolExec.absolutePath
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val toolExec = File(androidHome, toolName)
|
||||
if (toolExec.exists()) {
|
||||
return toolExec.absolutePath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!toolName.contains(".exe")) {
|
||||
val exeTool = findToolInSdkPath("$toolName.exe")
|
||||
if (exeTool != null) return exeTool
|
||||
}
|
||||
if (!toolName.contains(".sh")) {
|
||||
val shTool = findToolInSdkPath("$toolName.sh")
|
||||
if (shTool != null) return shTool
|
||||
}
|
||||
if (!toolName.contains(".bat")) {
|
||||
val batTool = findToolInSdkPath("$toolName.bat")
|
||||
if (batTool != null) return batTool
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
fun signWithDebugKey(input: File, output: File) {
|
||||
val debugKeystore = getDebugKeystorePath()
|
||||
val debugKeystorePassword = "android"
|
||||
val debugKeyAlias = "androiddebugkey"
|
||||
val debugKeyPassword = "android"
|
||||
|
||||
val zipAlign: String = findToolInSdkPath("zipalign")
|
||||
?: throw Exception("Could not find zipalign in ANDROID_SDK")
|
||||
val apksigner: String = findToolInSdkPath("apksigner")
|
||||
?: throw Exception("Could not find zipalign in ANDROID_SDK")
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
zipAlign,
|
||||
"-v", "4",
|
||||
input.absolutePath,
|
||||
output.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
apksigner, "sign",
|
||||
"--ks", debugKeystore,
|
||||
"--ks-pass", "pass:$debugKeystorePassword",
|
||||
"--ks-key-alias", debugKeyAlias,
|
||||
"--key-pass", "pass:$debugKeyPassword",
|
||||
output.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
println("APK signed and aligned successfully")
|
||||
}
|
||||
|
||||
fun signWithReleaseKey(input: File, output: File) {
|
||||
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (!propsFile.exists()) {
|
||||
throw Exception("Release keystore not found!")
|
||||
}
|
||||
|
||||
val props = loadProperties(propsFile)
|
||||
|
||||
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
|
||||
val releaseKeystorePassword = props["storePassword"] as String
|
||||
val releaseKeyAlias = props["keyAlias"] as String
|
||||
val releaseKeyPassword = props["keyPassword"] as String
|
||||
|
||||
val zipAlign: String = findToolInSdkPath("zipalign")
|
||||
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
|
||||
val apksigner: String = findToolInSdkPath("apksigner")
|
||||
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
zipAlign,
|
||||
"-v", "4",
|
||||
input.absolutePath,
|
||||
output.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
exec {
|
||||
commandLine(
|
||||
apksigner, "sign",
|
||||
"--ks", releaseKeystore,
|
||||
"--ks-pass", "pass:$releaseKeystorePassword",
|
||||
"--ks-key-alias", releaseKeyAlias,
|
||||
"--key-pass", "pass:$releaseKeyPassword",
|
||||
output.absolutePath
|
||||
)
|
||||
}
|
||||
|
||||
println("APK signed and aligned successfully")
|
||||
}
|
||||
|
||||
fun signBundle(input: File, output: File) {
|
||||
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
|
||||
val propsFile = File(secretsDir, "keystore.properties")
|
||||
|
||||
if (!propsFile.exists()) {
|
||||
throw Exception("Release keystore not found!")
|
||||
}
|
||||
|
||||
val props = loadProperties(propsFile)
|
||||
|
||||
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
|
||||
val releaseKeystorePassword = props["storePassword"] as String
|
||||
val releaseKeyAlias = props["keyAlias"] as String
|
||||
val releaseKeyPassword = props["keyPassword"] as String
|
||||
|
||||
// val zipAlign: String = findToolInSdkPath("zipalign")
|
||||
// ?: throw Exception("Could not find zipalign in ANDROID_SDK")
|
||||
val jarsigner: String = findToolInPath("jarsigner")
|
||||
?: throw Exception("Could not find jarsigner in PATH")
|
||||
|
||||
/*
|
||||
exec {
|
||||
commandLine(
|
||||
zipAlign,
|
||||
"-v", "4",
|
||||
input.absolutePath,
|
||||
output.absolutePath
|
||||
)
|
||||
}
|
||||
*/
|
||||
input.copyTo(output, true)
|
||||
|
||||
exec {
|
||||
// -keystore $KEYSTORE -storetype $STORETYPE -storepass $STOREPASS -digestalg SHA1 -sigalg SHA256withRSA application.zip $KEYALIAS
|
||||
commandLine(
|
||||
jarsigner,
|
||||
"-verbose",
|
||||
"-sigalg", "SHA256withRSA",
|
||||
"-digestalg", "SHA-256",
|
||||
"-keystore", releaseKeystore,
|
||||
"-storepass", releaseKeystorePassword,
|
||||
output.absolutePath,
|
||||
releaseKeyAlias
|
||||
)
|
||||
}
|
||||
|
||||
println("AAB signed and aligned successfully")
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,18 @@
|
||||
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
|
||||
<application
|
||||
android:name=".AppMain"
|
||||
android:icon="@mipmap/launcher_icon">
|
||||
|
||||
|
||||
<service
|
||||
android:name=".WearSyncForegroundService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
@@ -35,7 +41,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_ace"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_ace_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -49,7 +55,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_ace_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_ace_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -63,7 +69,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_bi"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_bi_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -77,7 +83,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_bi_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_bi_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -91,7 +97,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_cactus"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_cactus_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -105,7 +111,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_cc"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_cc_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -119,7 +125,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_enby"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_enby_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -133,7 +139,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_enby_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_enby_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -147,7 +153,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_fidesz"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_fidesz_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -161,7 +167,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_filc"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_filc_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -175,7 +181,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_filco"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_filco_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -189,7 +195,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_galaxy"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_galaxy_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -203,7 +209,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_gay"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_gay_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -217,7 +223,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_gay_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_gay_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -231,7 +237,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_half_firka_2"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_half_firka_2_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -245,7 +251,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_kreta"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_kreta_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -259,7 +265,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lesb"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lesb_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -273,7 +279,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lesb_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lesb_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -287,7 +293,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lgbtq"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lgbtq_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -301,7 +307,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lgbtq_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lgbtq_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -315,7 +321,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lgbtqp"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lgbtqp_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -329,7 +335,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lgbtqp_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lgbtqp_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -343,7 +349,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_lidl"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_lidl_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -357,7 +363,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_mkkp"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_mkkp_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -371,7 +377,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_nuke"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_nuke_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -385,7 +391,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_modern"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_modern_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -399,7 +405,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_o1g"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_o1g_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -413,7 +419,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_old"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_old_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -427,7 +433,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_paper"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_paper_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -441,7 +447,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_pear"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_pear_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -455,7 +461,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_pixel"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_pixel_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -469,7 +475,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_pixelized"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_pixelized_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -483,7 +489,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_pride"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_pride_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -497,7 +503,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_proto"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_proto_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -511,7 +517,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_refilc"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_refilc_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -525,7 +531,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_refulc"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_refulc_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -539,7 +545,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_repont"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_repont_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -553,7 +559,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_szivacs"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_szivacs_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -567,7 +573,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_tisza"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_tisza_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -581,7 +587,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_trans"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_trans_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -595,7 +601,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_trans_f"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_trans_f_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -609,7 +615,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_void_icon"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_void_icon_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -623,7 +629,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_xmas1"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_xmas1_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -637,7 +643,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_xmas2"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_xmas2_round" >
|
||||
|
||||
<intent-filter>
|
||||
@@ -651,7 +657,7 @@
|
||||
android:targetActivity=".MainActivity"
|
||||
android:exported="true"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_xmas3"
|
||||
android:icon="@mipmap/launcher_icon"
|
||||
android:roundIcon="@mipmap/ic_xmas3_round" >
|
||||
|
||||
<intent-filter>
|
||||
|
||||
@@ -1,99 +1,5 @@
|
||||
package app.firka.naplo
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Application
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import org.brotli.dec.BrotliInputStream
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipFile
|
||||
|
||||
class AppMain : Application() {
|
||||
|
||||
private fun File.sha256(): String {
|
||||
if (!exists()) return "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
val digest = md.digest(this.readBytes())
|
||||
return digest.fold("") { str, it -> str + "%02x".format(it) }
|
||||
}
|
||||
|
||||
@SuppressLint("UnsafeDynamicallyLoadedCode")
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
var useUncompressedLibs = false
|
||||
|
||||
val abi = Build.SUPPORTED_ABIS[0]
|
||||
|
||||
val apks = File(applicationInfo.nativeLibraryDir, "../..").absoluteFile
|
||||
.listFiles()!!
|
||||
.filter { file -> file.name.endsWith(".apk") }
|
||||
.toList()
|
||||
|
||||
var nativesApkN: ZipFile? = null
|
||||
for (apk in apks) {
|
||||
if (nativesApkN != null) break
|
||||
|
||||
val zip = ZipFile(apk)
|
||||
val entries = zip.entries()
|
||||
|
||||
while (entries.hasMoreElements()) {
|
||||
val entry = entries.nextElement()
|
||||
|
||||
if (entry.name.endsWith("$abi/index.so")) {
|
||||
zip.close()
|
||||
nativesApkN = ZipFile(apk)
|
||||
break
|
||||
}
|
||||
if (entry.name.endsWith("$abi/libflutter.so")) {
|
||||
useUncompressedLibs = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
zip.close()
|
||||
}
|
||||
|
||||
if (useUncompressedLibs) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nativesApkN == null) {
|
||||
throw Exception("Can't find native libraries")
|
||||
}
|
||||
val nativesApk: ZipFile = nativesApkN
|
||||
|
||||
val compressedLibsIndex = nativesApk.getInputStream(
|
||||
nativesApk.getEntry("lib/$abi/index.so")
|
||||
)
|
||||
val compressedLibs = JSONObject(compressedLibsIndex.readBytes().toString(Charsets.UTF_8))
|
||||
|
||||
for (so in compressedLibs.keys()) {
|
||||
val soFile = File(cacheDir, so)
|
||||
|
||||
if (soFile.sha256() == compressedLibs.getString(so)) {
|
||||
System.load(soFile.absolutePath)
|
||||
return
|
||||
}
|
||||
|
||||
Log.d("AppMain", "Decompressing: $so")
|
||||
val brInput = nativesApk.getInputStream(
|
||||
nativesApk.getEntry("lib/$abi/${so.replace(".so", "-br.so")}")
|
||||
)
|
||||
val soOutput = FileOutputStream(soFile)
|
||||
|
||||
val brIn = BrotliInputStream(brInput)
|
||||
brIn.copyTo(soOutput)
|
||||
|
||||
brInput.close()
|
||||
soOutput.close()
|
||||
|
||||
System.load(soFile.absolutePath)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
class AppMain : Application() {}
|
||||
@@ -1,19 +1,28 @@
|
||||
package app.firka.naplo
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.glance.appwidget.updateAll
|
||||
import app.firka.naplo.glance.TimetableWidget
|
||||
import app.firka.naplo.glance.TimetableWidgetReceiver
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
|
||||
private val channel = "firka.app/main"
|
||||
private val wearSyncChannel = "app.firka/wear_sync"
|
||||
|
||||
private fun forceIconUpdate() {
|
||||
try {
|
||||
@@ -30,6 +39,57 @@ class MainActivity : FlutterActivity() {
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, wearSyncChannel).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"startWearSyncService" -> {
|
||||
val args = call.arguments as? Map<*, *>
|
||||
val cachePath = args?.get("cachePath") as? String
|
||||
val appDirPath = args?.get("appDirPath") as? String
|
||||
if (cachePath != null && appDirPath != null) {
|
||||
val messenger = flutterEngine.dartExecutor.binaryMessenger
|
||||
val ch = MethodChannel(messenger, wearSyncChannel)
|
||||
ch.invokeMethod("getLocalizedString", "wearSyncNotificationTitle", object : MethodChannel.Result {
|
||||
override fun success(titleResult: Any?) {
|
||||
val title = titleResult as? String ?: "Syncing with watch"
|
||||
ch.invokeMethod("getLocalizedString", "wearSyncNotificationText", object : MethodChannel.Result {
|
||||
override fun success(textResult: Any?) {
|
||||
val text = textResult as? String ?: ""
|
||||
val intent = Intent(this@MainActivity, WearSyncForegroundService::class.java).apply {
|
||||
action = WearSyncForegroundService.ACTION_START
|
||||
putExtra(WearSyncForegroundService.EXTRA_CACHE_PATH, cachePath)
|
||||
putExtra(WearSyncForegroundService.EXTRA_APP_DIR_PATH, appDirPath)
|
||||
putExtra(WearSyncForegroundService.EXTRA_NOTIFICATION_TITLE, title)
|
||||
putExtra(WearSyncForegroundService.EXTRA_NOTIFICATION_TEXT, text)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
startForegroundService(intent)
|
||||
} else {
|
||||
startService(intent)
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
override fun error(code: String, msg: String?, details: Any?) { result.success(null) }
|
||||
override fun notImplemented() { result.success(null) }
|
||||
})
|
||||
}
|
||||
override fun error(code: String, msg: String?, details: Any?) { result.error(code, msg, details) }
|
||||
override fun notImplemented() { result.notImplemented() }
|
||||
})
|
||||
} else {
|
||||
result.error("INVALID_ARGS", "cachePath and appDirPath required", null)
|
||||
}
|
||||
}
|
||||
"stopWearSyncService" -> {
|
||||
val intent = Intent(this, WearSyncForegroundService::class.java).apply {
|
||||
action = WearSyncForegroundService.ACTION_STOP
|
||||
}
|
||||
startService(intent)
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel).setMethodCallHandler {
|
||||
call, result ->
|
||||
when (call.method) {
|
||||
@@ -97,7 +157,29 @@ class MainActivity : FlutterActivity() {
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
result.success(true)
|
||||
result.success(true)
|
||||
}
|
||||
"refreshTimetableWidget" -> {
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
val appContext = context.applicationContext
|
||||
val appWidgetManager = AppWidgetManager.getInstance(appContext)
|
||||
val componentName = ComponentName(appContext, TimetableWidgetReceiver::class.java)
|
||||
val ids = appWidgetManager.getAppWidgetIds(componentName)
|
||||
if (ids.isNotEmpty()) {
|
||||
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
|
||||
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
|
||||
}
|
||||
appContext.sendBroadcast(intent)
|
||||
}
|
||||
TimetableWidget().updateAll(appContext)
|
||||
result.success(true)
|
||||
} catch (e: Exception) {
|
||||
result.error("refresh_failed", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
result.notImplemented()
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package app.firka.naplo
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ObjectInputStream
|
||||
import com.google.android.gms.wearable.MessageClient
|
||||
import com.google.android.gms.wearable.MessageEvent
|
||||
import com.google.android.gms.wearable.Wearable
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.embedding.engine.dart.DartExecutor
|
||||
import io.flutter.embedding.engine.loader.FlutterLoader
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* Foreground service that keeps the app able to respond to Wear OS sync requests.
|
||||
* When the watch sends request_sync, starts a Dart background isolate to fetch data,
|
||||
* then reads the cache file and sends sync_data to the watch.
|
||||
*/
|
||||
class WearSyncForegroundService : Service(), MessageClient.OnMessageReceivedListener {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
private var cachePath: String? = null
|
||||
private var appDirPath: String? = null
|
||||
|
||||
private val channelId = "firka_wear_sync"
|
||||
private val notificationId = 4001
|
||||
private var notificationTitle: String = "Syncing with watch"
|
||||
private var notificationText: String = ""
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_START -> {
|
||||
cachePath = intent.getStringExtra(EXTRA_CACHE_PATH)
|
||||
appDirPath = intent.getStringExtra(EXTRA_APP_DIR_PATH)
|
||||
notificationTitle = intent.getStringExtra(EXTRA_NOTIFICATION_TITLE) ?: "Syncing with watch"
|
||||
notificationText = intent.getStringExtra(EXTRA_NOTIFICATION_TEXT) ?: ""
|
||||
startForegroundWithNotification()
|
||||
Wearable.getMessageClient(this@WearSyncForegroundService)
|
||||
.addListener(this@WearSyncForegroundService)
|
||||
}
|
||||
ACTION_STOP -> {
|
||||
stopForegroundService()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onDestroy() {
|
||||
try {
|
||||
Wearable.getMessageClient(this@WearSyncForegroundService)
|
||||
.removeListener(this@WearSyncForegroundService)
|
||||
.addOnCompleteListener { }
|
||||
} catch (_: Exception) { }
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onMessageReceived(messageEvent: MessageEvent) {
|
||||
if (messageEvent.path != PATH_WATCH_CONNECTIVITY ||
|
||||
!isRequestSyncPayload(messageEvent.data)
|
||||
) return
|
||||
val cPath = cachePath
|
||||
val aPath = appDirPath
|
||||
if (cPath == null || aPath == null) return
|
||||
scope.launch {
|
||||
runSyncInBackground(cPath, aPath)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* watch_connectivity plugin sends with path "watch_connectivity" and serializes the message
|
||||
* map with Java ObjectOutputStream. Parse payload and check for id == "request_sync".
|
||||
*/
|
||||
private fun isRequestSyncPayload(data: ByteArray?): Boolean {
|
||||
if (data == null || data.isEmpty()) return false
|
||||
return try {
|
||||
ObjectInputStream(ByteArrayInputStream(data)).use { ois ->
|
||||
val map = ois.readObject()
|
||||
if (map is Map<*, *>) map["id"] == "request_sync" else false
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun startForegroundWithNotification() {
|
||||
val notification = buildNotification()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(notificationId, notification, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startForeground(notificationId, notification)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
packageManager.getLaunchIntentForPackage(packageName),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
return NotificationCompat.Builder(this, channelId)
|
||||
.setContentTitle(notificationTitle)
|
||||
.setContentText(notificationText)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val channel = NotificationChannel(
|
||||
channelId,
|
||||
"Wear sync",
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply { setShowBadge(false) }
|
||||
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
|
||||
.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopForegroundService() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
}
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private suspend fun runSyncInBackground(cPath: String, aPath: String) = withContext(Dispatchers.Default) {
|
||||
val flutterLoader = FlutterLoader()
|
||||
if (!flutterLoader.initialized()) {
|
||||
withContext(Dispatchers.Main) {
|
||||
flutterLoader.startInitialization(applicationContext)
|
||||
flutterLoader.ensureInitializationComplete(applicationContext, null)
|
||||
}
|
||||
}
|
||||
val (engine, bgChannel) = withContext(Dispatchers.Main) {
|
||||
val eng = FlutterEngine(applicationContext)
|
||||
val entrypoint = DartExecutor.DartEntrypoint(
|
||||
flutterLoader.findAppBundlePath(),
|
||||
"package:firka/services/wear_sync_background.dart",
|
||||
"wearSyncBackgroundEntrypoint"
|
||||
)
|
||||
eng.dartExecutor.executeDartEntrypoint(entrypoint)
|
||||
val ch = MethodChannel(eng.dartExecutor.binaryMessenger, "app.firka/wear_sync_background")
|
||||
Pair(eng, ch)
|
||||
}
|
||||
val completer = CompletableDeferred<Unit>()
|
||||
delay(500)
|
||||
withContext(Dispatchers.Main) {
|
||||
bgChannel.invokeMethod("request_sync", mapOf(
|
||||
"cachePath" to cPath,
|
||||
"appDirPath" to aPath
|
||||
), object : MethodChannel.Result {
|
||||
override fun success(result: Any?) {
|
||||
completer.complete(Unit)
|
||||
}
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
Log.e(TAG, "request_sync error: $errorCode $errorMessage")
|
||||
completer.complete(Unit)
|
||||
}
|
||||
override fun notImplemented() {
|
||||
completer.complete(Unit)
|
||||
}
|
||||
})
|
||||
}
|
||||
try {
|
||||
withTimeout(30_000) {
|
||||
completer.await()
|
||||
}
|
||||
} catch (_: kotlinx.coroutines.TimeoutCancellationException) {
|
||||
Log.w(TAG, "Wear sync isolate timed out")
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
engine.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WearSyncService"
|
||||
const val ACTION_START = "app.firka.naplo.WearSyncForegroundService.START"
|
||||
const val ACTION_STOP = "app.firka.naplo.WearSyncForegroundService.STOP"
|
||||
const val EXTRA_CACHE_PATH = "cachePath"
|
||||
const val EXTRA_APP_DIR_PATH = "appDirPath"
|
||||
const val EXTRA_NOTIFICATION_TITLE = "notificationTitle"
|
||||
const val EXTRA_NOTIFICATION_TEXT = "notificationText"
|
||||
private const val PATH_WATCH_CONNECTIVITY = "watch_connectivity"
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import app.firka.naplo.model.Colors
|
||||
import app.firka.naplo.model.Lesson
|
||||
import app.firka.naplo.glance.WidgetLesson
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
|
||||
val hhmm = DateTimeFormatterBuilder()
|
||||
@@ -26,8 +26,12 @@ val hhmm = DateTimeFormatterBuilder()
|
||||
.toFormatter()
|
||||
|
||||
@Composable
|
||||
fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
modifier: GlanceModifier = GlanceModifier) {
|
||||
fun LessonCard(
|
||||
lesson: WidgetLesson,
|
||||
colors: Colors,
|
||||
modifier: GlanceModifier = GlanceModifier,
|
||||
roomBadgeWidthDp: Float = 48f,
|
||||
) {
|
||||
Box(modifier =
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
@@ -38,7 +42,7 @@ fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
var bgColor = colors.a15p
|
||||
var fgColor = colors.textSecondary
|
||||
|
||||
if (lesson.substituteTeacher == null) {
|
||||
if (lesson.substituteTeacher != null) {
|
||||
bgColor = colors.warning15p
|
||||
fgColor = colors.warningText
|
||||
}
|
||||
@@ -46,9 +50,21 @@ fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
|
||||
Box(modifier = GlanceModifier.padding(12.dp)) {
|
||||
Row {
|
||||
val badgeStyle = TextStyle(
|
||||
color = ColorProvider(colors.textSecondary, colors.textSecondary),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
val badgePadding = GlanceModifier.padding(8.dp, 4.dp)
|
||||
val lessonNumberBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(24.dp)
|
||||
val roomBadgeModifier = GlanceModifier.cornerRadius(16.dp).width(roomBadgeWidthDp.dp)
|
||||
|
||||
Row(modifier = GlanceModifier.width(226.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (lesson.lessonNumber != null) {
|
||||
Box(modifier = GlanceModifier.cornerRadius(16.dp).background(bgColor)) {
|
||||
Box(
|
||||
modifier = lessonNumberBadgeModifier.background(bgColor),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
lesson.lessonNumber.toString(),
|
||||
style = TextStyle(
|
||||
@@ -56,7 +72,7 @@ fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Bold
|
||||
),
|
||||
modifier = GlanceModifier.padding(8.dp, 4.dp),
|
||||
modifier = GlanceModifier.padding(4.dp, 4.dp),
|
||||
)
|
||||
}
|
||||
Spacer(modifier = GlanceModifier.width(4.dp))
|
||||
@@ -72,8 +88,6 @@ fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
)
|
||||
}
|
||||
|
||||
// Spacer(modifier = GlanceModifier.width(10.dp))
|
||||
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
lesson.start.format(hhmm),
|
||||
@@ -84,24 +98,15 @@ fun LessonCard(lesson: Lesson, colors: Colors,
|
||||
),
|
||||
)
|
||||
Spacer(modifier = GlanceModifier.width(8.dp))
|
||||
Box(modifier = GlanceModifier.cornerRadius(16.dp).background(colors.a15p)) {
|
||||
var roomName = "N/A";
|
||||
if (lesson.roomName != null) {
|
||||
roomName = lesson.roomName!!;
|
||||
}
|
||||
|
||||
if (roomName.length < 2) {
|
||||
roomName = " $roomName"
|
||||
}
|
||||
|
||||
val roomName = (lesson.roomName ?: "N/A").take(5)
|
||||
Box(
|
||||
modifier = roomBadgeModifier.background(colors.a15p),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
roomName,
|
||||
style = TextStyle(
|
||||
color = ColorProvider(colors.textSecondary, colors.textSecondary),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Bold
|
||||
),
|
||||
modifier = GlanceModifier.padding(8.dp, 4.dp),
|
||||
style = badgeStyle,
|
||||
modifier = GlanceModifier.padding(4.dp, 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,10 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.glance.GlanceId
|
||||
import androidx.glance.GlanceModifier
|
||||
import androidx.glance.LocalSize
|
||||
import androidx.glance.appwidget.GlanceAppWidget
|
||||
import androidx.glance.appwidget.provideContent
|
||||
import androidx.glance.appwidget.SizeMode
|
||||
import androidx.glance.background
|
||||
import androidx.glance.color.ColorProvider
|
||||
import androidx.glance.currentState
|
||||
@@ -26,7 +28,9 @@ import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import app.firka.naplo.model.Colors
|
||||
import app.firka.naplo.model.Lesson
|
||||
import app.firka.naplo.glance.WidgetLesson
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.time.LocalDate
|
||||
@@ -37,20 +41,51 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
override val stateDefinition: GlanceStateDefinition<*>?
|
||||
get() = HomeWidgetGlanceStateDefinition()
|
||||
|
||||
override val sizeMode: SizeMode
|
||||
get() = SizeMode.Exact
|
||||
|
||||
override suspend fun provideGlance(context: Context, id: GlanceId) {
|
||||
val data = withContext(Dispatchers.IO) {
|
||||
loadWidgetData(context)
|
||||
}
|
||||
provideContent {
|
||||
GlanceContent(context, currentState())
|
||||
GlanceContent(context, currentState(), data)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState) {
|
||||
private fun loadWidgetData(context: Context): WidgetData? {
|
||||
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
|
||||
val widgetStateFile = File(appFlutter, "widget_state.json")
|
||||
if (!widgetStateFile.exists()) return null
|
||||
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
|
||||
val colors = Colors(widgetState)
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
val lessons = mutableListOf<WidgetLesson>()
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(WidgetLesson(tt.getJSONObject(i)))
|
||||
}
|
||||
val displayDateStr = widgetState.optString("displayDate", "")
|
||||
val targetDate = if (displayDateStr.isNotEmpty()) {
|
||||
try {
|
||||
LocalDate.parse(displayDateStr)
|
||||
} catch (_: Exception) {
|
||||
LocalDate.now()
|
||||
}
|
||||
} else {
|
||||
LocalDate.now()
|
||||
}
|
||||
val start = LocalDateTime.of(targetDate.year, targetDate.month, targetDate.dayOfMonth, 0, 0)
|
||||
val end = start.plusHours(23)
|
||||
val filtered = lessons.filter { it.start.isAfter(start) && it.end.isBefore(end) }
|
||||
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
|
||||
return WidgetData(colors, headerText, filtered)
|
||||
}
|
||||
|
||||
if (!widgetStateFile.exists()) {
|
||||
Box(modifier =
|
||||
GlanceModifier
|
||||
@Composable
|
||||
private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState, data: WidgetData?) {
|
||||
if (data == null) {
|
||||
Box(
|
||||
modifier = GlanceModifier
|
||||
.background(Color(0xFFFAFFF0))
|
||||
.padding(16.dp)
|
||||
.fillMaxSize(),
|
||||
@@ -65,47 +100,67 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
|
||||
val colors = Colors(widgetState)
|
||||
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
var lessons = mutableListOf<Lesson>()
|
||||
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(Lesson(tt.getJSONObject(i)))
|
||||
val size = LocalSize.current
|
||||
val lessonRowHeightDp = 52f
|
||||
val scale = lessonRowHeightDp / 52f
|
||||
val headerHeightDp = 20f * scale
|
||||
val verticalPaddingDp = 32f * scale
|
||||
val spacerDp = 4f * scale
|
||||
val paddingDp = 16f * scale
|
||||
val availableHeightDp = size.height.value - verticalPaddingDp - headerHeightDp - spacerDp
|
||||
val maxVisibleLessons = (availableHeightDp / lessonRowHeightDp).toInt().coerceAtLeast(0)
|
||||
val maxLessons = (maxVisibleLessons.coerceAtMost(16) / 2 * 2).coerceAtLeast(1)
|
||||
val displayLessons = data.lessons.take(maxLessons)
|
||||
val lessonChunks = displayLessons.chunked(2)
|
||||
val showDate = maxLessons > 1
|
||||
val maxRoomNameLen = displayLessons.maxOfOrNull { (it.roomName ?: "N/A").take(5).length } ?: 0
|
||||
val roomBadgeWidthDp = if (maxRoomNameLen <= 3) 28f else 48f
|
||||
val dateSectionHeight = if (showDate) headerHeightDp + spacerDp else 0f
|
||||
val lessonListHeight = when (val n = displayLessons.size) {
|
||||
0 -> 0f
|
||||
else -> n * lessonRowHeightDp + (n - 1) * spacerDp
|
||||
}
|
||||
val remainingHeight = (size.height.value - 2 * paddingDp - dateSectionHeight - lessonListHeight).coerceAtLeast(0f)
|
||||
val verticalPaddingAroundLessons = remainingHeight / 2f
|
||||
|
||||
val now = LocalDate.now()
|
||||
val start = LocalDateTime.of(now.year, now.month, now.dayOfMonth, 0, 0)
|
||||
val end = start.plusHours(23)
|
||||
lessons = lessons.filter { lesson -> lesson.start.isAfter(start) && lesson.end.isBefore(end) }.toMutableList()
|
||||
|
||||
Box(modifier =
|
||||
GlanceModifier
|
||||
.background(colors.background)
|
||||
.padding(16.dp)
|
||||
Box(
|
||||
modifier = GlanceModifier
|
||||
.background(data.colors.background)
|
||||
.padding(paddingDp.dp)
|
||||
.fillMaxSize()
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
"Mai órarend",
|
||||
style = TextStyle(
|
||||
color = ColorProvider(colors.textSecondary, colors.textSecondary),
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium
|
||||
if (showDate) {
|
||||
Text(
|
||||
data.headerText,
|
||||
style = TextStyle(
|
||||
color = ColorProvider(data.colors.textSecondary, data.colors.textSecondary),
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
)
|
||||
)
|
||||
Spacer(modifier = GlanceModifier.height(4.dp))
|
||||
for (lesson in lessons) {
|
||||
LessonCard(lesson, colors)
|
||||
Spacer(modifier = GlanceModifier.height(4.dp))
|
||||
Spacer(modifier = GlanceModifier.height(spacerDp.dp))
|
||||
}
|
||||
Spacer(modifier = GlanceModifier.height(verticalPaddingAroundLessons.dp))
|
||||
for (chunk in lessonChunks) {
|
||||
Column {
|
||||
for (lesson in chunk) {
|
||||
LessonCard(lesson, data.colors, roomBadgeWidthDp = roomBadgeWidthDp)
|
||||
Spacer(modifier = GlanceModifier.height(spacerDp.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(modifier = GlanceModifier.height(verticalPaddingAroundLessons.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
private data class WidgetData(
|
||||
val colors: Colors,
|
||||
val headerText: String,
|
||||
val lessons: List<WidgetLesson>,
|
||||
)
|
||||
@@ -1,7 +1,25 @@
|
||||
package app.firka.naplo.glance
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import HomeWidgetGlanceWidgetReceiver
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>() {
|
||||
override val glanceAppWidget = TimetableWidget()
|
||||
|
||||
override fun onAppWidgetOptionsChanged(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetId: Int,
|
||||
newOptions: Bundle,
|
||||
) {
|
||||
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
|
||||
runBlocking {
|
||||
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
|
||||
glanceAppWidget.update(context, glanceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package app.firka.naplo.glance
|
||||
|
||||
import app.firka.naplo.getIntOrNull
|
||||
import app.firka.naplo.getStringOrNull
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
|
||||
class WidgetLesson(data: JSONObject) {
|
||||
val formatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
|
||||
.optionalStart()
|
||||
.appendLiteral('Z')
|
||||
.optionalEnd()
|
||||
.toFormatter()
|
||||
|
||||
val name: String = data.getString("Nev")
|
||||
val start: LocalDateTime = LocalDateTime.parse(data.getString("KezdetIdopont"), formatter)
|
||||
val end: LocalDateTime = LocalDateTime.parse(data.getString("VegIdopont"), formatter)
|
||||
val lessonNumber: Int? = data.getIntOrNull("Oraszam")
|
||||
val roomName: String? = data.getStringOrNull("TeremNeve")
|
||||
val substituteTeacher: String? = data.getStringOrNull("HelyettesTanarNeve")
|
||||
}
|
||||
BIN
firka/android/app/src/main/res/drawable-hdpi/android12splash.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 4.4 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 7.5 KiB |
BIN
firka/android/app/src/main/res/drawable-hdpi/splash.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
firka/android/app/src/main/res/drawable-mdpi/android12splash.png
Normal file
|
After Width: | Height: | Size: 9.7 KiB |
BIN
firka/android/app/src/main/res/drawable-mdpi/splash.png
Normal file
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 15 KiB |
BIN
firka/android/app/src/main/res/drawable-night-hdpi/splash.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
BIN
firka/android/app/src/main/res/drawable-night-mdpi/splash.png
Normal file
|
After Width: | Height: | Size: 8.8 KiB |
BIN
firka/android/app/src/main/res/drawable-night-v21/background.png
Normal file
|
After Width: | Height: | Size: 69 B |
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background"/>
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/splash"/>
|
||||
</item>
|
||||
</layer-list>
|
||||
|
After Width: | Height: | Size: 18 KiB |
BIN
firka/android/app/src/main/res/drawable-night-xhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 28 KiB |
BIN
firka/android/app/src/main/res/drawable-night-xxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
BIN
firka/android/app/src/main/res/drawable-night-xxxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
firka/android/app/src/main/res/drawable-night/background.png
Normal file
|
After Width: | Height: | Size: 69 B |
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background"/>
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/splash"/>
|
||||
</item>
|
||||
</layer-list>
|
||||
BIN
firka/android/app/src/main/res/drawable-v21/background.png
Normal file
|
After Width: | Height: | Size: 69 B |
@@ -1,12 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="?android:colorBackground" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background"/>
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/splash"/>
|
||||
</item>
|
||||
</layer-list>
|
||||
|
||||
|
After Width: | Height: | Size: 18 KiB |
BIN
firka/android/app/src/main/res/drawable-xhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 28 KiB |
BIN
firka/android/app/src/main/res/drawable-xxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
BIN
firka/android/app/src/main/res/drawable-xxxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
firka/android/app/src/main/res/drawable/background.png
Normal file
|
After Width: | Height: | Size: 69 B |
@@ -1,12 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@android:color/white" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background"/>
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/splash"/>
|
||||
</item>
|
||||
</layer-list>
|
||||
|
||||
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 6.6 KiB After Width: | Height: | Size: 9.8 KiB |
|
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 13 KiB |
22
firka/android/app/src/main/res/values-night-v31/styles.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
<item name="android:windowFullscreen">false</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
<item name="android:windowSplashScreenBackground">#7ca120</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
|
||||
<item name="android:windowSplashScreenIconBackgroundColor">#7ca120</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -5,6 +5,10 @@
|
||||
<!-- Show a splash screen on the activity. Automatically removed when
|
||||
the Flutter engine draws its first frame -->
|
||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
<item name="android:windowFullscreen">false</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
|
||||
22
firka/android/app/src/main/res/values-v31/styles.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
<item name="android:windowFullscreen">false</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
<item name="android:windowSplashScreenBackground">#7ca120</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
|
||||
<item name="android:windowSplashScreenIconBackgroundColor">#7ca120</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -5,6 +5,10 @@
|
||||
<!-- Show a splash screen on the activity. Automatically removed when
|
||||
the Flutter engine draws its first frame -->
|
||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
<item name="android:windowFullscreen">false</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:initialLayout="@layout/glance_default_loading_layout"
|
||||
android:minWidth="300dp"
|
||||
android:minHeight="100dp"
|
||||
android:minWidth="250dp"
|
||||
android:minHeight="93dp"
|
||||
android:minResizeWidth="180dp"
|
||||
android:minResizeHeight="93dp"
|
||||
android:resizeMode="horizontal|vertical"
|
||||
android:updatePeriodMillis="10000">
|
||||
android:updatePeriodMillis="1800000">
|
||||
</appwidget-provider>
|
||||
@@ -22,8 +22,8 @@ subprojects {
|
||||
if (plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.library")) {
|
||||
val androidExtension = extensions.getByName("android") as BaseExtension
|
||||
androidExtension.apply {
|
||||
compileSdkVersion(35)
|
||||
buildToolsVersion = "35.0.0"
|
||||
compileSdkVersion(36)
|
||||
buildToolsVersion = "36.1.0"
|
||||
}
|
||||
}
|
||||
if (hasProperty("android")) {
|
||||
@@ -40,9 +40,6 @@ subprojects {
|
||||
|
||||
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||
}
|
||||
subprojects {
|
||||
project.evaluationDependsOn(":app")
|
||||
}
|
||||
|
||||
tasks.register<Delete>("clean") {
|
||||
delete(rootProject.layout.buildDirectory)
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
# Disabled for faster config and incremental builds; re-enable if any dependency needs support-library
|
||||
android.enableJetifier=false
|
||||
|
||||
# Build performance (cold and warm)
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
# Configuration cache disabled: Flutter/AGP/Kotlin plugin not fully compatible (KotlinBaseApiPlugin / ProjectServices)
|
||||
# org.gradle.configuration-cache=true
|
||||
org.gradle.daemon=true
|
||||
# Better Kotlin incremental compilation (warm builds)
|
||||
kotlin.incremental.useClasspathSnapshot=true
|
||||
|
||||
@@ -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.10.2-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
|
||||
|
||||
@@ -18,8 +18,9 @@ pluginManagement {
|
||||
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "8.7.0" apply false
|
||||
id("org.jetbrains.kotlin.android") version "1.8.22" apply false
|
||||
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
|
||||
}
|
||||
|
||||
include(":app")
|
||||
|
||||
BIN
firka/assets/images/logos/splash_android12.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
4
firka/assets/majesticons/gradeDefault.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<svg width="23" height="18" viewBox="0 0 23 18" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M4.8252 0L3.09442 6.29374L2.5175 3.93359C3.26925 3.93359 3.88114 4.15212 4.35317 4.58919C4.8252 5.02625 5.06122 5.6294 5.06122 6.39864C5.06122 7.15039 4.81646 7.76228 4.32695 8.23431C3.85492 8.68886 3.26051 8.91613 2.54372 8.91613C1.80945 8.91613 1.19756 8.68886 0.708046 8.23431C0.236015 7.76228 0 7.15039 0 6.39864C0 6.17136 0.0174826 5.95283 0.0524478 5.74304C0.0874131 5.51576 0.157344 5.25352 0.262239 4.95632C0.367135 4.65912 0.515737 4.26576 0.708046 3.77624L2.22903 0H4.8252ZM11.014 0L9.28327 6.29374L8.70634 3.93359C9.45809 3.93359 10.07 4.15212 10.542 4.58919C11.014 5.02625 11.2501 5.6294 11.2501 6.39864C11.2501 7.15039 11.0053 7.76228 10.5158 8.23431C10.0438 8.68886 9.44935 8.91613 8.73256 8.91613C7.99829 8.91613 7.3864 8.68886 6.89689 8.23431C6.42486 7.76228 6.18884 7.15039 6.18884 6.39864C6.18884 6.17136 6.20633 5.95283 6.24129 5.74304C6.27626 5.51576 6.34619 5.25352 6.45108 4.95632C6.55598 4.65912 6.70458 4.26576 6.89689 3.77624L8.41788 0H11.014Z" fill="#A0D025"/>
|
||||
<path d="M17.6748 17.832L19.4056 11.5383L19.9825 13.8984C19.2308 13.8984 18.6189 13.6799 18.1468 13.2428C17.6748 12.8058 17.4388 12.2026 17.4388 11.4334C17.4388 10.6816 17.6835 10.0698 18.1731 9.59772C18.6451 9.14317 19.2395 8.9159 19.9563 8.9159C20.6905 8.9159 21.3024 9.14317 21.792 9.59772C22.264 10.0698 22.5 10.6816 22.5 11.4334C22.5 11.6607 22.4825 11.8792 22.4476 12.089C22.4126 12.3163 22.3427 12.5785 22.2378 12.8757C22.1329 13.1729 21.9843 13.5663 21.792 14.0558L20.271 17.832H17.6748ZM11.486 17.832L13.2167 11.5383L13.7937 13.8984C13.0419 13.8984 12.43 13.6799 11.958 13.2428C11.486 12.8058 11.2499 12.2026 11.2499 11.4334C11.2499 10.6816 11.4947 10.0698 11.9842 9.59772C12.4562 9.14317 13.0506 8.9159 13.7674 8.9159C14.5017 8.9159 15.1136 9.14317 15.6031 9.59772C16.0751 10.0698 16.3112 10.6816 16.3112 11.4334C16.3112 11.6607 16.2937 11.8792 16.2587 12.089C16.2237 12.3163 16.1538 12.5785 16.0489 12.8757C15.944 13.1729 15.7954 13.5663 15.6031 14.0558L14.0821 17.832H11.486Z" fill="#A0D025"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
4
firka/assets/majesticons/homeWithMark.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M21.2187 15.3754C21.5637 14.9441 22.1937 14.8741 22.6249 15.2191C23.0562 15.5641 23.1262 16.1941 22.7812 16.6254L18.7812 21.6254C18.6036 21.8474 18.3394 21.9826 18.0556 21.9984C17.7716 22.0142 17.494 21.9086 17.2929 21.7074L15.2929 19.7074C14.9024 19.3169 14.9024 18.6839 15.2929 18.2934C15.6834 17.9028 16.3164 17.9028 16.707 18.2934L17.9159 19.5023L21.2187 15.3754Z" fill="#A0D025"/>
|
||||
<path d="M10.7998 3.65137C11.146 3.39172 11.5673 3.25098 12 3.25098C12.4327 3.25098 12.854 3.39172 13.2002 3.65137L20.2002 8.90137C20.4484 9.08763 20.6503 9.32886 20.7891 9.60645C20.9279 9.88415 21 10.1905 21 10.501V12.4565C21 12.9796 20.4396 13.3258 19.9346 13.1894C19.4773 13.066 18.9964 13 18.5 13C16.5152 13 14.776 14.0513 13.8089 15.6274C13.6713 15.8515 13.4337 16.001 13.1708 16.001H13H11V19.001C11 19.5314 10.7891 20.04 10.4141 20.415C10.039 20.7901 9.53043 21.001 9 21.001H5C4.46957 21.001 3.96101 20.7901 3.58594 20.415C3.21087 20.04 3 19.5314 3 19.001V10.501C3 10.1905 3.07208 9.88416 3.21094 9.60645C3.34973 9.32885 3.55156 9.08763 3.7998 8.90137L10.7998 3.65137Z" fill="#A0D025"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
21
firka/flutter_native_splash.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
flutter_native_splash:
|
||||
color: "#7ca120"
|
||||
image: assets/images/logos/splash.png
|
||||
# Keep image centered instead of fill-scaled (stops icon looking zoomed/cropped)
|
||||
android_gravity: center
|
||||
|
||||
# Dark mode - same color as light mode for consistency
|
||||
color_dark: "#7ca120"
|
||||
image_dark: assets/images/logos/splash.png
|
||||
|
||||
# Android 12+ uses 960×960 image with logo in 640px circle (generated by codegen) to avoid cropping
|
||||
android_12:
|
||||
image: assets/images/logos/splash_android12.png
|
||||
color: "#7ca120"
|
||||
color_dark: "#7ca120"
|
||||
image_dark: assets/images/logos/splash_android12.png
|
||||
icon_background_color: "#7ca120"
|
||||
icon_background_color_dark: "#7ca120"
|
||||
|
||||
ios: true
|
||||
web: false
|
||||
@@ -1,42 +0,0 @@
|
||||
import 'package:firka/helpers/db/models/generic_cache_model.dart';
|
||||
import 'package:firka/helpers/db/models/timetable_cache_model.dart';
|
||||
import 'package:firka/helpers/db/models/token_model.dart';
|
||||
import 'package:firka/main.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:isar/isar.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'test_helpers.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
await resetAppData();
|
||||
setApiUrls();
|
||||
|
||||
group('main', () {
|
||||
testWidgets('InitializationScreen -> HomeScreen', (tester) async {
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
|
||||
var isar = await Isar.open(
|
||||
[TokenModelSchema, GenericCacheModelSchema, TimetableCacheModelSchema],
|
||||
inspector: true,
|
||||
directory: dir.path,
|
||||
);
|
||||
isarInit = isar;
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.put(TokenModel());
|
||||
});
|
||||
|
||||
await tester.pumpWidget(InitializationScreen());
|
||||
|
||||
await waitUntil(Duration(minutes: 2), tester, () async {
|
||||
var ele = find.byKey(const Key('homeScreen'));
|
||||
return ele.allCandidates.isNotEmpty;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:firka/main.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import 'test_helpers.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
await resetAppData();
|
||||
setApiUrls();
|
||||
|
||||
group('main', () {
|
||||
testWidgets('InitializationScreen -> LoginScreen', (tester) async {
|
||||
await tester.pumpWidget(InitializationScreen());
|
||||
|
||||
await waitUntil(Duration(minutes: 2), tester, () async {
|
||||
var ele = find.byKey(const Key('loginScreen'));
|
||||
return ele.allCandidates.isNotEmpty;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import 'package:firka/helpers/api/consts.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
Future<bool> isWear() async {
|
||||
const platform = MethodChannel('firka.app/main');
|
||||
|
||||
return await platform.invokeMethod("isWear");
|
||||
}
|
||||
|
||||
Future<bool> isPhone() async {
|
||||
return !(await isWear());
|
||||
}
|
||||
|
||||
Future<void> resetAppData() async {
|
||||
final isarDir = await getApplicationDocumentsDirectory();
|
||||
if (await isarDir.exists()) await isarDir.delete(recursive: true);
|
||||
}
|
||||
|
||||
void setApiUrls() {
|
||||
KretaEndpoints.kretaBase = "localhost:8060";
|
||||
KretaEndpoints.kretaIdp = "http://localhost:8060";
|
||||
KretaEndpoints.kretaLoginUrl =
|
||||
"${KretaEndpoints.kretaIdp}/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fprompt%3Dlogin%26nonce%3DwylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU%26response_type%3Dcode%26code_challenge_method%3DS256%26scope%3Dopenid%2520email%2520offline_access%2520kreta-ellenorzo-webapi.public%2520kreta-eugyintezes-webapi.public%2520kreta-fileservice-webapi.public%2520kreta-mobile-global-webapi.public%2520kreta-dkt-webapi.public%2520kreta-ier-webapi.public%26code_challenge%3DHByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ%26redirect_uri%3Dhttps%253A%252F%252Fmobil.e-kreta.hu%252Fellenorzo-student%252Fprod%252Foauthredirect%26client_id%3Dkreta-ellenorzo-student-mobile-ios%26state%3Dkreta_student_mobile%26suppressed_prompt%3Dlogin";
|
||||
KretaEndpoints.tokenGrantUrl = "${KretaEndpoints.kretaIdp}/connect/token";
|
||||
}
|
||||
|
||||
Future<void> waitUntil(Duration timeout, WidgetTester tester,
|
||||
Future<bool> Function() callback) async {
|
||||
var now = DateTime.now();
|
||||
while (
|
||||
now.difference(DateTime.now()).inMilliseconds < timeout.inMilliseconds) {
|
||||
await tester.pump(Duration(milliseconds: 100));
|
||||
|
||||
if (await callback()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception("waitUntil timed out");
|
||||
}
|
||||
5
firka/ios/.gitignore
vendored
@@ -33,4 +33,7 @@ Runner/GeneratedPluginRegistrant.*
|
||||
!default.pbxuser
|
||||
!default.perspectivev3
|
||||
|
||||
/.DerivedData
|
||||
/.DerivedData
|
||||
|
||||
# Developer-specific configuration
|
||||
.dev_config
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "Icon-1024.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "watchos",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 147 KiB |
@@ -0,0 +1,64 @@
|
||||
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()
|
||||
}
|
||||
42
firka/ios/FirkaWatch Watch App/Components/FirkaCard.swift
Normal file
@@ -0,0 +1,42 @@
|
||||
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()
|
||||
}
|
||||
39
firka/ios/FirkaWatch Watch App/Components/GradeBadge.swift
Normal file
@@ -0,0 +1,39 @@
|
||||
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()
|
||||
}
|
||||
46
firka/ios/FirkaWatch Watch App/Components/GradeRow.swift
Normal file
@@ -0,0 +1,46 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
146
firka/ios/FirkaWatch Watch App/Components/LessonCard.swift
Normal file
@@ -0,0 +1,146 @@
|
||||
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()
|
||||
}
|
||||
68
firka/ios/FirkaWatch Watch App/Components/ProgressBar.swift
Normal file
@@ -0,0 +1,68 @@
|
||||
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()
|
||||
}
|
||||
43
firka/ios/FirkaWatch Watch App/Components/SubjectRow.swift
Normal file
@@ -0,0 +1,43 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
189
firka/ios/FirkaWatch Watch App/ContentView.swift
Normal file
@@ -0,0 +1,189 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?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>
|
||||
35
firka/ios/FirkaWatch Watch App/FirkaWatchApp.swift
Normal file
@@ -0,0 +1,35 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
464
firka/ios/FirkaWatch Watch App/Localization/WatchL10n.swift
Normal file
@@ -0,0 +1,464 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
551
firka/ios/FirkaWatch Watch App/Services/DataStore.swift
Normal file
@@ -0,0 +1,551 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
119
firka/ios/FirkaWatch Watch App/Views/GradeSubjectView.swift
Normal file
@@ -0,0 +1,119 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
108
firka/ios/FirkaWatch Watch App/Views/GradesView.swift
Normal file
@@ -0,0 +1,108 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
598
firka/ios/FirkaWatch Watch App/Views/HomeView.swift
Normal file
@@ -0,0 +1,598 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
109
firka/ios/FirkaWatch Watch App/Views/LessonDetailView.swift
Normal file
@@ -0,0 +1,109 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
308
firka/ios/FirkaWatch Watch App/Views/ReauthRequiredView.swift
Normal file
@@ -0,0 +1,308 @@
|
||||
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()
|
||||
}
|
||||
78
firka/ios/FirkaWatch Watch App/Views/SettingsView.swift
Normal file
@@ -0,0 +1,78 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
369
firka/ios/FirkaWatch Watch App/Views/TimetableView.swift
Normal file
@@ -0,0 +1,369 @@
|
||||
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
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"platform" : "watchos",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
369
firka/ios/FirkaWatchComplications/FirkaComplications.swift
Normal file
@@ -0,0 +1,369 @@
|
||||
#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
|
||||
12
firka/ios/FirkaWatchComplicationsExtension.entitlements
Normal file
@@ -0,0 +1,12 @@
|
||||
<?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>com.apple.developer.ubiquity-kvstore-identifier</key>
|
||||
<string>$(TeamIdentifierPrefix)app.firka.firkaa</string>
|
||||
</dict>
|
||||
</plist>
|
||||
12
firka/ios/HomeWidgetsExtension.entitlements
Normal file
@@ -0,0 +1,12 @@
|
||||
<?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>com.apple.developer.ubiquity-kvstore-identifier</key>
|
||||
<string>$(TeamIdentifierPrefix)$(CFBundleIdentifier)</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||