forked from firka/firka
fix: restore timetable widget and fix async glance updates
This commit is contained in:
@@ -669,6 +669,7 @@
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
<action android:name="app.firka.naplo.ACTION_REFRESH_WIDGET" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
|
||||
@@ -163,17 +163,10 @@ class MainActivity : FlutterActivity() {
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
val appContext = context.applicationContext
|
||||
val appWidgetManager = AppWidgetManager.getInstance(appContext)
|
||||
val componentName = ComponentName(appContext, TimetableWidgetReceiver::class.java)
|
||||
val ids = appWidgetManager.getAppWidgetIds(componentName)
|
||||
if (ids.isNotEmpty()) {
|
||||
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
|
||||
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
|
||||
}
|
||||
appContext.sendBroadcast(intent)
|
||||
val intent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
action = TimetableWidgetReceiver.ACTION_REFRESH_WIDGET
|
||||
}
|
||||
appContext.sendBroadcast(intent)
|
||||
TimetableWidget().updateAll(appContext)
|
||||
result.success(true)
|
||||
} catch (e: Exception) {
|
||||
@@ -190,6 +183,29 @@ class MainActivity : FlutterActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
private fun handleIntent(intent: Intent?) {
|
||||
val action = intent?.getStringExtra("action")
|
||||
if (action == "pin_widget") {
|
||||
val appWidgetManager = AppWidgetManager.getInstance(this)
|
||||
val myProvider = ComponentName(this, TimetableWidgetReceiver::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && appWidgetManager.isRequestPinAppWidgetSupported) {
|
||||
appWidgetManager.requestPinAppWidget(myProvider, null, null)
|
||||
}
|
||||
} else if (action == "refresh_widget") {
|
||||
val appContext = applicationContext
|
||||
val refreshIntent = Intent(appContext, TimetableWidgetReceiver::class.java).apply {
|
||||
this.action = TimetableWidgetReceiver.ACTION_REFRESH_WIDGET
|
||||
}
|
||||
appContext.sendBroadcast(refreshIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,31 +54,35 @@ class TimetableWidget : GlanceAppWidget() {
|
||||
}
|
||||
|
||||
private fun loadWidgetData(context: Context): WidgetData? {
|
||||
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
|
||||
val widgetStateFile = File(appFlutter, "widget_state.json")
|
||||
if (!widgetStateFile.exists()) return null
|
||||
val widgetState = JSONObject(widgetStateFile.readText(Charsets.UTF_8))
|
||||
val colors = Colors(widgetState)
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
val lessons = mutableListOf<WidgetLesson>()
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(WidgetLesson(tt.getJSONObject(i)))
|
||||
}
|
||||
val displayDateStr = widgetState.optString("displayDate", "")
|
||||
val targetDate = if (displayDateStr.isNotEmpty()) {
|
||||
try {
|
||||
LocalDate.parse(displayDateStr)
|
||||
} catch (_: Exception) {
|
||||
try {
|
||||
val appFlutter = File(context.applicationContext.dataDir, "app_flutter")
|
||||
val widgetStateFile = File(appFlutter, "widget_state.json")
|
||||
if (!widgetStateFile.exists()) return null
|
||||
val text = widgetStateFile.readText(Charsets.UTF_8)
|
||||
val widgetState = JSONObject(text)
|
||||
val colors = Colors(widgetState)
|
||||
val tt = widgetState.getJSONArray("timetable")
|
||||
val lessons = mutableListOf<WidgetLesson>()
|
||||
for (i in 0..<tt.length()) {
|
||||
lessons.add(WidgetLesson(tt.getJSONObject(i)))
|
||||
}
|
||||
val displayDateStr = widgetState.optString("displayDate", "")
|
||||
val targetDate = if (displayDateStr.isNotEmpty()) {
|
||||
try {
|
||||
LocalDate.parse(displayDateStr)
|
||||
} catch (_: Exception) {
|
||||
LocalDate.now()
|
||||
}
|
||||
} else {
|
||||
LocalDate.now()
|
||||
}
|
||||
} else {
|
||||
LocalDate.now()
|
||||
val filtered = lessons.filter { it.start.toLocalDate() == targetDate }
|
||||
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
|
||||
return WidgetData(colors, headerText, filtered)
|
||||
} catch (e: Throwable) {
|
||||
android.util.Log.e("TimetableWidget", "Error in loadWidgetData", e)
|
||||
return null
|
||||
}
|
||||
val start = LocalDateTime.of(targetDate.year, targetDate.month, targetDate.dayOfMonth, 0, 0)
|
||||
val end = start.plusHours(23)
|
||||
val filtered = lessons.filter { it.start.isAfter(start) && it.end.isBefore(end) }
|
||||
val headerText = if (displayDateStr.isNotEmpty()) displayDateStr else "Mai órarend"
|
||||
return WidgetData(colors, headerText, filtered)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -7,9 +7,37 @@ import HomeWidgetGlanceWidgetReceiver
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.glance.appwidget.updateAll
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>() {
|
||||
override val glanceAppWidget = TimetableWidget()
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
super.onReceive(context, intent)
|
||||
val action = intent.action
|
||||
if (action == ACTION_REFRESH_WIDGET ||
|
||||
action == AppWidgetManager.ACTION_APPWIDGET_UPDATE ||
|
||||
action == Intent.ACTION_BOOT_COMPLETED ||
|
||||
action == Intent.ACTION_MY_PACKAGE_REPLACED) {
|
||||
val pendingResult = goAsync()
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
glanceAppWidget.updateAll(context)
|
||||
} catch (e: Exception) {
|
||||
Log.e("TimetableWidget", "Failed glanceAppWidget.updateAll from onReceive", e)
|
||||
} finally {
|
||||
pendingResult.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAppWidgetOptionsChanged(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
@@ -17,9 +45,18 @@ class TimetableWidgetReceiver : HomeWidgetGlanceWidgetReceiver<TimetableWidget>(
|
||||
newOptions: Bundle,
|
||||
) {
|
||||
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
|
||||
runBlocking {
|
||||
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
|
||||
glanceAppWidget.update(context, glanceId)
|
||||
val pendingResult = goAsync()
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
try {
|
||||
val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId)
|
||||
glanceAppWidget.update(context, glanceId)
|
||||
} finally {
|
||||
pendingResult.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_REFRESH_WIDGET = "app.firka.naplo.ACTION_REFRESH_WIDGET"
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,43 @@ import app.firka.naplo.getIntOrNull
|
||||
import app.firka.naplo.getStringOrNull
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
import java.time.temporal.ChronoField
|
||||
|
||||
class WidgetLesson(data: JSONObject) {
|
||||
val formatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
|
||||
.optionalStart()
|
||||
.appendLiteral('Z')
|
||||
.optionalEnd()
|
||||
.toFormatter()
|
||||
companion object {
|
||||
private val formatter: DateTimeFormatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
|
||||
.optionalStart()
|
||||
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
|
||||
.optionalEnd()
|
||||
.optionalStart()
|
||||
.appendLiteral('Z')
|
||||
.optionalEnd()
|
||||
.optionalStart()
|
||||
.appendOffset("+HH:MM", "+00:00")
|
||||
.optionalEnd()
|
||||
.toFormatter()
|
||||
|
||||
val name: String = data.getString("Nev")
|
||||
val start: LocalDateTime = LocalDateTime.parse(data.getString("KezdetIdopont"), formatter)
|
||||
val end: LocalDateTime = LocalDateTime.parse(data.getString("VegIdopont"), formatter)
|
||||
val lessonNumber: Int? = data.getIntOrNull("Oraszam")
|
||||
val roomName: String? = data.getStringOrNull("TeremNeve")
|
||||
val substituteTeacher: String? = data.getStringOrNull("HelyettesTanarNeve")
|
||||
fun parseDateTime(raw: String): LocalDateTime {
|
||||
return try {
|
||||
LocalDateTime.parse(raw, formatter)
|
||||
} catch (_: Exception) {
|
||||
try {
|
||||
OffsetDateTime.parse(raw).toLocalDateTime()
|
||||
} catch (_: Exception) {
|
||||
LocalDateTime.parse(raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val name: String = data.optString("name", data.optString("Nev", ""))
|
||||
val start: LocalDateTime = parseDateTime(data.optString("start", data.optString("KezdetIdopont", "")))
|
||||
val end: LocalDateTime = parseDateTime(data.optString("end", data.optString("VegIdopont", "")))
|
||||
val lessonNumber: Int? = data.getIntOrNull("dailyNth") ?: data.getIntOrNull("Oraszam")
|
||||
val roomName: String? = data.getStringOrNull("roomName") ?: data.getStringOrNull("TeremNeve")
|
||||
val substituteTeacher: String? = data.getStringOrNull("substituteTeacher") ?: data.getStringOrNull("HelyettesTanarNeve")
|
||||
}
|
||||
|
||||
173
firka/integration_test/widget_e2e_test.dart
Normal file
173
firka/integration_test/widget_e2e_test.dart
Normal file
@@ -0,0 +1,173 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/services/notification_diff_service.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
Future<TokenGrantResponse> _authenticateMockServer(HttpClient httpClient) async {
|
||||
final loginReq = await httpClient.getUrl(Uri.parse('$_mockServerUrl/Account/Login'));
|
||||
final loginResp = await loginReq.close();
|
||||
final loginBody = await loginResp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody);
|
||||
if (match == null) {
|
||||
throw Exception('Failed to extract code from mock server login: $loginBody');
|
||||
}
|
||||
final code = match.group(1)!;
|
||||
|
||||
final tokenReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/connect/token'));
|
||||
tokenReq.headers.contentType = ContentType('application', 'x-www-form-urlencoded');
|
||||
tokenReq.write('grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}');
|
||||
final tokenResp = await tokenReq.close();
|
||||
final tokenBody = await tokenResp.transform(utf8.decoder).join();
|
||||
if (tokenResp.statusCode != 200) {
|
||||
throw Exception('Token request failed (${tokenResp.statusCode}): $tokenBody');
|
||||
}
|
||||
return TokenGrantResponse.fromJson(jsonDecode(tokenBody) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _getMockLessons(HttpClient httpClient) async {
|
||||
final req = await httpClient.getUrl(Uri.parse('$_mockServerUrl/admin/api/lessons'));
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
final list = jsonDecode(body) as List;
|
||||
return list.cast<Map<String, dynamic>>();
|
||||
}
|
||||
|
||||
Future<void> _putMockLessons(HttpClient httpClient, List<Map<String, dynamic>> lessons) async {
|
||||
final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl/admin/api/lessons'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(lessons));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 204 && resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to update mock lessons (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
logger = Logger("FirkaTest");
|
||||
dio.options.connectTimeout = const Duration(seconds: 5);
|
||||
dio.options.receiveTimeout = const Duration(seconds: 3);
|
||||
dio.options.validateStatus = (status) => status != null && status < 500;
|
||||
|
||||
group('Widget End-to-End Test with Mock Kreta Server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
httpClient = HttpClient();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Opening app updates widget with timetable and FCM wakeup syncs timetable changes', (tester) async {
|
||||
// 1. Initialize DB and authenticate with mock_kreta_server
|
||||
final isar = await initDB();
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
// Configure mock backend settings and enable notifications
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
await Settings.notifyAll.set(true);
|
||||
|
||||
final originalLessons = await _getMockLessons(httpClient);
|
||||
final today = DateTime.now();
|
||||
final seededLessons = originalLessons.indexed.map((entry) {
|
||||
final (i, l) = entry;
|
||||
final m = Map<String, dynamic>.from(l);
|
||||
m['KezdetIdopont'] = DateTime(today.year, today.month, today.day, 8 + i, 0).toIso8601String();
|
||||
m['VegIdopont'] = DateTime(today.year, today.month, today.day, 8 + i, 45).toIso8601String();
|
||||
return m;
|
||||
}).toList();
|
||||
await _putMockLessons(httpClient, seededLessons);
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
// 2. Initialize app (simulates opening the app)
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
if (initData.client != null) {
|
||||
await initData.client!.init();
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
}
|
||||
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, 'widget_state.json'));
|
||||
|
||||
// Verify that widget_state.json was created on app opening
|
||||
expect(widgetFile.existsSync(), isTrue, reason: 'widget_state.json must exist after opening app');
|
||||
|
||||
final initialContent = jsonDecode(widgetFile.readAsStringSync()) as Map<String, dynamic>;
|
||||
expect(initialContent.containsKey('colors'), isTrue);
|
||||
expect(initialContent.containsKey('timetable'), isTrue);
|
||||
|
||||
final initialTimetable = (initialContent['timetable'] as List).cast<Map<String, dynamic>>();
|
||||
expect(initialTimetable.isNotEmpty, isTrue, reason: 'Timetable in widget must not be empty');
|
||||
|
||||
final firstLessonName = initialTimetable.first['name'];
|
||||
expect(firstLessonName, isNotNull);
|
||||
expect(initialTimetable.first.containsKey('dailyNth'), isTrue);
|
||||
expect(initialTimetable.first.containsKey('start'), isTrue);
|
||||
expect(initialTimetable.first.containsKey('end'), isTrue);
|
||||
|
||||
// 3. Simulate timetable change on mock server
|
||||
final currentMockLessons = await _getMockLessons(httpClient);
|
||||
expect(currentMockLessons.isNotEmpty, isTrue);
|
||||
|
||||
// Mutate the target lesson: change room and assign a substitute teacher
|
||||
final modifiedLessons = List<Map<String, dynamic>>.from(currentMockLessons);
|
||||
final targetIndex = modifiedLessons.indexWhere((l) => l['Nev'] == firstLessonName);
|
||||
expect(targetIndex != -1, isTrue);
|
||||
final updatedLesson = Map<String, dynamic>.from(modifiedLessons[targetIndex]);
|
||||
updatedLesson['TeremNeve'] = 'LAB-999';
|
||||
updatedLesson['HelyettesTanarNeve'] = 'Prof. E2E Teszt';
|
||||
modifiedLessons[targetIndex] = updatedLesson;
|
||||
|
||||
await _putMockLessons(httpClient, modifiedLessons);
|
||||
|
||||
// 4. Trigger FCM wakeup processing
|
||||
await NotificationDiffService.checkAll();
|
||||
|
||||
// 5. Verify widget_state.json was updated with modified timetable
|
||||
final updatedContent = jsonDecode(widgetFile.readAsStringSync()) as Map<String, dynamic>;
|
||||
final updatedTimetable = (updatedContent['timetable'] as List).cast<Map<String, dynamic>>();
|
||||
|
||||
final updatedMatch = updatedTimetable.firstWhere(
|
||||
(l) => l['name'] == firstLessonName,
|
||||
orElse: () => <String, dynamic>{},
|
||||
);
|
||||
expect(updatedMatch.isNotEmpty, isTrue);
|
||||
expect(updatedMatch['roomName'], equals('LAB-999'), reason: 'Widget state should have updated room name');
|
||||
expect(updatedMatch['substituteTeacher'], equals('Prof. E2E Teszt'), reason: 'Widget state should have updated substitute teacher');
|
||||
|
||||
// Revert mock server lessons back to original
|
||||
await _putMockLessons(httpClient, originalLessons);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -9,6 +9,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/fcm_service.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/core/settings/settings_effects.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
@@ -168,6 +169,9 @@ Future<void> _initData(AppInitialization init) async {
|
||||
// onUserLogin() itself no-ops if notifyAll is off or permission is denied.
|
||||
unawaited(FcmService.onUserLogin(client: init.client!));
|
||||
|
||||
// Immediately refresh widget state from cached Isar lessons so widget is up to date
|
||||
unawaited(WidgetCacheHelper.updateWidgetCacheFromIsar());
|
||||
|
||||
// Don't block first paint on the network: render whatever is already
|
||||
// cached, then stream in student/timetable/grades/etc. as they arrive.
|
||||
unawaited(() async {
|
||||
@@ -182,6 +186,7 @@ Future<void> _initData(AppInitialization init) async {
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
|
||||
await init.client!.renewCache(reInit: false);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
}());
|
||||
|
||||
|
||||
@@ -2,7 +2,12 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -11,13 +16,39 @@ import 'package:path_provider/path_provider.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class WidgetCacheHelper {
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle style,
|
||||
List<LessonCacheModel> timetable,
|
||||
) {
|
||||
List<Map<String, dynamic>> timetableJson = [];
|
||||
static Map<String, dynamic> lessonToJson(LessonCacheModel lesson) {
|
||||
return {
|
||||
'name': lesson.name,
|
||||
'start': lesson.start.toIso8601String(),
|
||||
'end': lesson.end.toIso8601String(),
|
||||
'dailyNth': lesson.dailyNth,
|
||||
'yearlyNth': lesson.yearlyNth,
|
||||
'roomName': lesson.roomName,
|
||||
'substituteTeacher': lesson.substituteTeacher,
|
||||
'teacher': lesson.teacher,
|
||||
'topic': lesson.topic,
|
||||
'state': lesson.state,
|
||||
'type': lesson.type,
|
||||
// Backward-compatibility aliases for legacy receivers
|
||||
'Nev': lesson.name,
|
||||
'KezdetIdopont': lesson.start.toIso8601String(),
|
||||
'VegIdopont': lesson.end.toIso8601String(),
|
||||
'Oraszam': lesson.dailyNth,
|
||||
'TeremNeve': lesson.roomName,
|
||||
'HelyettesTanarNeve': lesson.substituteTeacher,
|
||||
};
|
||||
}
|
||||
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle? style,
|
||||
List<LessonCacheModel> timetable, {
|
||||
Map<String, dynamic>? existingColors,
|
||||
}) {
|
||||
final timetableJson = timetable.map(lessonToJson).toList();
|
||||
final colors = style != null
|
||||
? _colorsMap(style)
|
||||
: (existingColors ?? _defaultColors());
|
||||
return {'colors': colors, 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> toAndroidWidgetJson(
|
||||
@@ -27,6 +58,12 @@ class WidgetCacheHelper {
|
||||
final timetableJson = <Map<String, dynamic>>[];
|
||||
for (var lesson in timetable) {
|
||||
timetableJson.add({
|
||||
'name': lesson.name,
|
||||
'start': lesson.start.toUtc().toIso8601String(),
|
||||
'end': lesson.end.toUtc().toIso8601String(),
|
||||
'dailyNth': lesson.lessonNumber,
|
||||
'roomName': lesson.roomName,
|
||||
'substituteTeacher': lesson.substituteTeacher,
|
||||
'Nev': lesson.name,
|
||||
'KezdetIdopont': lesson.start.toUtc().toIso8601String(),
|
||||
'VegIdopont': lesson.end.toUtc().toIso8601String(),
|
||||
@@ -38,6 +75,38 @@ class WidgetCacheHelper {
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _defaultColors() {
|
||||
return {
|
||||
'background': 0xFFFAFFF0,
|
||||
'backgroundAmoled': 0xFF000000,
|
||||
'background0p': 0x00000000,
|
||||
'success': 0xFF2E7D32,
|
||||
'textPrimary': 0xFF1B1C18,
|
||||
'textSecondary': 0xFF45483D,
|
||||
'textTertiary': 0xFF76786B,
|
||||
'card': 0xFFEFF4E3,
|
||||
'cardTranslucent': 0xDDEFF4E3,
|
||||
'buttonSecondaryFill': 0xFFE0E5D4,
|
||||
'accent': 0xFF4C662B,
|
||||
'secondary': 0xFF586249,
|
||||
'shadowColor': 0x1A000000,
|
||||
'a15p': 0x264C662B,
|
||||
'warningAccent': 0xFFE65100,
|
||||
'warningText': 0xFFBF360C,
|
||||
'warning15p': 0x26E65100,
|
||||
'warningCard': 0xFFFFE0B2,
|
||||
'errorAccent': 0xFFBA1A1A,
|
||||
'errorText': 0xFFBA1A1A,
|
||||
'error15p': 0x26BA1A1A,
|
||||
'errorCard': 0xFFFFDAD6,
|
||||
'grade5': 0xFF4C662B,
|
||||
'grade4': 0xFF688837,
|
||||
'grade3': 0xFFE6A000,
|
||||
'grade2': 0xFFE66A00,
|
||||
'grade1': 0xFFBA1A1A,
|
||||
};
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _colorsMap(FirkaStyle style) {
|
||||
return {
|
||||
'background': style.colors.background.toARGB32(),
|
||||
@@ -70,23 +139,84 @@ class WidgetCacheHelper {
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> refreshWidget() async {
|
||||
if (!Platform.isAndroid) return;
|
||||
try {
|
||||
await HomeWidget.updateWidget(
|
||||
name: 'TimetableWidget',
|
||||
qualifiedAndroidName: 'app.firka.naplo.glance.TimetableWidgetReceiver',
|
||||
);
|
||||
try {
|
||||
const channel = MethodChannel("firka.app/main");
|
||||
await channel.invokeMethod<void>('refreshTimetableWidget');
|
||||
} catch (_) {}
|
||||
} catch (e) {
|
||||
debugPrint('Error refreshing timetable widget: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCacheFromLessons(
|
||||
List<LessonCacheModel> lessons, {
|
||||
FirkaStyle? style,
|
||||
String? displayDate,
|
||||
}) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
Map<String, dynamic>? existingColors;
|
||||
if (style == null && await widgetFile.exists()) {
|
||||
try {
|
||||
final content = jsonDecode(await widgetFile.readAsString());
|
||||
if (content is Map && content['colors'] is Map) {
|
||||
existingColors = Map<String, dynamic>.from(content['colors']);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final data = toJson(style, lessons, existingColors: existingColors);
|
||||
if (displayDate != null) {
|
||||
data['displayDate'] = displayDate;
|
||||
}
|
||||
|
||||
await widgetFile.writeAsString(jsonEncode(data));
|
||||
await refreshWidget();
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCacheFromIsar({
|
||||
FirkaStyle? style,
|
||||
String? displayDate,
|
||||
}) async {
|
||||
try {
|
||||
final now = timeNow();
|
||||
final start = now.subtract(const Duration(days: 7));
|
||||
final end = now.add(const Duration(days: 14));
|
||||
var lessons = await isarInit.lessonCacheModels
|
||||
.filter()
|
||||
.startBetween(start, end)
|
||||
.sortByStart()
|
||||
.findAll();
|
||||
if (lessons.isEmpty) {
|
||||
lessons = await isarInit.lessonCacheModels.where().sortByStart().findAll();
|
||||
}
|
||||
await updateWidgetCacheFromLessons(
|
||||
lessons,
|
||||
style: style,
|
||||
displayDate: displayDate,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Error updating widget cache from Isar: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> updateWidgetCache(
|
||||
FirkaStyle style,
|
||||
KretaClient client,
|
||||
) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
|
||||
final now = timeNow();
|
||||
|
||||
final start = now.subtract(Duration(days: 7));
|
||||
final end = now.add(Duration(days: 14));
|
||||
final start = now.subtract(const Duration(days: 7));
|
||||
final end = now.add(const Duration(days: 14));
|
||||
final lessons = await client.getLessons(start, end);
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons)),
|
||||
);
|
||||
await updateWidgetCacheFromLessons(lessons, style: style);
|
||||
}
|
||||
|
||||
static Future<void> generateWidgetStateForDate(
|
||||
@@ -94,13 +224,16 @@ class WidgetCacheHelper {
|
||||
FirkaStyle style,
|
||||
KretaClient client,
|
||||
) async {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
|
||||
final json = toJson(style, []);
|
||||
json['displayDate'] =
|
||||
final dayStart = DateTime(date.year, date.month, date.day);
|
||||
final dayEnd = dayStart.add(const Duration(hours: 23, minutes: 59));
|
||||
final lessons = await client.getLessons(dayStart, dayEnd);
|
||||
final displayDate =
|
||||
'${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
await widgetFile.writeAsString(jsonEncode(json));
|
||||
await updateWidgetCacheFromLessons(
|
||||
lessons,
|
||||
style: style,
|
||||
displayDate: displayDate,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/last_seen.dart';
|
||||
@@ -13,6 +16,7 @@ import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/core/last_seen_helper.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
import 'package:firka/core/settings/settings_schema.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/services/fcm_headless_bootstrap.dart';
|
||||
import 'package:firka/services/local_notification_service.dart';
|
||||
|
||||
@@ -96,10 +100,16 @@ class NotificationDiffService {
|
||||
);
|
||||
}
|
||||
|
||||
if (Settings.notifyLessons.value) {
|
||||
final now = DateTime.now();
|
||||
final lessons = await client.getLessons(now, now.add(const Duration(days: 7)));
|
||||
final now = DateTime.now();
|
||||
final lessons = await client.getLessons(now, now.add(const Duration(days: 7)));
|
||||
|
||||
final selectedToken = Settings.getSelectedToken();
|
||||
final isActiveAccount = selectedToken == null || selectedToken.key == accountKey;
|
||||
if (isActiveAccount) {
|
||||
await _checkAndUpdateWidget(lessons);
|
||||
}
|
||||
|
||||
if (Settings.notifyLessons.value) {
|
||||
final cancelled = lessons.where(_isCancelledLesson).toList();
|
||||
final substituted = lessons
|
||||
.where((l) => !_isCancelledLesson(l) && l.substituteTeacher != null)
|
||||
@@ -230,6 +240,45 @@ class NotificationDiffService {
|
||||
static int _notificationId(int accountKey, String kind) =>
|
||||
Object.hash(accountKey, kind) & 0x7fffffff;
|
||||
|
||||
static Future<void> _checkAndUpdateWidget(List<LessonCacheModel> lessons) async {
|
||||
try {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
if (_hasTimetableChanged(lessons, widgetFile)) {
|
||||
_logger.info('Timetable changed during FCM sync, updating widget');
|
||||
await WidgetCacheHelper.updateWidgetCacheFromLessons(lessons);
|
||||
}
|
||||
} catch (e, st) {
|
||||
_logger.warning('Failed to update widget during FCM sync: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static bool _hasTimetableChanged(List<LessonCacheModel> lessons, File widgetFile) {
|
||||
if (!widgetFile.existsSync()) return true;
|
||||
try {
|
||||
final content = jsonDecode(widgetFile.readAsStringSync());
|
||||
final cachedTt = content['timetable'] as List?;
|
||||
if (cachedTt == null) return true;
|
||||
if (cachedTt.length != lessons.length) return true;
|
||||
for (int i = 0; i < lessons.length; i++) {
|
||||
final l = lessons[i];
|
||||
final c = cachedTt[i] as Map?;
|
||||
if (c == null) return true;
|
||||
if (c['name'] != l.name ||
|
||||
c['start'] != l.start.toIso8601String() ||
|
||||
c['end'] != l.end.toIso8601String() ||
|
||||
c['dailyNth'] != l.dailyNth ||
|
||||
c['roomName'] != l.roomName ||
|
||||
c['substituteTeacher'] != l.substituteTeacher) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (_) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches the "isCancelled" convention already used across the app's
|
||||
/// live-activity/widget code (state names aren't a stable enum, just a
|
||||
/// Kréta-provided label; "elmarad" is the substring that consistently
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
|
||||
import 'package:firka/core/bloc/profile_picture_cubit.dart';
|
||||
import 'package:firka/core/bloc/settings_cubit.dart';
|
||||
@@ -67,10 +67,7 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
await initData.client!.renewCache(reInit: true);
|
||||
|
||||
if (Platform.isAndroid) {
|
||||
await HomeWidget.updateWidget(
|
||||
qualifiedAndroidName:
|
||||
"app.firka.naplo.glance.TimetableWidgetReceiver",
|
||||
);
|
||||
await WidgetCacheHelper.updateWidgetCacheFromIsar();
|
||||
}
|
||||
} catch (e) {
|
||||
if (_disposed) return;
|
||||
|
||||
134
firka/test/data/widget_test.dart
Normal file
134
firka/test/data/widget_test.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('WidgetCacheHelper serialization', () {
|
||||
test('serializes LessonCacheModel fields without custom DTO', () {
|
||||
final start = DateTime(2026, 9, 8, 8, 0);
|
||||
final end = DateTime(2026, 9, 8, 8, 45);
|
||||
|
||||
final lesson = LessonCacheModel()
|
||||
..name = 'Matematika'
|
||||
..start = start
|
||||
..end = end
|
||||
..dailyNth = 1
|
||||
..yearlyNth = 12
|
||||
..roomName = '101'
|
||||
..teacher = 'Kovács Péter'
|
||||
..substituteTeacher = 'Nagy Anna'
|
||||
..topic = 'Trigonometria'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final json = WidgetCacheHelper.lessonToJson(lesson);
|
||||
|
||||
// Check standard LessonCacheModel properties
|
||||
expect(json['name'], equals('Matematika'));
|
||||
expect(json['start'], equals(start.toIso8601String()));
|
||||
expect(json['end'], equals(end.toIso8601String()));
|
||||
expect(json['dailyNth'], equals(1));
|
||||
expect(json['yearlyNth'], equals(12));
|
||||
expect(json['roomName'], equals('101'));
|
||||
expect(json['teacher'], equals('Kovács Péter'));
|
||||
expect(json['substituteTeacher'], equals('Nagy Anna'));
|
||||
expect(json['topic'], equals('Trigonometria'));
|
||||
expect(json['state'], equals('Megtartott óra'));
|
||||
expect(json['type'], equals('Tanóra'));
|
||||
|
||||
// Check backward compatibility aliases
|
||||
expect(json['Nev'], equals('Matematika'));
|
||||
expect(json['KezdetIdopont'], equals(start.toIso8601String()));
|
||||
expect(json['VegIdopont'], equals(end.toIso8601String()));
|
||||
expect(json['Oraszam'], equals(1));
|
||||
expect(json['TeremNeve'], equals('101'));
|
||||
expect(json['HelyettesTanarNeve'], equals('Nagy Anna'));
|
||||
});
|
||||
|
||||
test('toJson generates complete widget state with colors and timetable', () {
|
||||
final start = DateTime(2026, 9, 8, 8, 55);
|
||||
final end = DateTime(2026, 9, 8, 9, 40);
|
||||
|
||||
final lesson = LessonCacheModel()
|
||||
..name = 'Történelem'
|
||||
..start = start
|
||||
..end = end
|
||||
..dailyNth = 2
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final result = WidgetCacheHelper.toJson(null, [lesson]);
|
||||
|
||||
expect(result.containsKey('colors'), isTrue);
|
||||
expect(result.containsKey('timetable'), isTrue);
|
||||
expect(result['timetable'], hasLength(1));
|
||||
|
||||
final first = (result['timetable'] as List).first as Map<String, dynamic>;
|
||||
expect(first['name'], equals('Történelem'));
|
||||
expect(first['dailyNth'], equals(2));
|
||||
});
|
||||
|
||||
test('toJson preserves existing colors in headless mode when style is null', () {
|
||||
final customColors = <String, dynamic>{
|
||||
'background': 0xFF123456,
|
||||
'card': 0xFF654321,
|
||||
};
|
||||
|
||||
final result = WidgetCacheHelper.toJson(
|
||||
null,
|
||||
[],
|
||||
existingColors: customColors,
|
||||
);
|
||||
|
||||
expect(result['colors']['background'], equals(0xFF123456));
|
||||
expect(result['colors']['card'], equals(0xFF654321));
|
||||
expect(result['timetable'], isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('Timetable change detection for FCM wakeups', () {
|
||||
test('detects change when timetable content differs', () {
|
||||
final tempDir = Directory.systemTemp.createTempSync('widget_test_');
|
||||
final widgetFile = File('${tempDir.path}/widget_state.json');
|
||||
|
||||
final start1 = DateTime(2026, 9, 8, 8, 0);
|
||||
final end1 = DateTime(2026, 9, 8, 8, 45);
|
||||
|
||||
final oldLesson = LessonCacheModel()
|
||||
..name = 'Angol'
|
||||
..start = start1
|
||||
..end = end1
|
||||
..dailyNth = 1
|
||||
..roomName = '102'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
final initialData = WidgetCacheHelper.toJson(null, [oldLesson]);
|
||||
widgetFile.writeAsStringSync(jsonEncode(initialData));
|
||||
|
||||
// Same lesson: no change
|
||||
final readJson = jsonDecode(widgetFile.readAsStringSync());
|
||||
final tt = readJson['timetable'] as List;
|
||||
expect(tt[0]['name'], equals(oldLesson.name));
|
||||
expect(tt[0]['roomName'], equals(oldLesson.roomName));
|
||||
|
||||
// Substitute teacher assigned: changed!
|
||||
final updatedLesson = LessonCacheModel()
|
||||
..name = 'Angol'
|
||||
..start = start1
|
||||
..end = end1
|
||||
..dailyNth = 1
|
||||
..roomName = '102'
|
||||
..substituteTeacher = 'Kiss Éva'
|
||||
..state = 'Megtartott óra'
|
||||
..type = 'Tanóra';
|
||||
|
||||
expect(tt[0]['substituteTeacher'], isNot(equals(updatedLesson.substituteTeacher)));
|
||||
|
||||
tempDir.deleteSync(recursive: true);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -18,6 +18,9 @@ import 'package:path_provider/path_provider.dart';
|
||||
late Isar isarInit;
|
||||
|
||||
Future<Isar> initDB() async {
|
||||
if (Isar.getInstance() != null) {
|
||||
return isarInit = Isar.getInstance()!;
|
||||
}
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
|
||||
isarInit = await Isar.open(
|
||||
|
||||
Reference in New Issue
Block a user