diff --git a/firka/android/app/src/main/AndroidManifest.xml b/firka/android/app/src/main/AndroidManifest.xml
index 75f21326..eabc2407 100644
--- a/firka/android/app/src/main/AndroidManifest.xml
+++ b/firka/android/app/src/main/AndroidManifest.xml
@@ -6,7 +6,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ when (call.method) {
+ "startProgressService" -> {
+ val intent = Intent(this, ProgressNotificationForegroundService::class.java).apply {
+ action = ProgressNotificationForegroundService.ACTION_START
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ startForegroundService(intent)
+ } else {
+ startService(intent)
+ }
+ result.success(true)
+ }
+ "stopProgressService" -> {
+ val intent = Intent(this, ProgressNotificationForegroundService::class.java).apply {
+ action = ProgressNotificationForegroundService.ACTION_STOP
+ }
+ startService(intent)
+ result.success(true)
+ }
+ "isProgressServiceRunning" -> {
+ val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
+ val isNotifActive = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ try {
+ nm.activeNotifications?.any { it.id == 4002 } ?: false
+ } catch (e: Exception) {
+ ProgressNotificationForegroundService.isRunning
+ }
+ } else {
+ ProgressNotificationForegroundService.isRunning
+ }
+ result.success(ProgressNotificationForegroundService.isRunning && isNotifActive)
+ }
+ "updateProgressStrings" -> {
+ @Suppress("UNCHECKED_CAST")
+ val strings = call.arguments as? Map
+ if (strings != null) {
+ ProgressNotificationForegroundService.saveStrings(this, strings)
+ if (ProgressNotificationForegroundService.isRunning) {
+ val intent = Intent(this, ProgressNotificationForegroundService::class.java).apply {
+ action = ProgressNotificationForegroundService.ACTION_UPDATE
+ }
+ startService(intent)
+ }
+ result.success(true)
+ } else {
+ result.error("INVALID_ARGS", "strings map required", null)
+ }
+ }
+ "schedule6AmAlarm" -> {
+ ProgressAlarmReceiver.scheduleNext6AmAlarm(this)
+ result.success(true)
+ }
+ "cancel6AmAlarm" -> {
+ ProgressAlarmReceiver.cancel6AmAlarm(this)
+ result.success(true)
+ }
+ else -> result.notImplemented()
+ }
+ }
+
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel).setMethodCallHandler {
call, result ->
when (call.method) {
diff --git a/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressAlarmReceiver.kt b/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressAlarmReceiver.kt
new file mode 100644
index 00000000..fa59de7c
--- /dev/null
+++ b/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressAlarmReceiver.kt
@@ -0,0 +1,97 @@
+package app.firka.naplo
+
+import android.app.AlarmManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.util.Log
+import java.time.LocalDate
+import java.time.LocalDateTime
+import java.time.ZoneId
+
+class ProgressAlarmReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent?) {
+ Log.d(TAG, "onReceive action: ${intent?.action}")
+
+ scheduleNext6AmAlarm(context)
+
+ val data = ProgressNotificationForegroundService.loadTodayTimetable(context)
+ if (data == null || data.lessons.isEmpty()) {
+ Log.d(TAG, "No timetable for today at 6 AM wakeup; skipping service start")
+ return
+ }
+
+ val sorted = data.lessons.sortedBy { it.start }
+ val lastLesson = sorted.last()
+ val now = LocalDateTime.now()
+
+ if (now.isBefore(lastLesson.end)) {
+ Log.d(TAG, "Starting ProgressNotificationForegroundService from 6 AM alarm")
+ val serviceIntent = Intent(context, ProgressNotificationForegroundService::class.java).apply {
+ action = ProgressNotificationForegroundService.ACTION_START
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(serviceIntent)
+ } else {
+ context.startService(serviceIntent)
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "ProgressAlarmReceiver"
+ const val ACTION_PROGRESS_6AM_ALARM = "app.firka.naplo.ACTION_PROGRESS_6AM_ALARM"
+ const val ALARM_REQUEST_CODE = 400201
+
+ fun scheduleNext6AmAlarm(context: Context) {
+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
+ val intent = Intent(context, ProgressAlarmReceiver::class.java).apply {
+ action = ACTION_PROGRESS_6AM_ALARM
+ }
+ val pendingIntent = PendingIntent.getBroadcast(
+ context,
+ ALARM_REQUEST_CODE,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+
+ val now = LocalDateTime.now()
+ var target = now.toLocalDate().atTime(6, 0)
+ if (!target.isAfter(now)) {
+ target = target.plusDays(1)
+ }
+
+ val epochMillis = target.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
+ Log.d(TAG, "Scheduling next 6 AM alarm for $target ($epochMillis)")
+
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, epochMillis, pendingIntent)
+ } else {
+ alarmManager.setExact(AlarmManager.RTC_WAKEUP, epochMillis, pendingIntent)
+ }
+ } catch (e: SecurityException) {
+ Log.w(TAG, "SecurityException while scheduling exact 6 AM alarm, falling back to setWindow", e)
+ alarmManager.set(AlarmManager.RTC_WAKEUP, epochMillis, pendingIntent)
+ }
+ }
+
+ fun cancel6AmAlarm(context: Context) {
+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
+ val intent = Intent(context, ProgressAlarmReceiver::class.java).apply {
+ action = ACTION_PROGRESS_6AM_ALARM
+ }
+ val pendingIntent = PendingIntent.getBroadcast(
+ context,
+ ALARM_REQUEST_CODE,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ alarmManager.cancel(pendingIntent)
+ Log.d(TAG, "Cancelled 6 AM progress alarm")
+ }
+ }
+}
diff --git a/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressNotificationForegroundService.kt b/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressNotificationForegroundService.kt
new file mode 100644
index 00000000..d63127ed
--- /dev/null
+++ b/firka/android/app/src/main/kotlin/app/firka/naplo/ProgressNotificationForegroundService.kt
@@ -0,0 +1,649 @@
+package app.firka.naplo
+
+import android.app.AlarmManager
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.pm.ServiceInfo
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.IBinder
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import app.firka.naplo.glance.WidgetLesson
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+import java.io.File
+import java.time.Duration
+import java.time.LocalDate
+import java.time.LocalDateTime
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+
+class ProgressNotificationForegroundService : Service() {
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private var tickerJob: Job? = null
+ private var isForegroundStarted = false
+ private var transitionPendingIntent: PendingIntent? = null
+
+ private val timeReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context?, intent: Intent?) {
+ when (intent?.action) {
+ Intent.ACTION_TIME_TICK,
+ Intent.ACTION_SCREEN_ON,
+ Intent.ACTION_USER_PRESENT -> {
+ refreshAndPostNotification()
+ }
+ }
+ }
+ }
+
+ private val channelId = "firka_progress_notification_v3"
+ private val notificationId = 4002
+
+ private val hhmm = DateTimeFormatter.ofPattern("HH:mm")
+
+ private fun formatTemplate(template: String, vararg replacements: Pair): String {
+ var res = template
+ for ((key, value) in replacements) {
+ res = res.replace("{$key}", value)
+ }
+ return res
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+ isRunning = true
+ createNotificationChannel()
+ val filter = IntentFilter().apply {
+ addAction(Intent.ACTION_TIME_TICK)
+ addAction(Intent.ACTION_SCREEN_ON)
+ addAction(Intent.ACTION_USER_PRESENT)
+ }
+ ContextCompat.registerReceiver(
+ this,
+ timeReceiver,
+ filter,
+ ContextCompat.RECEIVER_NOT_EXPORTED
+ )
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ createNotificationChannel()
+ when (intent?.action) {
+ ACTION_START, ACTION_UPDATE -> {
+ isRunning = true
+ refreshAndPostNotification()
+ startTicker()
+ }
+ ACTION_STOP -> {
+ isRunning = false
+ stopForegroundService()
+ return START_NOT_STICKY
+ }
+ else -> {
+ isRunning = true
+ refreshAndPostNotification()
+ startTicker()
+ }
+ }
+ return START_STICKY
+ }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onDestroy() {
+ isRunning = false
+ cancelTransitionAlarm()
+ try {
+ unregisterReceiver(timeReceiver)
+ } catch (_: Exception) {}
+ tickerJob?.cancel()
+ scope.cancel()
+ super.onDestroy()
+ }
+
+ private fun startTicker() {
+ tickerJob?.cancel()
+ tickerJob = scope.launch {
+ while (isActive) {
+ val currentMillis = System.currentTimeMillis()
+ val millisIntoMinute = currentMillis % 60_000
+ // Target next :00 or :30 second boundary
+ val delayMillis = if (millisIntoMinute < 30_000) {
+ 30_000 - millisIntoMinute
+ } else {
+ 60_000 - millisIntoMinute
+ }.coerceIn(1_000, 30_000)
+
+ delay(delayMillis)
+ refreshAndPostNotification()
+ }
+ }
+ }
+
+ private fun refreshAndPostNotification() {
+ val widgetData = loadTodayTimetable(applicationContext)
+
+ if (widgetData == null || widgetData.lessons.isEmpty()) {
+ Log.d(TAG, "No lessons for today; stopping progress service")
+ stopForegroundService()
+ return
+ }
+
+ val lessons = widgetData.lessons.sortedBy { it.start }
+ val now = LocalDateTime.now()
+ val lastLesson = lessons.last()
+
+ // If today's last lesson has ended, stop notification & foreground service
+ if (now.isAfter(lastLesson.end) || now.isEqual(lastLesson.end)) {
+ Log.d(TAG, "Last lesson of the day ended (${lastLesson.end}); stopping progress service")
+ stopForegroundService()
+ return
+ }
+
+ val notification = buildProgressNotification(widgetData, now)
+ if (notification == null) {
+ stopForegroundService()
+ return
+ }
+
+ if (!isForegroundStarted) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(
+ notificationId,
+ notification,
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
+ )
+ } else {
+ @Suppress("DEPRECATION")
+ startForeground(notificationId, notification)
+ }
+ isForegroundStarted = true
+ }
+
+ val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
+ nm.notify(notificationId, notification)
+
+ // Schedule exact alarm for next transition (lesson start/end or break end)
+ val firstLesson = lessons.first()
+ val targetTransitionTime: LocalDateTime? = when {
+ now.isBefore(firstLesson.start) -> firstLesson.start
+ else -> {
+ val currentLesson = lessons.find { !now.isBefore(it.start) && now.isBefore(it.end) }
+ if (currentLesson != null) {
+ currentLesson.end
+ } else {
+ val nextLesson = lessons.firstOrNull { it.start.isAfter(now) }
+ nextLesson?.start
+ }
+ }
+ }
+ if (targetTransitionTime != null) {
+ scheduleNextTransitionAlarm(targetTransitionTime)
+ }
+ }
+
+ private fun buildProgressNotification(data: TimetableProgressData, now: LocalDateTime): Notification? {
+ val strings = getStrings(this)
+ val lessons = data.lessons.sortedBy { it.start }
+ val firstLesson = lessons.first()
+ val lastLesson = lessons.last()
+
+ val pendingIntent = PendingIntent.getActivity(
+ this,
+ 0,
+ packageManager.getLaunchIntentForPackage(packageName),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+
+ val accentColor = data.accentColor
+ val breakColor = data.breakColor
+
+ val remainingLessonsCount = lessons.count { !now.isAfter(it.end) }
+ val remainingSuffix = if (remainingLessonsCount == 1) {
+ strings["progress_notif_remaining_lessons_one"] ?: ""
+ } else {
+ val template = strings["progress_notif_remaining_lessons_other"] ?: ""
+ formatTemplate(template, "count" to remainingLessonsCount.toString())
+ }
+
+ if (now.isBefore(firstLesson.start)) {
+ val minutesLeft = minutesRemaining(now, firstLesson.start)
+ val firstLessonIconRes = resolveSubjectIcon(firstLesson)
+
+ val title = if (firstLesson.lessonNumber != null) {
+ val template = strings["progress_notif_lesson_title"] ?: ""
+ if (template.isNotEmpty()) {
+ formatTemplate(template, "number" to firstLesson.lessonNumber.toString(), "name" to firstLesson.name)
+ } else {
+ firstLesson.name
+ }
+ } else {
+ firstLesson.name
+ }
+
+ val room = firstLesson.roomName?.trim()
+ val roomSuffix = if (!room.isNullOrBlank() && room != "null") "\n$room" else ""
+ val subSuffix = if (!firstLesson.substituteTeacher.isNullOrBlank() && firstLesson.substituteTeacher != "null" && firstLesson.substituteTeacher != "-") {
+ strings["progress_notif_substitution"] ?: ""
+ } else ""
+ val timeRange = "${firstLesson.start.format(hhmm)}-${firstLesson.end.format(hhmm)}"
+ val templateCase1 = strings["progress_notif_case1_text"] ?: ""
+ val text = formatTemplate(
+ templateCase1,
+ "minutes" to minutesLeft.toString(),
+ "timeRange" to timeRange,
+ "room" to roomSuffix,
+ "substitution" to subSuffix,
+ "remaining" to remainingSuffix
+ )
+ val criticalTemplate = strings["progress_notif_critical_text"] ?: ""
+ val criticalText = formatTemplate(criticalTemplate, "minutes" to minutesLeft.toString())
+
+ val morningStart = firstLesson.start.toLocalDate().atTime(6, 0)
+ val baseStart = if (now.isBefore(morningStart)) now else morningStart
+ val totalMinutes = Duration.between(baseStart, firstLesson.start).toMinutes().coerceAtLeast(15)
+ val elapsed = Duration.between(baseStart, now).toMinutes().coerceIn(0, totalMinutes)
+
+ if (Build.VERSION.SDK_INT >= 36) {
+ val progressStyle = Notification.ProgressStyle()
+ .setProgress(elapsed.toInt())
+ .setProgressSegments(listOf(
+ Notification.ProgressStyle.Segment(totalMinutes.toInt()).setColor(accentColor)
+ ))
+ .setProgressEndIcon(Icon.createWithResource(this, firstLessonIconRes))
+ .setProgressTrackerIcon(Icon.createWithResource(this, R.drawable.ic_subject_break))
+
+ val builder = Notification.Builder(this, channelId)
+ .setStyle(progressStyle)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setLargeIcon(Icon.createWithResource(this, firstLessonIconRes))
+ .setContentIntent(pendingIntent)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setRequestPromotedOngoing(true)
+ .setShortCriticalText(criticalText.take(7))
+
+ return builder.build()
+ } else {
+ return NotificationCompat.Builder(this, channelId)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentIntent(pendingIntent)
+ .setProgress(totalMinutes.toInt(), elapsed.toInt(), false)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .build()
+ }
+ }
+
+ val currentLesson = lessons.find { !now.isBefore(it.start) && now.isBefore(it.end) }
+
+ val title: String
+ val text: String
+ val criticalText: String
+ val trackerIconRes: Int
+ val largeIconRes: Int
+ val endIconRes: Int
+ val itemDuration: Int
+ val itemElapsed: Int
+ val itemColor: Int
+
+ if (currentLesson != null) {
+ val lessonDuration = Duration.between(currentLesson.start, currentLesson.end).toMinutes().coerceAtLeast(1).toInt()
+ val elapsed = Duration.between(currentLesson.start, now).toMinutes().coerceIn(0, lessonDuration.toLong()).toInt()
+ val timeLeft = minutesRemaining(now, currentLesson.end)
+
+ itemDuration = lessonDuration
+ itemElapsed = elapsed
+ itemColor = accentColor
+
+ trackerIconRes = resolveSubjectIcon(currentLesson)
+ largeIconRes = trackerIconRes
+ endIconRes = R.drawable.ic_subject_break
+
+ val prefix = if (currentLesson.lessonNumber != null) {
+ val template = strings["progress_notif_lesson_title"] ?: ""
+ if (template.isNotEmpty()) {
+ formatTemplate(template, "number" to currentLesson.lessonNumber.toString(), "name" to currentLesson.name)
+ } else {
+ currentLesson.name
+ }
+ } else {
+ currentLesson.name
+ }
+ title = prefix
+ val room = currentLesson.roomName?.trim()
+ val roomSuffix = if (!room.isNullOrBlank() && room != "null") "\n$room" else ""
+ val subSuffix = if (!currentLesson.substituteTeacher.isNullOrBlank() && currentLesson.substituteTeacher != "null" && currentLesson.substituteTeacher != "-") {
+ strings["progress_notif_substitution"] ?: ""
+ } else ""
+ val timeRange = "${currentLesson.start.format(hhmm)}-${currentLesson.end.format(hhmm)}"
+ val templateLesson = strings["progress_notif_case2_lesson_text"] ?: ""
+ text = formatTemplate(
+ templateLesson,
+ "minutes" to timeLeft.toString(),
+ "timeRange" to timeRange,
+ "room" to roomSuffix,
+ "substitution" to subSuffix,
+ "remaining" to remainingSuffix
+ )
+ val criticalTemplate = strings["progress_notif_critical_text"] ?: ""
+ criticalText = formatTemplate(criticalTemplate, "minutes" to timeLeft.toString())
+ } else {
+ val previousLesson = lessons.lastOrNull { !now.isBefore(it.end) }
+ val nextLesson = lessons.firstOrNull { it.start.isAfter(now) }
+ val breakStart = previousLesson?.end ?: now
+ val breakEnd = nextLesson?.start ?: lastLesson.end
+
+ val breakDuration = Duration.between(breakStart, breakEnd).toMinutes().coerceAtLeast(1).toInt()
+ val elapsed = Duration.between(breakStart, now).toMinutes().coerceIn(0, breakDuration.toLong()).toInt()
+ val timeLeft = minutesRemaining(now, breakEnd)
+
+ itemDuration = breakDuration
+ itemElapsed = elapsed
+ itemColor = breakColor
+
+ trackerIconRes = R.drawable.ic_subject_break
+ largeIconRes = if (nextLesson != null) resolveSubjectIcon(nextLesson) else trackerIconRes
+ endIconRes = if (nextLesson != null) resolveSubjectIcon(nextLesson) else trackerIconRes
+
+ title = strings["progress_notif_case2_break_title"] ?: ""
+ val templateBreak = strings["progress_notif_case2_break_text"] ?: ""
+ text = formatTemplate(
+ templateBreak,
+ "minutes" to timeLeft.toString(),
+ "remaining" to remainingSuffix
+ )
+ val criticalTemplate = strings["progress_notif_critical_text"] ?: ""
+ criticalText = formatTemplate(criticalTemplate, "minutes" to timeLeft.toString())
+ }
+
+ if (Build.VERSION.SDK_INT >= 36) {
+ val progressStyle = Notification.ProgressStyle()
+ .setProgress(itemElapsed)
+ .setProgressSegments(listOf(
+ Notification.ProgressStyle.Segment(itemDuration).setColor(itemColor)
+ ))
+ .setProgressTrackerIcon(Icon.createWithResource(this, trackerIconRes))
+ .setProgressEndIcon(Icon.createWithResource(this, endIconRes))
+
+ val builder = Notification.Builder(this, channelId)
+ .setStyle(progressStyle)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setLargeIcon(Icon.createWithResource(this, largeIconRes))
+ .setContentIntent(pendingIntent)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setRequestPromotedOngoing(true)
+ .setShortCriticalText(criticalText.take(7))
+
+ return builder.build()
+ } else {
+ return NotificationCompat.Builder(this, channelId)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentIntent(pendingIntent)
+ .setProgress(itemDuration, itemElapsed, false)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .build()
+ }
+ }
+
+ private fun resolveSubjectIcon(lesson: WidgetLesson): Int {
+ if (!lesson.icon.isNullOrEmpty()) {
+ val res = getSubjectIconRes(lesson.icon)
+ if (res != R.drawable.ic_notification) return res
+ }
+ val name = lesson.name.lowercase()
+ return when {
+ Regex("mate(k|matika)").containsMatchIn(name) -> R.drawable.ic_subject_mathematics
+ Regex("magyar nyelv|nyelvtan").containsMatchIn(name) -> R.drawable.ic_subject_grammar
+ Regex("irodalom").containsMatchIn(name) -> R.drawable.ic_subject_literature
+ Regex("tor(i|tenelem)").containsMatchIn(name) -> R.drawable.ic_subject_history
+ Regex("foldrajz").containsMatchIn(name) -> R.drawable.ic_subject_geography
+ Regex("rajz|muvtori|muveszet|vizualis").containsMatchIn(name) -> R.drawable.ic_subject_art
+ Regex("fizika").containsMatchIn(name) -> R.drawable.ic_subject_physics
+ Regex("^enek|zene|szolfezs|zongora|korus").containsMatchIn(name) -> R.drawable.ic_subject_music
+ Regex("^tes(i|tneveles)|sport|edzeselmelet").containsMatchIn(name) -> R.drawable.ic_subject_pe
+ Regex("kemia").containsMatchIn(name) -> R.drawable.ic_subject_chemistry
+ Regex("biologia").containsMatchIn(name) -> R.drawable.ic_subject_biology
+ Regex("angol|nemet|francia|olasz|orosz|spanyol|latin|kinai|idegen|nyelv").containsMatchIn(name) -> R.drawable.ic_subject_language
+ Regex("informatika|szoftver|digitalis").containsMatchIn(name) -> R.drawable.ic_subject_it
+ Regex("prog|alkalmazas").containsMatchIn(name) -> R.drawable.ic_subject_code
+ Regex("halozat").containsMatchIn(name) -> R.drawable.ic_subject_networking
+ Regex("filozofia").containsMatchIn(name) -> R.drawable.ic_subject_philosophy
+ Regex("osztaly(fonoki|kozosseg)").containsMatchIn(name) -> R.drawable.ic_subject_ofo
+ Regex("penzugy|gazdasag").containsMatchIn(name) -> R.drawable.ic_subject_economics
+ Regex("kornyezet|termeszet").containsMatchIn(name) -> R.drawable.ic_subject_env
+ Regex("(hit|erkolcs)tan|vallas|etika").containsMatchIn(name) -> R.drawable.ic_subject_religion
+ Regex("adatbazis").containsMatchIn(name) -> R.drawable.ic_subject_database
+ else -> R.drawable.ic_subject_unknown
+ }
+ }
+
+ private fun getSubjectIconRes(iconName: String?): Int {
+ if (iconName == null) return R.drawable.ic_subject_unknown
+ return when (iconName.lowercase()) {
+ "mathematics" -> R.drawable.ic_subject_mathematics
+ "grammar" -> R.drawable.ic_subject_grammar
+ "literature" -> R.drawable.ic_subject_literature
+ "history" -> R.drawable.ic_subject_history
+ "geography" -> R.drawable.ic_subject_geography
+ "art" -> R.drawable.ic_subject_art
+ "physics" -> R.drawable.ic_subject_physics
+ "music" -> R.drawable.ic_subject_music
+ "pe" -> R.drawable.ic_subject_pe
+ "chemistry" -> R.drawable.ic_subject_chemistry
+ "biology" -> R.drawable.ic_subject_biology
+ "env" -> R.drawable.ic_subject_env
+ "religion" -> R.drawable.ic_subject_religion
+ "economics" -> R.drawable.ic_subject_economics
+ "it" -> R.drawable.ic_subject_it
+ "code" -> R.drawable.ic_subject_code
+ "networking" -> R.drawable.ic_subject_networking
+ "theatre" -> R.drawable.ic_subject_theatre
+ "film" -> R.drawable.ic_subject_film
+ "electricalengineering" -> R.drawable.ic_subject_electricalengineering
+ "mechanicalengineering" -> R.drawable.ic_subject_mechanicalengineering
+ "technika" -> R.drawable.ic_subject_technika
+ "dance" -> R.drawable.ic_subject_dance
+ "philosophy" -> R.drawable.ic_subject_philosophy
+ "erettsegi" -> R.drawable.ic_subject_erettsegi
+ "ofo" -> R.drawable.ic_subject_ofo
+ "diligence" -> R.drawable.ic_subject_diligence
+ "attitude" -> R.drawable.ic_subject_attitude
+ "language" -> R.drawable.ic_subject_language
+ "linux" -> R.drawable.ic_subject_linux
+ "database" -> R.drawable.ic_subject_database
+ "applications" -> R.drawable.ic_subject_applications
+ "project" -> R.drawable.ic_subject_project
+ "break" -> R.drawable.ic_subject_break
+ else -> R.drawable.ic_subject_unknown
+ }
+ }
+
+ private fun createNotificationChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
+ try {
+ nm.deleteNotificationChannel("firka_progress_notification")
+ nm.deleteNotificationChannel("firka_progress_notification_v2")
+ } catch (_: Exception) {}
+
+ val strings = getStrings(this)
+ val channelName = strings["progress_notif_channel_name"]?.takeIf { it.isNotBlank() } ?: "Firka"
+ val channelDesc = strings["progress_notif_channel_desc"] ?: ""
+
+ val channel = NotificationChannel(
+ channelId,
+ channelName,
+ NotificationManager.IMPORTANCE_DEFAULT
+ ).apply {
+ setShowBadge(false)
+ setSound(null, null)
+ enableVibration(false)
+ description = channelDesc
+ }
+ nm.createNotificationChannel(channel)
+ }
+ }
+
+ private fun scheduleNextTransitionAlarm(targetTime: LocalDateTime) {
+ val alarmManager = getSystemService(ALARM_SERVICE) as? AlarmManager ?: return
+ cancelTransitionAlarm()
+
+ val intent = Intent(this, ProgressNotificationForegroundService::class.java).apply {
+ action = ACTION_UPDATE
+ }
+ val pendingIntent = PendingIntent.getService(
+ this,
+ 1001,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ transitionPendingIntent = pendingIntent
+
+ val epochMillis = targetTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
+ if (epochMillis > System.currentTimeMillis()) {
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, epochMillis, pendingIntent)
+ } else {
+ alarmManager.setExact(AlarmManager.RTC_WAKEUP, epochMillis, pendingIntent)
+ }
+ } catch (e: SecurityException) {
+ Log.w(TAG, "Cannot schedule transition alarm", e)
+ }
+ }
+ }
+
+ private fun cancelTransitionAlarm() {
+ val alarmManager = getSystemService(ALARM_SERVICE) as? AlarmManager ?: return
+ transitionPendingIntent?.let {
+ alarmManager.cancel(it)
+ transitionPendingIntent = null
+ }
+ }
+
+ private fun stopForegroundService() {
+ isRunning = false
+ cancelTransitionAlarm()
+ tickerJob?.cancel()
+ isForegroundStarted = false
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ } else {
+ @Suppress("DEPRECATION")
+ stopForeground(true)
+ }
+ stopSelf()
+ }
+
+ private fun minutesRemaining(from: LocalDateTime, to: LocalDateTime): Int {
+ val seconds = Duration.between(from, to).seconds
+ return if (seconds <= 0) 1 else ((seconds + 59) / 60).toInt().coerceAtLeast(1)
+ }
+
+ companion object {
+ private const val TAG = "ProgressNotifService"
+ const val ACTION_START = "app.firka.naplo.ProgressNotificationForegroundService.START"
+ const val ACTION_UPDATE = "app.firka.naplo.ProgressNotificationForegroundService.UPDATE"
+ const val ACTION_STOP = "app.firka.naplo.ProgressNotificationForegroundService.STOP"
+
+ private const val PREFS_STRINGS = "firka_progress_strings"
+
+ @Volatile
+ var isRunning: Boolean = false
+
+ fun saveStrings(context: Context, strings: Map) {
+ val prefs = context.applicationContext.getSharedPreferences(PREFS_STRINGS, Context.MODE_PRIVATE)
+ val editor = prefs.edit()
+ for ((k, v) in strings) {
+ editor.putString(k, v)
+ }
+ editor.apply()
+ }
+
+ fun getStrings(context: Context): Map {
+ val prefs = context.applicationContext.getSharedPreferences(PREFS_STRINGS, Context.MODE_PRIVATE)
+ val all = prefs.all
+ val result = mutableMapOf()
+ for ((k, v) in all) {
+ if (v is String) {
+ result[k] = v
+ }
+ }
+ return result
+ }
+
+ fun loadTodayTimetable(context: Context): TimetableProgressData? {
+ return try {
+ val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
+ val widgetStateFile = File(appFlutter, "widget_state.json")
+ if (!widgetStateFile.exists()) return null
+ val text = widgetStateFile.readText(Charsets.UTF_8)
+ val json = JSONObject(text)
+
+ val tt = json.getJSONArray("timetable")
+ val allLessons = mutableListOf()
+ for (i in 0 until tt.length()) {
+ allLessons.add(WidgetLesson(tt.getJSONObject(i)))
+ }
+
+ val today = LocalDate.now()
+ var todayLessons = allLessons.filter { it.start.toLocalDate() == today }
+ if (todayLessons.isEmpty()) {
+ val displayDateStr = json.optString("displayDate", "")
+ if (displayDateStr.isNotEmpty()) {
+ try {
+ val displayDate = LocalDate.parse(displayDateStr)
+ todayLessons = allLessons.filter { it.start.toLocalDate() == displayDate }
+ } catch (_: Exception) {}
+ }
+ }
+
+ val colorsObj = json.optJSONObject("colors")
+ val accent = colorsObj?.optInt("accent", 0xFF4C662B.toInt()) ?: 0xFF4C662B.toInt()
+ val secondary = colorsObj?.optInt("secondary", 0xFF586249.toInt()) ?: 0xFF586249.toInt()
+ val language = json.optString("language", null)
+
+ TimetableProgressData(todayLessons, accent, secondary, language)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error reading timetable data", e)
+ null
+ }
+ }
+ }
+}
+
+data class TimetableProgressData(
+ val lessons: List,
+ val accentColor: Int,
+ val breakColor: Int,
+ val language: String? = null,
+)
diff --git a/firka/android/app/src/main/kotlin/app/firka/naplo/glance/WidgetLesson.kt b/firka/android/app/src/main/kotlin/app/firka/naplo/glance/WidgetLesson.kt
index 8f1de251..ed49d908 100644
--- a/firka/android/app/src/main/kotlin/app/firka/naplo/glance/WidgetLesson.kt
+++ b/firka/android/app/src/main/kotlin/app/firka/naplo/glance/WidgetLesson.kt
@@ -41,6 +41,9 @@ class WidgetLesson(data: JSONObject) {
val start: LocalDateTime = parseDateTime(data.optString("start", data.optString("KezdetIdopont", "")))
val end: LocalDateTime = parseDateTime(data.optString("end", data.optString("VegIdopont", "")))
val lessonNumber: Int? = data.getIntOrNull("dailyNth") ?: data.getIntOrNull("Oraszam")
- val roomName: String? = data.getStringOrNull("roomName") ?: data.getStringOrNull("TeremNeve")
- val substituteTeacher: String? = data.getStringOrNull("substituteTeacher") ?: data.getStringOrNull("HelyettesTanarNeve")
+ val roomName: String? = (data.getStringOrNull("roomName") ?: data.getStringOrNull("TeremNeve"))
+ ?.takeIf { it != "null" && it != "-" && it.isNotBlank() }
+ val substituteTeacher: String? = (data.getStringOrNull("substituteTeacher") ?: data.getStringOrNull("HelyettesTanarNeve"))
+ ?.takeIf { it != "null" && it != "-" && it.isNotBlank() }
+ val icon: String? = data.getStringOrNull("icon")
}
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_applications.xml b/firka/android/app/src/main/res/drawable/ic_subject_applications.xml
new file mode 100644
index 00000000..2ea48440
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_applications.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_art.xml b/firka/android/app/src/main/res/drawable/ic_subject_art.xml
new file mode 100644
index 00000000..f7ab7b09
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_art.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_attitude.xml b/firka/android/app/src/main/res/drawable/ic_subject_attitude.xml
new file mode 100644
index 00000000..083d6de9
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_attitude.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_biology.xml b/firka/android/app/src/main/res/drawable/ic_subject_biology.xml
new file mode 100644
index 00000000..30973491
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_biology.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_break.xml b/firka/android/app/src/main/res/drawable/ic_subject_break.xml
new file mode 100644
index 00000000..96136136
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_break.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_chemistry.xml b/firka/android/app/src/main/res/drawable/ic_subject_chemistry.xml
new file mode 100644
index 00000000..80facc61
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_chemistry.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_code.xml b/firka/android/app/src/main/res/drawable/ic_subject_code.xml
new file mode 100644
index 00000000..7a434fb8
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_code.xml
@@ -0,0 +1,13 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_dance.xml b/firka/android/app/src/main/res/drawable/ic_subject_dance.xml
new file mode 100644
index 00000000..a1ff581c
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_dance.xml
@@ -0,0 +1,14 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_database.xml b/firka/android/app/src/main/res/drawable/ic_subject_database.xml
new file mode 100644
index 00000000..2fdff676
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_database.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_diligence.xml b/firka/android/app/src/main/res/drawable/ic_subject_diligence.xml
new file mode 100644
index 00000000..17bde987
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_diligence.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_economics.xml b/firka/android/app/src/main/res/drawable/ic_subject_economics.xml
new file mode 100644
index 00000000..455a8e6b
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_economics.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_electricalengineering.xml b/firka/android/app/src/main/res/drawable/ic_subject_electricalengineering.xml
new file mode 100644
index 00000000..dda806bb
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_electricalengineering.xml
@@ -0,0 +1,14 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_env.xml b/firka/android/app/src/main/res/drawable/ic_subject_env.xml
new file mode 100644
index 00000000..f546be17
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_env.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_erettsegi.xml b/firka/android/app/src/main/res/drawable/ic_subject_erettsegi.xml
new file mode 100644
index 00000000..8dbde9e4
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_erettsegi.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_film.xml b/firka/android/app/src/main/res/drawable/ic_subject_film.xml
new file mode 100644
index 00000000..2c34a838
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_film.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_geography.xml b/firka/android/app/src/main/res/drawable/ic_subject_geography.xml
new file mode 100644
index 00000000..53e3af29
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_geography.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_grammar.xml b/firka/android/app/src/main/res/drawable/ic_subject_grammar.xml
new file mode 100644
index 00000000..984f22b0
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_grammar.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_history.xml b/firka/android/app/src/main/res/drawable/ic_subject_history.xml
new file mode 100644
index 00000000..be23eeb6
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_history.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_it.xml b/firka/android/app/src/main/res/drawable/ic_subject_it.xml
new file mode 100644
index 00000000..623e4501
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_it.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_language.xml b/firka/android/app/src/main/res/drawable/ic_subject_language.xml
new file mode 100644
index 00000000..2856ebd6
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_language.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_linux.xml b/firka/android/app/src/main/res/drawable/ic_subject_linux.xml
new file mode 100644
index 00000000..01225071
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_linux.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_literature.xml b/firka/android/app/src/main/res/drawable/ic_subject_literature.xml
new file mode 100644
index 00000000..7e4d74e0
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_literature.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_mathematics.xml b/firka/android/app/src/main/res/drawable/ic_subject_mathematics.xml
new file mode 100644
index 00000000..c4e40435
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_mathematics.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_mechanicalengineering.xml b/firka/android/app/src/main/res/drawable/ic_subject_mechanicalengineering.xml
new file mode 100644
index 00000000..1fca7940
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_mechanicalengineering.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_music.xml b/firka/android/app/src/main/res/drawable/ic_subject_music.xml
new file mode 100644
index 00000000..1b6f16bc
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_music.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_networking.xml b/firka/android/app/src/main/res/drawable/ic_subject_networking.xml
new file mode 100644
index 00000000..5c8b181b
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_networking.xml
@@ -0,0 +1,14 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_ofo.xml b/firka/android/app/src/main/res/drawable/ic_subject_ofo.xml
new file mode 100644
index 00000000..093206d6
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_ofo.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_pe.xml b/firka/android/app/src/main/res/drawable/ic_subject_pe.xml
new file mode 100644
index 00000000..cd4951e4
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_pe.xml
@@ -0,0 +1,13 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_philosophy.xml b/firka/android/app/src/main/res/drawable/ic_subject_philosophy.xml
new file mode 100644
index 00000000..53c96a17
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_philosophy.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_physics.xml b/firka/android/app/src/main/res/drawable/ic_subject_physics.xml
new file mode 100644
index 00000000..4c76d22d
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_physics.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_project.xml b/firka/android/app/src/main/res/drawable/ic_subject_project.xml
new file mode 100644
index 00000000..de363861
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_project.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_religion.xml b/firka/android/app/src/main/res/drawable/ic_subject_religion.xml
new file mode 100644
index 00000000..206fe2da
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_religion.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_technika.xml b/firka/android/app/src/main/res/drawable/ic_subject_technika.xml
new file mode 100644
index 00000000..e6484feb
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_technika.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_theatre.xml b/firka/android/app/src/main/res/drawable/ic_subject_theatre.xml
new file mode 100644
index 00000000..633a1dc7
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_theatre.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/android/app/src/main/res/drawable/ic_subject_unknown.xml b/firka/android/app/src/main/res/drawable/ic_subject_unknown.xml
new file mode 100644
index 00000000..86137e2f
--- /dev/null
+++ b/firka/android/app/src/main/res/drawable/ic_subject_unknown.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/firka/lib/api/client/kreta_client.dart b/firka/lib/api/client/kreta_client.dart
index 785f6409..02205e21 100644
--- a/firka/lib/api/client/kreta_client.dart
+++ b/firka/lib/api/client/kreta_client.dart
@@ -572,19 +572,40 @@ class KretaClient {
}
Future getStudent() async {
- return (await _renewCache(
+ final list = await _renewCache(
KretaEndpoints.getStudent(cache.token.iss),
StudentCacheModel.new,
(cache) => Student.fromJson(cache),
- ).then(_save)).first;
+ ).then(_save);
+ if (list.isNotEmpty) {
+ return list.first;
+ }
+ final existing = cache.findStudentOrNull();
+ if (existing != null) {
+ logger.warning("getStudent returned empty, falling back to cached student");
+ return existing;
+ }
+ throw StateError("No student data returned from Kreta and no cached student found");
}
Future> getClassGroups() async {
- return await _renewCache(
+ final list = await _renewCache(
KretaEndpoints.getClassGroups(cache.token.iss),
ClassGroupCacheModel.new,
(item) => ClassGroup.fromJson(item),
).then(_save);
+ if (list.isNotEmpty) {
+ return list;
+ }
+ final existing = isarInit.classGroupCacheModels
+ .filter()
+ .group(cache.isCurrentClassGroup)
+ .findAllSync();
+ if (existing.isNotEmpty) {
+ logger.warning("getClassGroups returned empty, falling back to cached class groups");
+ return existing;
+ }
+ return list;
}
Future> getNoticeBoard({
diff --git a/firka/lib/app/initialization.dart b/firka/lib/app/initialization.dart
index 2a1fe91e..197789ef 100644
--- a/firka/lib/app/initialization.dart
+++ b/firka/lib/app/initialization.dart
@@ -10,6 +10,7 @@ import 'package:firka/app/app_state.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:firka/services/notification_delivery_service.dart';
+import 'package:firka/services/progress_notification_service.dart';
import 'package:firka/data/widget.dart';
import 'package:firka/core/settings/settings_effects.dart';
import 'package:firka/core/settings/settings_repository.dart';
@@ -28,6 +29,7 @@ import 'package:isar_community/isar.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
+
Future initLang(AppInitialization data) async {
switch (Settings.language.value) {
case AppLanguage.hu:
@@ -166,6 +168,7 @@ Future _initData(AppInitialization init) async {
logger.info(
"[Init] System locale changed in auto mode: $previousLocale -> $nextLocale",
);
+ await ProgressNotificationService.syncStrings(init.l10n);
}
init.themeCubit.refresh();
}());
@@ -209,6 +212,7 @@ Future _initData(AppInitialization init) async {
// Immediately refresh widget state from cached Isar lessons so widget is up to date
unawaited(WidgetCacheHelper.updateWidgetCacheFromIsar());
+ unawaited(ProgressNotificationService.checkAndStartOnMorning());
// Don't block first paint on the network: render whatever is already
// cached, then stream in student/timetable/grades/etc. as they arrive.
@@ -225,6 +229,7 @@ Future _initData(AppInitialization init) async {
await init.client!.renewCache(reInit: false);
await WidgetCacheHelper.updateWidgetCacheFromIsar();
+ unawaited(ProgressNotificationService.checkAndStartIfActive());
init.homeRefreshCubit.requestRefresh();
}());
diff --git a/firka/lib/core/settings.dart b/firka/lib/core/settings.dart
index 26ccfc79..f0e31900 100644
--- a/firka/lib/core/settings.dart
+++ b/firka/lib/core/settings.dart
@@ -293,6 +293,13 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsRegistry.notifyAll,
always,
),
+ SettingsUiBoolean(
+ FirkaIconType.majesticons,
+ Majesticon.clockSolid,
+ l10n.s_progress_notification,
+ SettingsRegistry.progressNotificationEnabled,
+ isPushNotificationsEnabled,
+ ),
SettingsUiHeaderSmall(l10n.s_notif_delivery_method_header, isPushNotificationsEnabled),
SettingsUiEnum(SettingsRegistry.notificationDeliveryMethod, [
l10n.s_notif_delivery_auto,
diff --git a/firka/lib/core/settings/settings_effects.dart b/firka/lib/core/settings/settings_effects.dart
index 51950f3c..8471f2aa 100644
--- a/firka/lib/core/settings/settings_effects.dart
+++ b/firka/lib/core/settings/settings_effects.dart
@@ -6,8 +6,10 @@ import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
import "package:firka/services/fcm_service.dart";
import "package:firka/services/notification_delivery_service.dart";
+import "package:firka/services/progress_notification_service.dart";
import "package:firka/services/watch_sync_helper.dart";
+import "package:firka/data/widget.dart";
import "settings_repository.dart";
import "settings_schema.dart";
@@ -20,6 +22,8 @@ void registerSettingsEffects(
repo.onChange(SettingsRegistry.language, (_) async {
await initLang(initData);
initData.homeRefreshCubit.requestRefresh();
+ await WidgetCacheHelper.updateWidgetCacheFromIsar();
+ await ProgressNotificationService.syncStrings(initData.l10n);
});
repo.onChange(SettingsRegistry.themeBrightness, (_) async {
@@ -56,12 +60,17 @@ void registerSettingsEffects(
repo.onChange(SettingsRegistry.notifyAll, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
+ await ProgressNotificationService.sync();
});
repo.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
});
+ repo.onChange(SettingsRegistry.progressNotificationEnabled, (_) async {
+ await ProgressNotificationService.sync();
+ });
+
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
await NotificationDeliveryService.handleWakeupIntervalChange();
});
diff --git a/firka/lib/core/settings/settings_schema.dart b/firka/lib/core/settings/settings_schema.dart
index 95011ca0..89d9ae90 100644
--- a/firka/lib/core/settings/settings_schema.dart
+++ b/firka/lib/core/settings/settings_schema.dart
@@ -191,4 +191,7 @@ abstract class SettingsSchema {
// colliding cacheKey scheme (see LessonCacheModel.cacheKey history).
@BoolSetting(id: 1048, defaultValue: false)
bool get lessonCacheKeyMigrationDone;
+
+ @BoolSetting(id: 1049, defaultValue: false)
+ bool get progressNotificationEnabled;
}
diff --git a/firka/lib/core/settings/settings_schema.gen.dart b/firka/lib/core/settings/settings_schema.gen.dart
index e8210645..6276d8bb 100644
--- a/firka/lib/core/settings/settings_schema.gen.dart
+++ b/firka/lib/core/settings/settings_schema.gen.dart
@@ -46,9 +46,10 @@ class SettingsRegistry {
static const fcmDebugNotifyOnMessage = BoolSetting(id: 1046, defaultValue: false);
static const notificationDeliveryMethod = EnumSetting(id: 1047, defaultValue: NotificationDeliveryMethod.auto, values: NotificationDeliveryMethod.values);
static const lessonCacheKeyMigrationDone = BoolSetting(id: 1048, defaultValue: false);
+ static const progressNotificationEnabled = BoolSetting(id: 1049, defaultValue: false);
static const all = [
- bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod, lessonCacheKeyMigrationDone,
+ bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod, lessonCacheKeyMigrationDone, progressNotificationEnabled,
];
}
@@ -96,4 +97,5 @@ extension SettingsAccessors on SettingsRepository {
SilentlySettable get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
SilentlySettable get notificationDeliveryMethod => SilentlySettable(this, SettingsRegistry.notificationDeliveryMethod);
SilentlySettable get lessonCacheKeyMigrationDone => SilentlySettable(this, SettingsRegistry.lessonCacheKeyMigrationDone);
+ SilentlySettable get progressNotificationEnabled => SilentlySettable(this, SettingsRegistry.progressNotificationEnabled);
}
diff --git a/firka/lib/data/widget.dart b/firka/lib/data/widget.dart
index 6e4cb6de..1c11a9be 100644
--- a/firka/lib/data/widget.dart
+++ b/firka/lib/data/widget.dart
@@ -1,6 +1,9 @@
import 'dart:convert';
import 'dart:io';
+import 'dart:ui' as ui;
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka_common/data/database.dart';
import 'package:firka_common/data/models/lesson_cache_model.dart';
@@ -13,6 +16,7 @@ import 'package:firka/core/debug_helper.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
+import 'package:firka_common/core/icon_helper.dart';
import 'package:firka/ui/theme/style.dart';
class WidgetCacheHelper {
@@ -29,6 +33,7 @@ class WidgetCacheHelper {
'topic': lesson.topic,
'state': lesson.state,
'type': lesson.type,
+ 'icon': getIconTypeByName(lesson.name)?.name,
// Backward-compatibility aliases for legacy receivers
'Nev': lesson.name,
'KezdetIdopont': lesson.start.toIso8601String(),
@@ -48,7 +53,18 @@ class WidgetCacheHelper {
final colors = style != null
? _colorsMap(style)
: (existingColors ?? _defaultColors());
- return {'colors': colors, 'timetable': timetableJson};
+ String? languageCode;
+ try {
+ final lang = Settings.language.value;
+ languageCode = lang == AppLanguage.auto
+ ? ui.PlatformDispatcher.instance.locale.languageCode
+ : lang.name;
+ } catch (_) {}
+ return {
+ 'colors': colors,
+ 'timetable': timetableJson,
+ if (languageCode != null) 'language': languageCode,
+ };
}
static Map toAndroidWidgetJson(
diff --git a/firka/lib/l10n b/firka/lib/l10n
index 44801bea..e01d6c09 160000
--- a/firka/lib/l10n
+++ b/firka/lib/l10n
@@ -1 +1 @@
-Subproject commit 44801bea9c39840097795e74d64916eb5d280c9f
+Subproject commit e01d6c090dd3b4928c0eb609111fb3f11e3e4bf8
diff --git a/firka/lib/services/notification_delivery_service.dart b/firka/lib/services/notification_delivery_service.dart
index a71a39a4..2a4027c2 100644
--- a/firka/lib/services/notification_delivery_service.dart
+++ b/firka/lib/services/notification_delivery_service.dart
@@ -12,6 +12,7 @@ import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka/services/fcm_service.dart';
+import 'package:firka/services/progress_notification_service.dart';
class NotificationDeliveryService {
static final Logger _logger = Logger('NotificationDeliveryService');
@@ -103,6 +104,8 @@ class NotificationDeliveryService {
case NotificationDeliveryMethod.auto:
break;
}
+
+ await ProgressNotificationService.sync();
} catch (e, st) {
_logger.warning('Failed to sync delivery backend: $e', e, st);
}
diff --git a/firka/lib/services/notification_diff_service.dart b/firka/lib/services/notification_diff_service.dart
index 9cb1d446..aeb01d7f 100644
--- a/firka/lib/services/notification_diff_service.dart
+++ b/firka/lib/services/notification_diff_service.dart
@@ -19,6 +19,7 @@ import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/data/widget.dart';
import 'package:firka/services/fcm_headless_bootstrap.dart';
import 'package:firka/services/local_notification_service.dart';
+import 'package:firka/services/progress_notification_service.dart';
/// Runs on a silent FCM wakeup: for every locally logged-in account, fetches
/// grades/homework/tests/absences/lessons/messages, diffs each against what
@@ -46,6 +47,8 @@ class NotificationDiffService {
_logger.warning('checkAll: account ${token.username} failed: $e', e, st);
}
}
+
+ await ProgressNotificationService.checkAndStartIfActive();
}
static Future _checkAccount(
diff --git a/firka/lib/services/progress_notification_service.dart b/firka/lib/services/progress_notification_service.dart
new file mode 100644
index 00000000..be59d22e
--- /dev/null
+++ b/firka/lib/services/progress_notification_service.dart
@@ -0,0 +1,227 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:isar_community/isar.dart';
+import 'package:logging/logging.dart';
+
+import 'package:firka_common/core/debug_helper.dart';
+import 'package:firka_common/data/database.dart';
+import 'package:firka_common/data/models/lesson_cache_model.dart';
+import 'package:firka/app/app_state.dart';
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/data/widget.dart';
+import 'package:firka/l10n/app_localizations.dart';
+import 'package:firka/services/notification_delivery_service.dart';
+
+class ProgressNotificationService {
+ static final Logger _logger = Logger('ProgressNotificationService');
+ static const MethodChannel _channel = MethodChannel('app.firka/progress_notification');
+
+ @visibleForTesting
+ static bool? isAndroidOverride;
+
+ static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
+
+ /// Syncs notification string templates from Flutter ARB localizations to Android SharedPreferences.
+ static Future syncStrings([AppLocalizations? l10n]) async {
+ if (!_isAndroid) return;
+ try {
+ l10n ??= initDone ? initData.l10n : null;
+ if (l10n == null) return;
+ final strings = {
+ 'progress_notif_channel_name': l10n.progress_notif_channel_name,
+ 'progress_notif_channel_desc': l10n.progress_notif_channel_desc,
+ 'progress_notif_lesson_title': l10n.progress_notif_lesson_title('{number}', '{name}'),
+ 'progress_notif_substitution': l10n.progress_notif_substitution,
+ 'progress_notif_case1_text': l10n.progress_notif_case1_text(
+ '{minutes}',
+ '{timeRange}',
+ '{room}',
+ '{substitution}',
+ '{remaining}',
+ ),
+ 'progress_notif_case2_lesson_text': l10n.progress_notif_case2_lesson_text(
+ '{minutes}',
+ '{timeRange}',
+ '{room}',
+ '{substitution}',
+ '{remaining}',
+ ),
+ 'progress_notif_case2_break_title': l10n.progress_notif_case2_break_title,
+ 'progress_notif_case2_break_text': l10n.progress_notif_case2_break_text(
+ '{minutes}',
+ '{remaining}',
+ ),
+ 'progress_notif_critical_text': l10n.progress_notif_critical_text('{minutes}'),
+ 'progress_notif_remaining_lessons_one': l10n.progress_notif_remaining_lessons_one,
+ 'progress_notif_remaining_lessons_other': l10n.progress_notif_remaining_lessons_other('{count}'),
+ };
+ await _channel.invokeMethod('updateProgressStrings', strings);
+ _logger.info('Synced progress notification strings to native platform');
+ } catch (e, st) {
+ _logger.warning('Failed to sync progress notification strings: $e', e, st);
+ }
+ }
+
+ static Future startService() async {
+ if (!_isAndroid) return false;
+ try {
+ await syncStrings();
+ final res = await _channel.invokeMethod('startProgressService');
+ _logger.info('Started ProgressNotificationForegroundService: $res');
+ return res ?? true;
+ } catch (e, st) {
+ _logger.warning('Failed to start ProgressNotificationForegroundService: $e', e, st);
+ return false;
+ }
+ }
+
+ static Future stopService() async {
+ if (!_isAndroid) return false;
+ try {
+ final res = await _channel.invokeMethod('stopProgressService');
+ _logger.info('Stopped ProgressNotificationForegroundService: $res');
+ return res ?? true;
+ } catch (e, st) {
+ _logger.warning('Failed to stop ProgressNotificationForegroundService: $e', e, st);
+ return false;
+ }
+ }
+
+ static Future schedule6AmAlarm() async {
+ if (!_isAndroid) return false;
+ try {
+ final res = await _channel.invokeMethod('schedule6AmAlarm');
+ _logger.info('Scheduled 6 AM progress alarm: $res');
+ return res ?? true;
+ } catch (e, st) {
+ _logger.warning('Failed to schedule 6 AM progress alarm: $e', e, st);
+ return false;
+ }
+ }
+
+ static Future cancel6AmAlarm() async {
+ if (!_isAndroid) return false;
+ try {
+ final res = await _channel.invokeMethod('cancel6AmAlarm');
+ _logger.info('Cancelled 6 AM progress alarm: $res');
+ return res ?? true;
+ } catch (e, st) {
+ _logger.warning('Failed to cancel 6 AM progress alarm: $e', e, st);
+ return false;
+ }
+ }
+
+ static Future isRunning() async {
+ if (!_isAndroid) return false;
+ try {
+ final res = await _channel.invokeMethod('isProgressServiceRunning');
+ return res ?? false;
+ } catch (e, st) {
+ _logger.warning('Failed to check if progress service is running: $e', e, st);
+ return false;
+ }
+ }
+
+ /// Syncs service state based on current settings and delivery method.
+ static Future sync() async {
+ if (!_isAndroid) return;
+
+ await syncStrings();
+
+ final isEnabled = Settings.progressNotificationEnabled.value && Settings.notifyAll.value;
+ if (!isEnabled) {
+ _logger.info('Progress notifications disabled, stopping service and cancelling alarm');
+ await stopService();
+ await cancel6AmAlarm();
+ return;
+ }
+
+ final deliveryMethod = await NotificationDeliveryService.getEffectiveMethod();
+ if (deliveryMethod == NotificationDeliveryMethod.alarm) {
+ await schedule6AmAlarm();
+ } else {
+ await cancel6AmAlarm();
+ }
+
+ await checkAndStartIfActive();
+ }
+
+ /// Checks if current time is on/after the start date (first lesson start)
+ /// and before the last lesson ends. If so, and the progress-centric
+ /// notification is not running, starts it up.
+ static Future checkAndStartOnAppOpen() async {
+ if (!_isAndroid) return;
+ if (!Settings.progressNotificationEnabled.value || !Settings.notifyAll.value) return;
+
+ try {
+ final now = timeNow();
+ final startOfDay = DateTime(now.year, now.month, now.day);
+ final endOfDay = DateTime(now.year, now.month, now.day, 23, 59, 59);
+
+ var lessons = await isarInit.lessonCacheModels
+ .filter()
+ .startBetween(startOfDay, endOfDay)
+ .sortByStart()
+ .findAll();
+
+ if (lessons.isEmpty) {
+ lessons = await isarInit.lessonCacheModels
+ .filter()
+ .on(now)
+ .sortByStart()
+ .findAll();
+ }
+
+ if (lessons.isEmpty) {
+ _logger.info('No lessons for today; not starting progress service on app open');
+ return;
+ }
+
+ final firstLesson = lessons.first;
+ final lastLesson = lessons.last;
+ final startDate = firstLesson.start;
+
+ final isAboveStartDate = now.isAfter(startDate) || now.isAtSameMomentAs(startDate);
+ final isBelowLastLesson = now.isBefore(lastLesson.end);
+
+ if (!isAboveStartDate) {
+ _logger.info('Current time ($now) is before start date ($startDate); not starting progress service');
+ return;
+ }
+
+ if (!isBelowLastLesson) {
+ _logger.info('Current time ($now) is after last lesson end (${lastLesson.end}); stopping/not starting progress service');
+ final running = await isRunning();
+ if (running) {
+ await stopService();
+ }
+ return;
+ }
+
+ final running = await isRunning();
+ if (!running) {
+ _logger.info('Time is within school day and progress service is not running; starting up');
+ await WidgetCacheHelper.updateWidgetCacheFromIsar();
+ await startService();
+ } else {
+ _logger.info('Progress service is already running');
+ }
+ } catch (e, st) {
+ _logger.warning('Error in checkAndStartOnAppOpen: $e', e, st);
+ }
+ }
+
+ /// Checks if today has lessons and if current time is within active bounds.
+ static Future checkAndStartIfActive() async {
+ await checkAndStartOnAppOpen();
+ }
+
+ /// Called on app startup in the morning.
+ static Future checkAndStartOnMorning() async {
+ await sync();
+ }
+}
diff --git a/firka/lib/ui/phone/pages/home/home_timetable.dart b/firka/lib/ui/phone/pages/home/home_timetable.dart
index 0033530d..1c560dfa 100644
--- a/firka/lib/ui/phone/pages/home/home_timetable.dart
+++ b/firka/lib/ui/phone/pages/home/home_timetable.dart
@@ -167,12 +167,16 @@ class _HomeTimetableScreen extends FirkaState
return TimeTableDayWidget(
lessons,
events,
- onRefresh: () => widget.data.client!.pullRefresh(
- () => widget.data.client!.getLessonsCovering(
- _currentTabWeekMonday,
- _currentTabWeekMonday.add(const Duration(days: 7)),
- ),
- ),
+ onRefresh: () async {
+ await widget.data.client!.pullRefresh(
+ () => widget.data.client!.getLessonsCovering(
+ _currentTabWeekMonday,
+ _currentTabWeekMonday.add(const Duration(days: 7)),
+ ),
+ );
+ _lessonsCache.clear();
+ if (mounted) setState(() {});
+ },
);
}
diff --git a/firka/lib/ui/phone/screens/home/home_screen.dart b/firka/lib/ui/phone/screens/home/home_screen.dart
index feecbd84..b1fe0bb0 100644
--- a/firka/lib/ui/phone/screens/home/home_screen.dart
+++ b/firka/lib/ui/phone/screens/home/home_screen.dart
@@ -1,8 +1,10 @@
+import 'dart:async';
import 'dart:io';
import 'package:firka/core/bloc/toast_cubit.dart';
import 'package:firka/core/firka_bundle.dart';
import 'package:firka/core/settings.dart';
import 'package:firka/app/app_state.dart';
+import 'package:firka/services/progress_notification_service.dart';
import 'package:firka/ui/theme/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -164,6 +166,8 @@ class _HomeScreenState extends FirkaState
super.didChangeAppLifecycleState(state);
if (state != AppLifecycleState.resumed || _disposed) return;
+ unawaited(ProgressNotificationService.checkAndStartOnAppOpen());
+
final lastPrefetch = _lastPrefetchAt;
if (lastPrefetch != null &&
DateTime.now().difference(lastPrefetch) < _prefetchCooldown) {
diff --git a/firka/test/services/progress_notification_service_test.dart b/firka/test/services/progress_notification_service_test.dart
new file mode 100644
index 00000000..4e5f4bbe
--- /dev/null
+++ b/firka/test/services/progress_notification_service_test.dart
@@ -0,0 +1,314 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:firka_common/core/debug_helper.dart';
+import 'package:firka_common/data/database.dart';
+import 'package:firka_common/data/models/lesson_cache_model.dart';
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/l10n/app_localizations_en.dart';
+import 'package:firka/l10n/app_localizations_hu.dart';
+import 'package:firka/services/notification_delivery_service.dart';
+import 'package:firka/services/progress_notification_service.dart';
+import 'package:isar_community/isar.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const progressChannel = MethodChannel('app.firka/progress_notification');
+ late Directory tempDir;
+ late List progressCalls;
+
+ setUp(() async {
+ progressCalls = [];
+ ProgressNotificationService.isAndroidOverride = true;
+ NotificationDeliveryService.isAndroidOverride = true;
+ NotificationDeliveryService.resetForTesting();
+ NotificationDeliveryService.gmsAvailabilityOverride = true;
+
+ tempDir = Directory.systemTemp.createTempSync('progress_test_');
+
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ const MethodChannel('plugins.flutter.io/path_provider'),
+ (MethodCall methodCall) async => tempDir.path,
+ );
+
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ progressChannel,
+ (MethodCall call) async {
+ progressCalls.add(call);
+ return true;
+ },
+ );
+
+ final isar = await initDB();
+ await isar.writeTxn(() async {
+ await isar.clear();
+ });
+ Settings = SettingsRepository(isar);
+ await Settings.loadAll();
+ });
+
+ tearDown(() async {
+ debugFakeTime = null;
+ try {
+ if (tempDir.existsSync()) {
+ tempDir.deleteSync(recursive: true);
+ }
+ } catch (_) {}
+ });
+
+ test('progressNotificationEnabled setting defaults to false and can be toggled', () async {
+ expect(Settings.progressNotificationEnabled.value, isFalse);
+ await Settings.progressNotificationEnabled.set(true);
+ expect(Settings.progressNotificationEnabled.value, isTrue);
+ await Settings.progressNotificationEnabled.set(false);
+ expect(Settings.progressNotificationEnabled.value, isFalse);
+ });
+
+ test('startService and stopService invoke appropriate method channel methods', () async {
+ final startRes = await ProgressNotificationService.startService();
+ expect(startRes, isTrue);
+ expect(progressCalls.any((c) => c.method == 'startProgressService'), isTrue);
+
+ final stopRes = await ProgressNotificationService.stopService();
+ expect(stopRes, isTrue);
+ expect(progressCalls.any((c) => c.method == 'stopProgressService'), isTrue);
+ });
+
+ test('schedule6AmAlarm and cancel6AmAlarm invoke appropriate method channel methods', () async {
+ final schedRes = await ProgressNotificationService.schedule6AmAlarm();
+ expect(schedRes, isTrue);
+ expect(progressCalls.any((c) => c.method == 'schedule6AmAlarm'), isTrue);
+
+ final cancelRes = await ProgressNotificationService.cancel6AmAlarm();
+ expect(cancelRes, isTrue);
+ expect(progressCalls.any((c) => c.method == 'cancel6AmAlarm'), isTrue);
+ });
+
+ test('sync stops service and cancels alarm when disabled', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(false);
+ progressCalls.clear();
+
+ await ProgressNotificationService.sync();
+
+ expect(progressCalls.any((c) => c.method == 'stopProgressService'), isTrue);
+ expect(progressCalls.any((c) => c.method == 'cancel6AmAlarm'), isTrue);
+ });
+
+ test('sync schedules 6 AM alarm when delivery method is alarm', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ progressCalls.clear();
+
+ await ProgressNotificationService.sync();
+
+ expect(progressCalls.any((c) => c.method == 'schedule6AmAlarm'), isTrue);
+ });
+
+ test('sync cancels 6 AM alarm when delivery method is FCM (triggers via FCM wakeup)', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
+ progressCalls.clear();
+
+ await ProgressNotificationService.sync();
+
+ expect(progressCalls.any((c) => c.method == 'cancel6AmAlarm'), isTrue);
+ });
+
+ LessonCacheModel makeLesson(String uid, String name, DateTime start, DateTime end) {
+ return LessonCacheModel()
+ ..cacheKey = Isar.autoIncrement
+ ..createdAt = DateTime.now()
+ ..uid = uid
+ ..name = name
+ ..state = 'normal'
+ ..type = 'lesson'
+ ..start = start
+ ..end = end;
+ }
+
+ test('isRunning queries method channel isProgressServiceRunning', () async {
+ progressCalls.clear();
+ final running = await ProgressNotificationService.isRunning();
+ expect(running, isTrue);
+ expect(progressCalls.any((c) => c.method == 'isProgressServiceRunning'), isTrue);
+ });
+
+ test('checkAndStartOnAppOpen does not start when time is before first lesson start', () async {
+ final isar = isarInit;
+ final today = DateTime.now();
+ final lesson1 = makeLesson('l1', 'Math', DateTime(today.year, today.month, today.day, 8, 0), DateTime(today.year, today.month, today.day, 8, 45));
+ final lesson2 = makeLesson('l2', 'History', DateTime(today.year, today.month, today.day, 9, 0), DateTime(today.year, today.month, today.day, 9, 45));
+
+ await isar.writeTxn(() async {
+ await isar.lessonCacheModels.putAll([lesson1, lesson2]);
+ });
+
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+
+ // Set time before first lesson (07:30)
+ debugFakeTime = DateTime(today.year, today.month, today.day, 7, 30);
+ progressCalls.clear();
+
+ await ProgressNotificationService.checkAndStartOnAppOpen();
+
+ expect(progressCalls.any((c) => c.method == 'startProgressService'), isFalse);
+ });
+
+ test('checkAndStartOnAppOpen starts service when time is within school day and service is not running', () async {
+ final isar = isarInit;
+ final today = DateTime.now();
+ final lesson1 = makeLesson('l1', 'Math', DateTime(today.year, today.month, today.day, 8, 0), DateTime(today.year, today.month, today.day, 8, 45));
+ final lesson2 = makeLesson('l2', 'History', DateTime(today.year, today.month, today.day, 9, 0), DateTime(today.year, today.month, today.day, 9, 45));
+
+ await isar.writeTxn(() async {
+ await isar.lessonCacheModels.putAll([lesson1, lesson2]);
+ });
+
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+
+ // Mock isProgressServiceRunning returning false
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ progressChannel,
+ (MethodCall call) async {
+ progressCalls.add(call);
+ if (call.method == 'isProgressServiceRunning') return false;
+ return true;
+ },
+ );
+
+ // Set time inside school day (08:20)
+ debugFakeTime = DateTime(today.year, today.month, today.day, 8, 20);
+ progressCalls.clear();
+
+ await ProgressNotificationService.checkAndStartOnAppOpen();
+
+ expect(progressCalls.any((c) => c.method == 'isProgressServiceRunning'), isTrue);
+ expect(progressCalls.any((c) => c.method == 'startProgressService'), isTrue);
+ });
+
+ test('checkAndStartOnAppOpen does not start service when already running', () async {
+ final isar = isarInit;
+ final today = DateTime.now();
+ final lesson1 = makeLesson('l1', 'Math', DateTime(today.year, today.month, today.day, 8, 0), DateTime(today.year, today.month, today.day, 8, 45));
+ final lesson2 = makeLesson('l2', 'History', DateTime(today.year, today.month, today.day, 9, 0), DateTime(today.year, today.month, today.day, 9, 45));
+
+ await isar.writeTxn(() async {
+ await isar.lessonCacheModels.putAll([lesson1, lesson2]);
+ });
+
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+
+ // Mock isProgressServiceRunning returning true
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ progressChannel,
+ (MethodCall call) async {
+ progressCalls.add(call);
+ if (call.method == 'isProgressServiceRunning') return true;
+ return true;
+ },
+ );
+
+ // Set time inside school day (08:20)
+ debugFakeTime = DateTime(today.year, today.month, today.day, 8, 20);
+ progressCalls.clear();
+
+ await ProgressNotificationService.checkAndStartOnAppOpen();
+
+ expect(progressCalls.any((c) => c.method == 'isProgressServiceRunning'), isTrue);
+ expect(progressCalls.any((c) => c.method == 'startProgressService'), isFalse);
+ });
+
+ test('checkAndStartOnAppOpen stops service and does not start when time is after last lesson end', () async {
+ final isar = isarInit;
+ final today = DateTime.now();
+ final lesson1 = makeLesson('l1', 'Math', DateTime(today.year, today.month, today.day, 8, 0), DateTime(today.year, today.month, today.day, 8, 45));
+ final lesson2 = makeLesson('l2', 'History', DateTime(today.year, today.month, today.day, 9, 0), DateTime(today.year, today.month, today.day, 9, 45));
+
+ await isar.writeTxn(() async {
+ await isar.lessonCacheModels.putAll([lesson1, lesson2]);
+ });
+
+ await Settings.notifyAll.set(true);
+ await Settings.progressNotificationEnabled.set(true);
+
+ // Mock isProgressServiceRunning returning true
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ progressChannel,
+ (MethodCall call) async {
+ progressCalls.add(call);
+ if (call.method == 'isProgressServiceRunning') return true;
+ return true;
+ },
+ );
+
+ // Set time after last lesson (10:00)
+ debugFakeTime = DateTime(today.year, today.month, today.day, 10, 0);
+ progressCalls.clear();
+
+ await ProgressNotificationService.checkAndStartOnAppOpen();
+
+ expect(progressCalls.any((c) => c.method == 'startProgressService'), isFalse);
+ expect(progressCalls.any((c) => c.method == 'stopProgressService'), isTrue);
+ });
+
+ test('syncStrings sends Hungarian strings map to native platform without Unicode symbols', () async {
+ progressCalls.clear();
+ await ProgressNotificationService.syncStrings(AppLocalizationsHu());
+ final call = progressCalls.firstWhere((c) => c.method == 'updateProgressStrings');
+ final map = call.arguments as Map;
+ expect(map['progress_notif_channel_name'], 'Tanítási nap folyamata');
+ expect(map['progress_notif_channel_desc'], 'Élő értesítés a mai órák és szünetek állapotáról');
+ expect(map['progress_notif_lesson_title'], '{number}. óra: {name}');
+ expect(map['progress_notif_substitution'], ' (Helyettesítés)');
+ expect(map['progress_notif_case1_text'], '{minutes} perc múlva ({timeRange}){room}{substitution}{remaining}');
+ expect(map['progress_notif_case2_lesson_text'], '{minutes} perc van hátra ({timeRange}){room}{substitution}{remaining}');
+ expect(map['progress_notif_case2_break_title'], 'Szünet');
+ expect(map['progress_notif_case2_break_text'], '{minutes} perc van hátra{remaining}');
+ expect(map['progress_notif_critical_text'], '{minutes}p');
+ expect(map['progress_notif_remaining_lessons_one'], ' - Még 1 óra van hátra');
+ expect(map['progress_notif_remaining_lessons_other'], ' - Még {count} óra van hátra');
+
+ // Verify none of the strings contain Unicode bullet
+ for (final val in map.values) {
+ expect((val as String).contains('•'), isFalse);
+ }
+ });
+
+ test('syncStrings sends English strings map to native platform without Unicode symbols', () async {
+ progressCalls.clear();
+ await ProgressNotificationService.syncStrings(AppLocalizationsEn());
+ final call = progressCalls.firstWhere((c) => c.method == 'updateProgressStrings');
+ final map = call.arguments as Map;
+ expect(map['progress_notif_channel_name'], 'School day progress');
+ expect(map['progress_notif_channel_desc'], "Live progress notification for today's lessons and breaks");
+ expect(map['progress_notif_lesson_title'], 'Lesson {number}: {name}');
+ expect(map['progress_notif_substitution'], ' (Substitution)');
+ expect(map['progress_notif_case1_text'], 'In {minutes} min ({timeRange}){room}{substitution}{remaining}');
+ expect(map['progress_notif_case2_lesson_text'], '{minutes} min left ({timeRange}){room}{substitution}{remaining}');
+ expect(map['progress_notif_case2_break_title'], 'Break');
+ expect(map['progress_notif_case2_break_text'], '{minutes} min left{remaining}');
+ expect(map['progress_notif_critical_text'], '{minutes}m');
+ expect(map['progress_notif_remaining_lessons_one'], ' - 1 lesson remaining');
+ expect(map['progress_notif_remaining_lessons_other'], ' - {count} lessons remaining');
+
+ // Verify none of the strings contain Unicode bullet
+ for (final val in map.values) {
+ expect((val as String).contains('•'), isFalse);
+ }
+ });
+}
diff --git a/firka_common/lib/core/icon_helper.dart b/firka_common/lib/core/icon_helper.dart
index 9d6feaab..083eb238 100644
--- a/firka_common/lib/core/icon_helper.dart
+++ b/firka_common/lib/core/icon_helper.dart
@@ -117,10 +117,10 @@ Map _iconMap = {
ClassIcon.project: Majesticon.presentationSolid,
};
-ClassIcon? getIconType(SubjectCacheModel subject) {
+ClassIcon? getIconTypeByName(String subjectName) {
ClassIcon? icon;
- final normalized = subject.name
+ final normalized = subjectName
.toLowerCase()
.replaceAll("ö", "o")
.replaceAll("ü", "u")
@@ -143,6 +143,10 @@ ClassIcon? getIconType(SubjectCacheModel subject) {
return icon;
}
+ClassIcon? getIconType(SubjectCacheModel subject) {
+ return getIconTypeByName(subject.name);
+}
+
Uint8List getIconData(ClassIcon? icon) {
if (icon == null) return Majesticon.alertCircleSolid;
diff --git a/firka_common/lib/data/models/lesson_cache_model.dart b/firka_common/lib/data/models/lesson_cache_model.dart
index 060d992b..8edf49ca 100644
--- a/firka_common/lib/data/models/lesson_cache_model.dart
+++ b/firka_common/lib/data/models/lesson_cache_model.dart
@@ -76,11 +76,15 @@ class LessonCacheModel extends GenericCacheModel {
if (classGroup.value == null) {
classGroup.value = isarInit.classGroupCacheModels
- .filter()
- .group(ctx.cacheManager.isCurrentClassGroup)
- .and()
- .typeEqualTo("Osztaly")
- .findFirstSync()!;
+ .filter()
+ .group(ctx.cacheManager.isCurrentClassGroup)
+ .and()
+ .typeEqualTo("Osztaly")
+ .findFirstSync() ??
+ isarInit.classGroupCacheModels
+ .filter()
+ .group(ctx.cacheManager.isCurrentClassGroup)
+ .findFirstSync();
}
}
diff --git a/kreta_api/lib/src/model/student.dart b/kreta_api/lib/src/model/student.dart
index 284fb518..b2bf56ea 100644
--- a/kreta_api/lib/src/model/student.dart
+++ b/kreta_api/lib/src/model/student.dart
@@ -39,25 +39,48 @@ class Student extends NameUid {
factory Student.fromJson(Map json) {
var guardianList = List.empty(growable: true);
- for (var item in json['Gondviselok']) {
- guardianList.add(Guardian.fromJson(item));
+ if (json['Gondviselok'] is List) {
+ for (var item in json['Gondviselok']) {
+ guardianList.add(Guardian.fromJson(item));
+ }
}
return Student(
- addressDataList: List.from(json['Cimek'] as List),
- bankAccount: BankAccount.fromJson(json['Bankszamla']),
+ addressDataList: json['Cimek'] is List
+ ? List.from(json['Cimek'] as List)
+ : const [],
+ bankAccount: json['Bankszamla'] is Map
+ ? BankAccount.fromJson(json['Bankszamla'])
+ : const BankAccount(
+ accountNumber: null,
+ isReadOnly: null,
+ ownerName: null,
+ ownerType: null,
+ ),
birthdate: DateFormat('yyyy-M-d').parse(
"${json['SzuletesiEv']}-${json['SzuletesiHonap']}-${json['SzuletesiNap']}",
),
emailAddress: json['EmailCim'],
- name: json['Nev'],
+ name: json['Nev']?.toString() ?? '',
phoneNumber: json['Telefonszam'],
- schoolYearUID: json['TanevUid'],
- uid: json['Uid'],
+ schoolYearUID: json['TanevUid']?.toString() ?? '',
+ uid: json['Uid'].toString(),
guardianList: guardianList,
- instituteCode: json['IntezmenyAzonosito'],
- instituteName: json['IntezmenyNev'],
- institution: Institution.fromJson(json['Intezmeny']),
+ instituteCode: json['IntezmenyAzonosito']?.toString() ?? '',
+ instituteName: json['IntezmenyNev']?.toString() ?? '',
+ institution: json['Intezmeny'] is Map
+ ? Institution.fromJson(json['Intezmeny'])
+ : Institution(
+ customizationSettings: const CustomizationSettings(
+ delayForNotifications: 0,
+ isClassAverageVisible: true,
+ isLessonsThemeVisible: true,
+ nextServerDeployAsString: '',
+ ),
+ shortName: '',
+ systemModuleList: const [],
+ uid: '',
+ ),
);
}