1
0
forked from firka/firka

feat(android): add progress centric notification support

This commit is contained in:
2026-09-17 20:45:30 +02:00
parent 77af5acba3
commit 02b2043b5c
58 changed files with 2029 additions and 33 deletions

View File

@@ -6,7 +6,12 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<application
android:name=".AppMain"
@@ -17,6 +22,24 @@
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".ProgressNotificationForegroundService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Displays ongoing school day lesson and break progress updates." />
</service>
<receiver
android:name=".ProgressAlarmReceiver"
android:exported="false">
<intent-filter>
<action android:name="app.firka.naplo.ACTION_PROGRESS_6AM_ALARM" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:exported="true"

View File

@@ -7,8 +7,9 @@ import org.json.JSONObject
fun JSONObject.getStringOrNull(key: String): String? {
return try {
if (has(key)) {
getString(key)
if (has(key) && !isNull(key)) {
val v = getString(key)
if (v == "null" || v.isBlank()) null else v
} else {
null
}

View File

@@ -1,5 +1,6 @@
package app.firka.naplo
import android.app.NotificationManager
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
@@ -25,6 +26,7 @@ class MainActivity : FlutterActivity() {
private val channel = "firka.app/main"
private val wearSyncChannel = "app.firka/wear_sync"
private val progressNotificationChannel = "app.firka/progress_notification"
private fun forceIconUpdate() {
try {
@@ -92,6 +94,67 @@ class MainActivity : FlutterActivity() {
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, progressNotificationChannel).setMethodCallHandler { call, result ->
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<String, String>
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) {

View File

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

View File

@@ -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, String>): 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<String, String>) {
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<String, String> {
val prefs = context.applicationContext.getSharedPreferences(PREFS_STRINGS, Context.MODE_PRIVATE)
val all = prefs.all
val result = mutableMapOf<String, String>()
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<WidgetLesson>()
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<WidgetLesson>,
val accentColor: Int,
val breakColor: Int,
val language: String? = null,
)

View File

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

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M19 4H5a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"
android:fillColor="#FFFFFFFF" />
<path
android:pathData="M12 16h7a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h7zm0 0v4m0 0h4m-4 0H8"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M15.586 3a2 2 0 0 1 2.828 0L21 5.586a2 2 0 0 1 0 2.828L19.414 10 14 4.586 15.586 3zm-3 3-9 9A2 2 0 0 0 3 16.414V19a2 2 0 0 0 2 2h2.586A2 2 0 0 0 9 20.414l9-9L12.586 6z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 7.0,8.0 a 5.0,5.0 0 1,0 10.0,0 a 5.0,5.0 0 1,0 -10.0,0 Z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M20 21a8 8 0 1 0-16 0"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M12 13a8 8 0 0 0-8 8h16a8 8 0 0 0-8-8z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M10 1a1 1 0 0 0 0 2h1v1.062A7.96 7.96 0 0 0 7.094 5.68L5.914 4.5l.793-.793a1 1 0 0 0-1.414-1.414l-3 3a1 1 0 0 0 1.414 1.414l.793-.793 1.18 1.18A7.96 7.96 0 0 0 4.062 11H3v-1a1 1 0 0 0-2 0v4a1 1 0 1 0 2 0v-1h1.062c.182 1.46.759 2.8 1.618 3.906l-1.18 1.18-.793-.793a1 1 0 0 0-1.414 1.414l3 3a1 1 0 0 0 1.414-1.414l-.793-.793 1.18-1.18A7.965 7.965 0 0 0 11 19.938V21h-1a1 1 0 1 0 0 2h4a1 1 0 1 0 0-2h-1v-1.062a7.965 7.965 0 0 0 3.906-1.618l1.18 1.18-.793.793a1 1 0 0 0 1.414 1.414l3-3a1 1 0 0 0-1.414-1.414l-.793.793-1.18-1.18A7.965 7.965 0 0 0 19.938 13H21v1a1 1 0 1 0 2 0v-4a1 1 0 1 0-2 0v1h-1.062a7.965 7.965 0 0 0-1.618-3.906l1.18-1.18.793.793a1 1 0 1 0 1.414-1.414l-3-3a1 1 0 1 0-1.414 1.414l.793.793-1.18 1.18A7.966 7.966 0 0 0 13 4.062V3h1a1 1 0 1 0 0-2h-4zm3 13a1 1 0 0 1 1-1h.001a1 1 0 1 1 0 2H14a1 1 0 0 1-1-1zm-3-3.5a.5.5 0 1 1 1 0 .5.5 0 0 1-1 0zm.5-2.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12zm11-5a1 1 0 1 0-2 0v3.764a3 3 0 0 0 1.658 2.683l2.895 1.447a1 1 0 1 0 .894-1.788l-2.894-1.448a1 1 0 0 1-.553-.894V7z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M6 2a1 1 0 0 0 0 2h1v13a5 5 0 0 0 10 0V4h1a1 1 0 1 0 0-2H6zm3 5V4h6v3H9zm4.708 5.708a1 1 0 0 1-1.414 0h-.001a1 1 0 0 1 1.414-1.415 1 1 0 0 1 0 1.415zm-3.414 4a1 1 0 1 0 1.414-1.414v-.001a1 1 0 0 0-1.415 1.414z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M9.5 5H9a2 2 0 0 0-2 2v2c0 1-.6 3-3 3 1 0 3 .6 3 3v2a2 2 0 0 0 2 2h.5m5-14h.5a2 2 0 0 1 2 2v2c0 1 .6 3 3 3-1 0-3 .6-3 3v2a2 2 0 0 1-2 2h-.5"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M17 7a5.001 5.001 0 0 0-4.607 3.053C11.963 11.07 12.896 12 14 12h6c1.105 0 2.037-.93 1.607-1.947A5.001 5.001 0 0 0 17 7zm0 10a5.001 5.001 0 0 0-3.053-4.607C12.93 11.963 12 12.896 12 14v6c0 1.105.93 2.037 1.947 1.607A5.001 5.001 0 0 0 17 17zM7 17a5.001 5.001 0 0 0 4.607-3.053C12.037 12.93 11.104 12 10 12H4c-1.105 0-2.037.93-1.607 1.947A5.001 5.001 0 0 0 7 17zM7 7a5.001 5.001 0 0 0 3.053 4.607C11.07 12.037 12 11.104 12 10V4c0-1.105-.93-2.037-1.947-1.607A5.001 5.001 0 0 0 7 7z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M21 7c0 2.21-4.03 4-9 4S3 9.21 3 7s4.03-4 9-4 9 1.79 9 4z"
android:fillColor="#FFFFFFFF" />
<path
android:pathData="M21 7c0 2.21-4.03 4-9 4S3 9.21 3 7m18 0c0-2.21-4.03-4-9-4S3 4.79 3 7m18 0v5M3 7v5m18 0c0 2.21-4.03 4-9 4s-9-1.79-9-4m18 0v5c0 2.21-4.03 4-9 4s-9-1.79-9-4v-5"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M10 2a3.001 3.001 0 0 0-2.83 2H6a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3h-1.17A3.001 3.001 0 0 0 14 2h-4zM9 5a1 1 0 0 1 1-1h4a1 1 0 1 1 0 2h-4a1 1 0 0 1-1-1zm6.78 6.625a1 1 0 1 0-1.56-1.25l-3.303 4.128-1.21-1.21a1 1 0 0 0-1.414 1.414l2 2a1 1 0 0 0 1.488-.082l4-5z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M21 8c0 1.02-1.186 1.92-3 2.462-1.134.34-2.513.538-4 .538s-2.866-.199-4-.538C8.187 9.92 7 9.02 7 8c0-1.657 3.134-3 7-3s7 1.343 7 3z"
android:fillColor="#FFFFFFFF" />
<path
android:pathData="M21 8c0-1.657-3.134-3-7-3S7 6.343 7 8m14 0v4c0 1.02-1.186 1.92-3 2.462-1.134.34-2.513.538-4 .538s-2.866-.199-4-.538C8.187 13.92 7 13.02 7 12V8m14 0c0 1.02-1.186 1.92-3 2.462-1.134.34-2.513.538-4 .538s-2.866-.199-4-.538C8.187 9.92 7 9.02 7 8"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M3 12v4c0 1.02 1.187 1.92 3 2.462 1.134.34 2.513.538 4 .538s2.866-.199 4-.538c1.813-.542 3-1.442 3-2.462v-1M3 12c0-1.197 1.635-2.23 4-2.711M3 12c0 1.02 1.187 1.92 3 2.462 1.134.34 2.513.538 4 .538.695 0 1.366-.043 2-.124"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4 14 14 3v7h6L10 21v-7H4z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M20.156 6.473a2.639 2.639 0 0 0-2.63-2.629C15.049 3.817 9.909 4.193 6.5 7.6c-2.796 2.796-2.915 7.3-.157 10.057 2.758 2.758 7.26 2.639 10.057-.157 3.407-3.408 3.783-8.548 3.756-11.027zm-4.62 1.991a1 1 0 0 1 0 1.415l-.978.977.587.195a1 1 0 0 1-.633 1.898l-1.535-.512-1.247 1.247.586.196a1 1 0 0 1-.632 1.897l-1.173-.39a3.01 3.01 0 0 1-.344-.14l-2.41 2.41-3.121 3.121a1 1 0 0 1-1.414-1.414l3.121-3.121 2.41-2.41a3.009 3.009 0 0 1-.14-.344l-.39-1.173a1 1 0 0 1 1.897-.632l.196.586 1.247-1.247-.512-1.535a1 1 0 0 1 1.898-.633l.195.587.977-.978a1 1 0 0 1 1.414 0z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 5.0,9.0 a 7.0,7.0 0 1,0 14.0,0 a 7.0,7.0 0 1,0 -14.0,0 Z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M7 20.234V14c.667.667 2.6 2 5 2s4.333-1.333 5-2v6.234a1 1 0 0 1-1.514.857l-2.972-1.782a1 1 0 0 0-1.028 0L8.514 21.09A1 1 0 0 1 7 20.234z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M5 5a3 3 0 0 0-3 3v8a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-1.586l2.293 2.293A1 1 0 0 0 22 16V8a1 1 0 0 0-1.707-.707L18 9.586V8a3 3 0 0 0-3-3H5z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 3.0,12.0 a 9.0,9.0 0 1,0 18.0,0 a 9.0,9.0 0 1,0 -18.0,0 Z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M13.5 6h.5a2 2 0 0 0 2-2C8.4 1.2 4.5 6.5 3.5 9.5l4.167 5.093c.215.263.333.593.333.933C8 16.34 8.673 17 9.487 17c.828 0 1.513.672 1.513 1.5V21c2.167-.167 6.8-1.2 8-4h-1a2 2 0 0 1-2-2 2 2 0 0 0-2-2h-2a2 2 0 0 1-2-2v-1a1 1 0 0 1 1-1 1 1 0 0 0 1-1v-.5A1.5 1.5 0 0 1 13.5 6z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M3 5a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V5zm5 0v7l2.293-2.293a1 1 0 0 1 1.414 0L14 12V5a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12zm14.243-4.243L9.879 9.88l-2.122 6.364 6.364-2.122 2.122-6.364z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M3 6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v7.764l1.447 2.894-.894.448.894-.448c.998 1.995-.453 4.342-2.683 4.342H4.236c-2.23 0-3.68-2.347-2.683-4.342L3 13.764V6zm3-1a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H6z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12 2H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h.93a2 2 0 0 1 1.664.89l.574.862a1 1 0 0 0 1.664 0l.574-.861A2 2 0 0 1 11.07 12H12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M18 10h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-.93a2 2 0 0 0-1.664.89l-.574.862a1 1 0 0 1-1.664 0l-.574-.861A2 2 0 0 0 12.93 20H12a2 2 0 0 1-2-2v-1"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12 3a2 2 0 0 0-1 3.732V8H8c-3.2 0-4 2.667-4 4v7c0 .667.4 2 2 2h1v-4a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v4h1c1.6 0 2-1.333 2-2v-7c0-3.2-2.667-4-4-4h-3V6.732A2 2 0 0 0 12 3zm3 18v-3h-2v3h2zm-4 0v-3H9v3h2zm10-3v-5c.667 0 2 .4 2 2v1c0 .667-.4 2-2 2zM3 13v5c-1.6 0-2-1.333-2-2v-1c0-1.6 1.333-2 2-2zm6-1a1 1 0 1 0 0 2h.001a1 1 0 1 0 0-2H9zm5 1a1 1 0 0 1 1-1h.001a1 1 0 1 1 0 2H15a1 1 0 0 1-1-1z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M11 4.85c-2.195-1.022-5.52-1.565-8.633.979A1 1 0 0 0 2 6.603V19a1 1 0 0 0 1.633.774c2.736-2.236 5.734-1.31 7.367-.255V4.849zm2 0v14.669c1.633-1.056 4.63-1.981 7.367.255A1 1 0 0 0 22 19V6.603a1 1 0 0 0-.367-.774C18.52 3.285 15.195 3.828 13 4.849z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M7 2a3 3 0 0 0-3 3v14a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3H7zm0 4a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V6zm1 7a1 1 0 1 0 0 2h.01a1 1 0 1 0 0-2H8zm3 1a1 1 0 0 1 1-1h.01a1 1 0 1 1 0 2H12a1 1 0 0 1-1-1zm1 2a1 1 0 1 0 0 2h.01a1 1 0 1 0 0-2H12zm-5 1a1 1 0 0 1 1-1h.01a1 1 0 1 1 0 2H8a1 1 0 0 1-1-1zm10-3a1 1 0 1 0-2 0v3a1 1 0 1 0 2 0v-3z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M9.024 2.783A1 1 0 0 1 10 2h4a1 1 0 0 1 .976.783l.44 1.981c.4.19.781.41 1.14.66l1.938-.61a1 1 0 0 1 1.166.454l2 3.464a1 1 0 0 1-.19 1.237l-1.497 1.373a8.1 8.1 0 0 1 0 1.316l1.497 1.373a1 1 0 0 1 .19 1.237l-2 3.464a1 1 0 0 1-1.166.454l-1.937-.61c-.36.25-.741.47-1.14.66l-.44 1.98A1 1 0 0 1 14 22h-4a1 1 0 0 1-.976-.783l-.44-1.981c-.4-.19-.781-.41-1.14-.66l-1.938.61a1 1 0 0 1-1.166-.454l-2-3.464a1 1 0 0 1 .19-1.237l1.497-1.373a8.097 8.097 0 0 1 0-1.316L2.53 9.97a1 1 0 0 1-.19-1.237l2-3.464a1 1 0 0 1 1.166-.454l1.937.61c.36-.25.741-.47 1.14-.66l.44-1.98zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M13 4h4v4h-4v9c0 1-.6 3-3 3s-3-2-3-3 .6-3 3-3 3 2 3 3V4z"
android:fillColor="#FFFFFFFF" />
<path
android:pathData="M13 17V8m0 9c0 1-.6 3-3 3s-3-2-3-3 .6-3 3-3 3 2 3 3zm0-9V4h4v4h-4z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M2 13.5C2 17.9 5.667 19 7.5 19h10c1.5 0 4.5-.9 4.5-4.5S19 10 17.5 10c0-1.5-1.5-5-5-5-2.8 0-4.5 2-5 3C5.667 8 2 9.1 2 13.5z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 5.0,9.0 a 4.0,4.0 0 1,0 8.0,0 a 4.0,4.0 0 1,0 -8.0,0 Z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M9 13c-3.866 0-7 2.686-7 6h14c0-3.314-3.134-6-7-6z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M15 13a4 4 0 1 0-3-6.646m0 5.411c.897.942 2.193 1.235 3 1.235 3.866 0 7 2.686 7 6h-6"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M3 12h4l3 7 4-14 3 7h4"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12 7a5 5 0 0 0-2 9.584V19h4v-2.416A5.001 5.001 0 0 0 12 7z"
android:fillColor="#FFFFFFFF" />
<path
android:pathData="M21 12h1m-3.5-6.5 1-1M12 3V2M5.5 5.5l-1-1M3 12H2m8 10h4m3-10a5 5 0 1 0-7 4.584V19h4v-2.416A5.001 5.001 0 0 0 17 12z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M18.893 7.936a8.003 8.003 0 0 1-7.774 12.016m-6.012-3.888a8.003 8.003 0 0 1 7.774-12.016"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 15.657,6.343 a 2.0,2.0 0 1,0 4.0,0 a 2.0,2.0 0 1,0 -4.0,0 Z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 4.343,17.657 a 2.0,2.0 0 1,0 4.0,0 a 2.0,2.0 0 1,0 -4.0,0 Z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 10.0,12.0 a 2.0,2.0 0 1,0 4.0,0 a 2.0,2.0 0 1,0 -4.0,0 Z"
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M3 2a1 1 0 0 0 0 2v11a1 1 0 0 0 1 1h4.613L7.05 20.684a1 1 0 0 0 1.898.632L10.72 16h2.558l1.772 5.316a1 1 0 0 0 1.898-.632L15.387 16H20a1 1 0 0 0 1-1V4a1 1 0 1 0 0-2H3z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12 3a1 1 0 0 1 1 1v1h1a1 1 0 1 1 0 2h-1v1.5l7.6 5.7A1 1 0 0 1 20 16h-1v3h2a1 1 0 1 1 0 2h-7v-3a2 2 0 1 0-4 0v3H3a1 1 0 1 1 0-2h2v-3H4a1 1 0 0 1-.6-1.8L11 8.5V7h-1a1 1 0 0 1 0-2h1V4a1 1 0 0 1 1-1z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12.879 3.707a3 3 0 0 1 4.242 0l3.172 3.172a3 3 0 0 1 0 4.242l-9.172 9.172a3 3 0 0 1-4.242 0L3.707 17.12a3 3 0 0 1 0-4.242L4.586 12l1.707 1.707a1 1 0 0 0 1.414-1.414L6 10.586 7.586 9l2.707 2.707a1 1 0 0 0 1.414-1.414L9 7.586 10.586 6l1.707 1.707a1 1 0 1 0 1.414-1.414L12 4.586l.879-.879z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M2 3a1 1 0 0 1 1-1h18a1 1 0 1 1 0 2v11a1 1 0 0 1-1 1h-4.613l1.562 4.684a1 1 0 0 1-1.898.632L13.28 16h-2.558L8.95 21.316a1 1 0 1 1-1.898-.632L8.613 16H4a1 1 0 0 1-1-1V4a1 1 0 0 1-1-1zm9.555 3.168A1 1 0 0 0 10 7v4a1 1 0 0 0 1.555.832l3-2a1 1 0 0 0 0-1.664l-3-2zM12.197 9 12 9.131V8.87l.197.131z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 5a1 1 0 0 1 1 1v5a1 1 0 1 1-2 0V8a1 1 0 0 1 1-1zm1 9a1 1 0 1 0-2 0 1 1 0 1 0 2 0z"
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd" />
</vector>

View File

@@ -572,19 +572,40 @@ class KretaClient {
}
Future<StudentCacheModel> getStudent() async {
return (await _renewCache<StudentCacheModel, Student>(
final list = await _renewCache<StudentCacheModel, Student>(
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<List<ClassGroupCacheModel>> 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<List<MessageCacheModel>> getNoticeBoard({

View File

@@ -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<void> initLang(AppInitialization data) async {
switch (Settings.language.value) {
case AppLanguage.hu:
@@ -166,6 +168,7 @@ Future<void> _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<void> _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<void> _initData(AppInitialization init) async {
await init.client!.renewCache(reInit: false);
await WidgetCacheHelper.updateWidgetCacheFromIsar();
unawaited(ProgressNotificationService.checkAndStartIfActive());
init.homeRefreshCubit.requestRefresh();
}());

View File

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

View File

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

View File

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

View File

@@ -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 = <Setting>[
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, 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<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
SilentlySettable<NotificationDeliveryMethod> get notificationDeliveryMethod => SilentlySettable(this, SettingsRegistry.notificationDeliveryMethod);
SilentlySettable<bool> get lessonCacheKeyMigrationDone => SilentlySettable(this, SettingsRegistry.lessonCacheKeyMigrationDone);
SilentlySettable<bool> get progressNotificationEnabled => SilentlySettable(this, SettingsRegistry.progressNotificationEnabled);
}

View File

@@ -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<String, dynamic> toAndroidWidgetJson(

View File

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

View File

@@ -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<void> _checkAccount(

View File

@@ -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<void> syncStrings([AppLocalizations? l10n]) async {
if (!_isAndroid) return;
try {
l10n ??= initDone ? initData.l10n : null;
if (l10n == null) return;
final strings = <String, String>{
'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<bool>('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<bool> startService() async {
if (!_isAndroid) return false;
try {
await syncStrings();
final res = await _channel.invokeMethod<bool>('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<bool> stopService() async {
if (!_isAndroid) return false;
try {
final res = await _channel.invokeMethod<bool>('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<bool> schedule6AmAlarm() async {
if (!_isAndroid) return false;
try {
final res = await _channel.invokeMethod<bool>('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<bool> cancel6AmAlarm() async {
if (!_isAndroid) return false;
try {
final res = await _channel.invokeMethod<bool>('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<bool> isRunning() async {
if (!_isAndroid) return false;
try {
final res = await _channel.invokeMethod<bool>('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<void> 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<void> 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<void> checkAndStartIfActive() async {
await checkAndStartOnAppOpen();
}
/// Called on app startup in the morning.
static Future<void> checkAndStartOnMorning() async {
await sync();
}
}

View File

@@ -167,12 +167,16 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
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(() {});
},
);
}

View File

@@ -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<HomeScreen>
super.didChangeAppLifecycleState(state);
if (state != AppLifecycleState.resumed || _disposed) return;
unawaited(ProgressNotificationService.checkAndStartOnAppOpen());
final lastPrefetch = _lastPrefetchAt;
if (lastPrefetch != null &&
DateTime.now().difference(lastPrefetch) < _prefetchCooldown) {

View File

@@ -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<MethodCall> 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);
}
});
}

View File

@@ -117,10 +117,10 @@ Map<ClassIcon, Uint8List> _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;

View File

@@ -76,11 +76,15 @@ class LessonCacheModel extends GenericCacheModel<Lesson> {
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();
}
}

View File

@@ -39,25 +39,48 @@ class Student extends NameUid {
factory Student.fromJson(Map<String, dynamic> json) {
var guardianList = List<Guardian>.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<String>.from(json['Cimek'] as List),
bankAccount: BankAccount.fromJson(json['Bankszamla']),
addressDataList: json['Cimek'] is List
? List<String>.from(json['Cimek'] as List)
: const [],
bankAccount: json['Bankszamla'] is Map<String, dynamic>
? 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<String, dynamic>
? Institution.fromJson(json['Intezmeny'])
: Institution(
customizationSettings: const CustomizationSettings(
delayForNotifications: 0,
isClassAverageVisible: true,
isLessonsThemeVisible: true,
nextServerDeployAsString: '',
),
shortName: '',
systemModuleList: const [],
uid: '',
),
);
}