Compare commits
4 Commits
cleanup/re
...
fix/widget
| Author | SHA1 | Date | |
|---|---|---|---|
| 0f0b7c0c8b | |||
| 394b7bfd70 | |||
| 95b6af52c2 | |||
| fcf6a08e79 |
@@ -28,6 +28,7 @@ steps:
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- flutter pub get
|
||||
|
||||
- name: codegen
|
||||
@@ -37,6 +38,76 @@ steps:
|
||||
- cd firka
|
||||
- dart run scripts/codegen.dart
|
||||
|
||||
- name: clone-mock-kreta-server
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
environment:
|
||||
GITEA_USERNAME:
|
||||
from_secret: gitea_username
|
||||
GITEA_TOKEN:
|
||||
from_secret: gitea_token
|
||||
commands:
|
||||
- pwd
|
||||
# The heredoc uses a quoted delimiter so $GITEA_USERNAME/$GITEA_TOKEN
|
||||
# are written to the script literally, not expanded here -- keeps the
|
||||
# secret values out of this (traced) command's expanded output.
|
||||
- |
|
||||
cat > /tmp/write_netrc.sh <<'NETRC_SCRIPT'
|
||||
printf 'machine git.firka.app\nlogin %s\npassword %s\n' "$GITEA_USERNAME" "$GITEA_TOKEN" > "$HOME/.netrc"
|
||||
chmod 600 "$HOME/.netrc"
|
||||
NETRC_SCRIPT
|
||||
# Runs as an untraced child shell, so the expansion above never hits the log.
|
||||
- sh /tmp/write_netrc.sh
|
||||
- git clone --depth 1 https://git.firka.app/firka/mock_kreta_server.git mock_kreta_server
|
||||
- rm -f /tmp/write_netrc.sh "$HOME/.netrc"
|
||||
|
||||
- name: build-mock-kreta-server
|
||||
image: golang:1.26
|
||||
commands:
|
||||
- cd mock_kreta_server
|
||||
- go build -o ../mock_kreta_server_bin .
|
||||
|
||||
# Runs the mock server in the background and exercises kreta_api's DTOs
|
||||
# against its real wire format, catching drift between the two repos.
|
||||
- name: kreta-api-mock-server-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- cd kreta_api
|
||||
- dart pub get
|
||||
- MOCK_KRETA_SERVER_URL=http://127.0.0.1:8090 dart test
|
||||
|
||||
- name: firka-e2e-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- cp $(find "$PUB_CACHE" -name libisar.so | grep linux | head -n 1) libisar.so 2>/dev/null || true
|
||||
- flutter test test/data/widget_test.dart test/e2e/screenshot_widget_test.dart test/e2e/notification_diff_test.dart
|
||||
|
||||
- name: firka-integration-tests
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
privileged: true
|
||||
volumes:
|
||||
- /dev/kvm:/dev/kvm
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- 'grep -q "::1" /etc/hosts || echo "::1 localhost ip6-localhost ip6-loopback" >> /etc/hosts 2>/dev/null || true'
|
||||
- sysctl -w net.ipv6.conf.all.disable_ipv6=0 2>/dev/null || true
|
||||
- sed -i 's/TIMEOUT=60/TIMEOUT=300/' /opt/bin/start-emulator.sh
|
||||
- sed -i 's/-snapshot default_boot/-no-snapshot-load/' /opt/bin/start-emulator.sh
|
||||
- ./mock_kreta_server_bin -addr :8090 -data mock_kreta_server/data.json &
|
||||
- sleep 1
|
||||
- /opt/bin/start-emulator.sh
|
||||
- adb reverse tcp:8090 tcp:8090
|
||||
- cd firka
|
||||
- '[ -f .env ] || cp .env.example .env 2>/dev/null || touch .env'
|
||||
- flutter test integration_test/widget_e2e_test.dart
|
||||
|
||||
- name: build-release
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
|
||||
3
firka/.gitignore
vendored
3
firka/.gitignore
vendored
@@ -52,4 +52,5 @@ app.*.map.json
|
||||
coverage
|
||||
|
||||
# Generated files
|
||||
*.g.dart
|
||||
*.g.dart
|
||||
libisar.so
|
||||
@@ -7,6 +7,10 @@
|
||||
|
||||
# The following line activates a set of recommended lints for Flutter apps,
|
||||
# packages, and plugins designed to encourage good coding practices.
|
||||
analyzer:
|
||||
exclude:
|
||||
- build/**
|
||||
- android/**
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
|
||||
@@ -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();
|
||||
}());
|
||||
|
||||
@@ -239,6 +244,7 @@ Future<void> initializeApp() async {
|
||||
);
|
||||
initData.settings.cubit = initData.settingsCubit;
|
||||
Settings = initData.settings;
|
||||
await Settings.loadAll();
|
||||
registerSettingsEffects(initData.settings, initData);
|
||||
|
||||
try {
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ class LocalNotificationService {
|
||||
FlutterLocalNotificationsPlugin();
|
||||
static bool _initialized = false;
|
||||
|
||||
static final List<({int id, String title, String body})> postedNotifications = [];
|
||||
|
||||
static Future<void> init() async {
|
||||
if (_initialized) return;
|
||||
|
||||
@@ -38,6 +40,12 @@ class LocalNotificationService {
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/// Returns active notifications currently shown in the system status bar (Android 6.0+).
|
||||
static Future<List<ActiveNotification>> getActiveNotifications() async {
|
||||
await init();
|
||||
return await _plugin.getActiveNotifications();
|
||||
}
|
||||
|
||||
/// Shows a single notification. [id] should be stable per logical
|
||||
/// notification (e.g. derived from account key + category) so a repeat
|
||||
/// wakeup that finds the same new items updates rather than duplicates it.
|
||||
@@ -46,6 +54,8 @@ class LocalNotificationService {
|
||||
required String title,
|
||||
required String body,
|
||||
}) async {
|
||||
postedNotifications.add((id: id, title: title, body: body));
|
||||
|
||||
await init();
|
||||
await _plugin.show(
|
||||
id,
|
||||
|
||||
@@ -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)
|
||||
@@ -198,6 +208,12 @@ class NotificationDiffService {
|
||||
body: body(newItems),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// First run: seed baseline silently without spamming backlog.
|
||||
// If there are no items yet, record current time so subsequent items notify.
|
||||
final baseline = LastSeen.newestOf(items) ?? LastSeen(DateTime.now(), 0);
|
||||
await LastSeenHelper.set(accountKey, kind, baseline);
|
||||
return;
|
||||
}
|
||||
|
||||
final newest = LastSeen.newestOf(items);
|
||||
@@ -230,6 +246,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;
|
||||
|
||||
@@ -9,7 +9,7 @@ const _lockFileName = 'codegen-lock.yaml';
|
||||
|
||||
void main() async {
|
||||
final root = _projectRoot();
|
||||
print(root);
|
||||
stdout.writeln(root);
|
||||
var ran = false;
|
||||
|
||||
if (_iconsOutOfDate(root)) {
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
318
firka/test/e2e/notification_diff_test.dart
Normal file
318
firka/test/e2e/notification_diff_test.dart
Normal file
@@ -0,0 +1,318 @@
|
||||
// ignore_for_file: depend_on_referenced_packages
|
||||
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/services/local_notification_service.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/services.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
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<void> _postItem(HttpClient httpClient, String endpoint, Map<String, dynamic> item) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl$endpoint'));
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(item));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200 && resp.statusCode != 204) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('POST $endpoint failed (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
Future<bool?> initialize(
|
||||
InitializationSettings initializationSettings, {
|
||||
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
|
||||
void Function(NotificationResponse)? onDidReceiveBackgroundNotificationResponse,
|
||||
}) async => true;
|
||||
|
||||
@override
|
||||
Future<void> show(
|
||||
int id,
|
||||
String? title,
|
||||
String? body, {
|
||||
NotificationDetails? notificationDetails,
|
||||
String? payload,
|
||||
}) async {}
|
||||
|
||||
@override
|
||||
Future<List<ActiveNotification>> getActiveNotifications() async => [];
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform();
|
||||
logger = Logger("NotificationDiffTest");
|
||||
|
||||
group('Notification System End-to-End Test with Mock Kreta Server', () {
|
||||
late HttpClient httpClient;
|
||||
|
||||
setUp(() {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(MethodCall methodCall) async => Directory.systemTemp.path,
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('dev.fluttercommunity.plus/package_info'),
|
||||
(MethodCall methodCall) async => {
|
||||
'appName': 'firka',
|
||||
'packageName': 'app.firka.naplo',
|
||||
'version': '1.0.0',
|
||||
'buildNumber': '1',
|
||||
},
|
||||
);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('firka.app/main'),
|
||||
(MethodCall methodCall) async => 'SM-A705FN;11;30',
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Synthetic FCM wakeup diffs changes correctly and posts notifications', (tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await _seedMockLessonsToday(httpClient);
|
||||
|
||||
final isar = await initDB();
|
||||
await isar.writeTxn(() async {
|
||||
await isar.clear();
|
||||
});
|
||||
Settings = SettingsRepository(isar);
|
||||
await Settings.loadAll();
|
||||
|
||||
await Settings.mockBackendEnabled.set(true);
|
||||
await Settings.mockBackendUrl.set(_mockServerUrl);
|
||||
await Settings.notifyAll.set(true);
|
||||
await Settings.notifyGrades.set(true);
|
||||
await Settings.notifyHomeworkTests.set(true);
|
||||
await Settings.notifyLessons.set(true);
|
||||
await Settings.notifyAbsences.set(true);
|
||||
await Settings.notifyMessages.set(true);
|
||||
await Settings.notifyMutedSubjects.set('[]');
|
||||
|
||||
final tokenResp = await _authenticateMockServer(httpClient);
|
||||
final tokenModel = TokenModel.fromResp(tokenResp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.clear();
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
await initializeApp();
|
||||
expect(initDone, isTrue);
|
||||
|
||||
if (initData.client != null) {
|
||||
await initData.client!.init();
|
||||
await initData.client!.renewCache(reInit: false);
|
||||
}
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isEmpty);
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
final newGradeUid = 'test-grade-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final newGradeTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/grades', {
|
||||
'Uid': newGradeUid,
|
||||
'RogzitesDatuma': newGradeTime,
|
||||
'KeszitesDatuma': newGradeTime,
|
||||
'Tantargy': {
|
||||
'Uid': '10,INF',
|
||||
'Nev': 'Informatika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 10,
|
||||
},
|
||||
'Tema': 'Algoritmusok',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Gyakorlati feladat'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Turing Alan',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final gradeNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('jegy'),
|
||||
);
|
||||
expect(gradeNotif.title, contains('jegy'));
|
||||
expect(gradeNotif.body, contains('Informatika'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
final newHwUid = 'test-hw-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final newHwTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/homework', {
|
||||
'Uid': newHwUid,
|
||||
'Tantargy': {
|
||||
'Uid': '11,BIO',
|
||||
'Nev': 'Biológia',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 11,
|
||||
},
|
||||
'TantargyNeve': 'Biológia',
|
||||
'RogzitoTanarNeve': 'Darwin Károly',
|
||||
'Szoveg': 'Olvassátok el a sejtbiológia fejezetet.',
|
||||
'FeladasDatuma': newHwTime,
|
||||
'HataridoDatuma': DateTime.now().add(const Duration(days: 3)).toUtc().toIso8601String(),
|
||||
'RogzitesIdopontja': newHwTime,
|
||||
'IsTanarRogzitette': true,
|
||||
'IsMegoldva': false,
|
||||
'IsBeadhato': false,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final hwNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('házi feladat'),
|
||||
);
|
||||
expect(hwNotif.title, contains('házi feladat'));
|
||||
expect(hwNotif.body, contains('Biológia'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await _postItem(httpClient, '/admin/api/timetable/mutate', {
|
||||
'Uid': '5000',
|
||||
'Nev': 'Matematika',
|
||||
'HelyettesTanarNeve': 'Prof. Helyettes',
|
||||
'Allapot': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Megtartott',
|
||||
'Leiras': 'Megtartott óra',
|
||||
},
|
||||
'Tipus': {
|
||||
'Uid': '1',
|
||||
'Nev': 'Tanóra',
|
||||
'Leiras': 'Tanóra',
|
||||
},
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final subNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('Helyettesítés'),
|
||||
);
|
||||
expect(subNotif.title, equals('Helyettesítés'));
|
||||
expect(subNotif.body, contains('Prof. Helyettes'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await _postItem(httpClient, '/admin/api/timetable/mutate', {
|
||||
'Uid': '5000',
|
||||
'Nev': 'Matematika',
|
||||
'Allapot': {
|
||||
'Uid': '3',
|
||||
'Nev': 'Elmaradt',
|
||||
'Leiras': 'Elmaradt óra',
|
||||
},
|
||||
'Tipus': {
|
||||
'Uid': 'UresOra',
|
||||
'Nev': 'UresOra',
|
||||
'Leiras': 'Lyukasóra',
|
||||
},
|
||||
'UtolsoModositas': DateTime.now().toUtc().toIso8601String(),
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
expect(LocalNotificationService.postedNotifications, isNotEmpty);
|
||||
final cancelNotif = LocalNotificationService.postedNotifications.firstWhere(
|
||||
(n) => n.title.contains('Elmaradt óra'),
|
||||
);
|
||||
expect(cancelNotif.title, equals('Elmaradt óra'));
|
||||
|
||||
LocalNotificationService.postedNotifications.clear();
|
||||
await Settings.notifyMutedSubjects.set(jsonEncode(['Fizika']));
|
||||
|
||||
final mutedGradeUid = 'test-grade-muted-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final mutedGradeTime = DateTime.now().toUtc().toIso8601String();
|
||||
await _postItem(httpClient, '/admin/api/grades', {
|
||||
'Uid': mutedGradeUid,
|
||||
'RogzitesDatuma': mutedGradeTime,
|
||||
'KeszitesDatuma': mutedGradeTime,
|
||||
'Tantargy': {
|
||||
'Uid': '12,FIZ',
|
||||
'Nev': 'Fizika',
|
||||
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
|
||||
'SortIndex': 12,
|
||||
},
|
||||
'Tema': 'Mechanika',
|
||||
'Tipus': {'Uid': '1', 'Nev': 'Írásbeli'},
|
||||
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
|
||||
'ErtekeloTanarNeve': 'Newton Izsák',
|
||||
'Jelleg': 'Ertekeles',
|
||||
'SzamErtek': 5,
|
||||
'SzovegesErtek': 'Jeles',
|
||||
'SulySzazalekErteke': 100,
|
||||
'OsztalyCsoport': {'Uid': '10,11.A'},
|
||||
});
|
||||
|
||||
await NotificationDiffService.checkAll();
|
||||
|
||||
final fizikaNotifs = LocalNotificationService.postedNotifications
|
||||
.where((n) => n.body.contains('Fizika') || n.body.contains('Newton'))
|
||||
.toList();
|
||||
expect(fizikaNotifs, isEmpty);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
248
firka/test/e2e/screenshot_widget_test.dart
Normal file
248
firka/test/e2e/screenshot_widget_test.dart
Normal file
@@ -0,0 +1,248 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _mockServerUrl = 'http://127.0.0.1:8090';
|
||||
|
||||
class _RealHttpOverrides extends HttpOverrides {}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _getMockLessons(HttpClient httpClient) async {
|
||||
final req = await httpClient.getUrl(Uri.parse('$_mockServerUrl/admin/api/timetable'));
|
||||
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/timetable'));
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _seedMockLessonsToday(HttpClient httpClient) async {
|
||||
final req = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/today'));
|
||||
final resp = await req.close();
|
||||
if (resp.statusCode != 200) {
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
throw Exception('Failed to shift lessons to today (${resp.statusCode}): $body');
|
||||
}
|
||||
}
|
||||
|
||||
class TimetableWidgetView extends StatelessWidget {
|
||||
final GlobalKey boundaryKey;
|
||||
final List<Map<String, dynamic>> lessons;
|
||||
|
||||
const TimetableWidgetView({
|
||||
required this.boundaryKey,
|
||||
required this.lessons,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const bgColor = Color(0xFFFAFFF0);
|
||||
const cardColor = Color(0xFFEFF4E3);
|
||||
const textPrimary = Color(0xFF1B1C18);
|
||||
const textSecondary = Color(0xFF45483D);
|
||||
const warningColor = Color(0xFFE65100);
|
||||
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Center(
|
||||
child: RepaintBoundary(
|
||||
key: boundaryKey,
|
||||
child: Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Mai órarend',
|
||||
style: TextStyle(
|
||||
color: textSecondary,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
for (final lesson in lessons.take(4))
|
||||
Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: lesson['HelyettesTanarNeve'] != null &&
|
||||
(lesson['HelyettesTanarNeve'] as String).isNotEmpty
|
||||
? warningColor.withValues(alpha: 0.15)
|
||||
: cardColor,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'${lesson['Oraszam'] ?? 1}.',
|
||||
style: const TextStyle(
|
||||
color: textSecondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
lesson['Nev'] as String? ?? '',
|
||||
style: const TextStyle(
|
||||
color: textPrimary,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (lesson['HelyettesTanarNeve'] != null &&
|
||||
(lesson['HelyettesTanarNeve'] as String).isNotEmpty)
|
||||
Text(
|
||||
'Helyettes: ${lesson['HelyettesTanarNeve']}',
|
||||
style: const TextStyle(
|
||||
color: warningColor,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (lesson['TeremNeve'] != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: textSecondary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
lesson['TeremNeve'] as String,
|
||||
style: const TextStyle(
|
||||
color: textSecondary,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<int>> _capturePng(WidgetTester tester, GlobalKey key) async {
|
||||
return await tester.runAsync(() async {
|
||||
final boundary = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
|
||||
final image = await boundary.toImage(pixelRatio: 2.0);
|
||||
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
return byteData!.buffer.asUint8List().toList();
|
||||
}) ?? [];
|
||||
}
|
||||
|
||||
int _countDifferentBytes(List<int> a, List<int> b) {
|
||||
int diff = 0;
|
||||
final minLen = a.length < b.length ? a.length : b.length;
|
||||
for (int i = 0; i < minLen; i++) {
|
||||
if (a[i] != b[i]) diff++;
|
||||
}
|
||||
diff += (a.length - b.length).abs();
|
||||
return diff;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
group('Widget End-to-End Screenshot Comparison Test', () {
|
||||
late HttpClient httpClient;
|
||||
late List<Map<String, dynamic>> originalLessons;
|
||||
|
||||
setUp(() async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5);
|
||||
originalLessons = await _getMockLessons(httpClient);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
try {
|
||||
await _putMockLessons(httpClient, originalLessons);
|
||||
} catch (_) {}
|
||||
httpClient.close(force: true);
|
||||
});
|
||||
|
||||
testWidgets('Widget screenshots differ programmatically after mock server timetable mutation', (tester) async {
|
||||
HttpOverrides.global = _RealHttpOverrides();
|
||||
|
||||
late List<Map<String, dynamic>> lessonsBefore;
|
||||
await tester.runAsync(() async {
|
||||
await _seedMockLessonsToday(httpClient);
|
||||
lessonsBefore = await _getMockLessons(httpClient);
|
||||
});
|
||||
expect(lessonsBefore.isNotEmpty, isTrue);
|
||||
|
||||
final boundaryKey1 = GlobalKey();
|
||||
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey1, lessons: lessonsBefore));
|
||||
await tester.pump();
|
||||
|
||||
final screenshotBefore = await _capturePng(tester, boundaryKey1);
|
||||
expect(screenshotBefore, isNotEmpty);
|
||||
|
||||
late List<Map<String, dynamic>> lessonsAfter;
|
||||
final targetName = lessonsBefore.first['Nev'];
|
||||
await tester.runAsync(() async {
|
||||
final mutateReq = await httpClient.postUrl(Uri.parse('$_mockServerUrl/admin/api/timetable/mutate'));
|
||||
mutateReq.headers.contentType = ContentType.json;
|
||||
mutateReq.write(jsonEncode({
|
||||
'Uid': lessonsBefore.first['Uid'],
|
||||
'Nev': targetName,
|
||||
'TeremNeve': 'LAB-999',
|
||||
'HelyettesTanarNeve': 'Prof. E2E Teszt',
|
||||
}));
|
||||
final mutateResp = await mutateReq.close();
|
||||
expect(mutateResp.statusCode, equals(200));
|
||||
|
||||
lessonsAfter = await _getMockLessons(httpClient);
|
||||
});
|
||||
|
||||
final targetLesson = lessonsAfter.firstWhere((l) => l['Nev'] == targetName);
|
||||
expect(targetLesson['TeremNeve'], equals('LAB-999'));
|
||||
expect(targetLesson['HelyettesTanarNeve'], equals('Prof. E2E Teszt'));
|
||||
|
||||
final boundaryKey2 = GlobalKey();
|
||||
await tester.pumpWidget(TimetableWidgetView(boundaryKey: boundaryKey2, lessons: lessonsAfter));
|
||||
await tester.pump();
|
||||
|
||||
final screenshotAfter = await _capturePng(tester, boundaryKey2);
|
||||
expect(screenshotAfter, isNotEmpty);
|
||||
|
||||
expect(screenshotBefore, isNot(equals(screenshotAfter)));
|
||||
expect(_countDifferentBytes(screenshotBefore, screenshotAfter), greaterThan(0));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -50,6 +50,7 @@ class LessonCacheModel extends GenericCacheModel<Lesson> {
|
||||
..topic = ctx.data.theme
|
||||
..roomName = ctx.data.roomName
|
||||
..type = ctx.data.type.name
|
||||
..createdAt = ctx.data.lastModifiedAt
|
||||
..classGroup.init(ctx.cacheManager, ctx.data.classGroup)
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject);
|
||||
|
||||
|
||||
@@ -8,3 +8,6 @@ environment:
|
||||
|
||||
dependencies:
|
||||
intl: any
|
||||
|
||||
dev_dependencies:
|
||||
test: ^1.25.0
|
||||
|
||||
166
kreta_api/test/mock_kreta_server_test.dart
Normal file
166
kreta_api/test/mock_kreta_server_test.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
// Integration test that runs against a live mock_kreta_server instance
|
||||
// (git.firka.app/firka/mock_kreta_server) to catch drift between the wire
|
||||
// format it serves and the DTOs in this package. The server URL is provided
|
||||
// by CI via MOCK_KRETA_SERVER_URL; see .woodpecker.yml.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
final _serverUrl =
|
||||
Platform.environment['MOCK_KRETA_SERVER_URL'] ?? 'http://127.0.0.1:8090';
|
||||
|
||||
Future<String> _fetchLoginCode(HttpClient client) async {
|
||||
final req = await client.getUrl(Uri.parse('$_serverUrl/Account/Login'));
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
|
||||
final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(body);
|
||||
if (match == null) {
|
||||
fail('mock server login page did not contain a code: $body');
|
||||
}
|
||||
return match.group(1)!;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _postToken(
|
||||
HttpClient client,
|
||||
Map<String, String> form,
|
||||
) async {
|
||||
final req = await client.postUrl(Uri.parse('$_serverUrl/connect/token'));
|
||||
req.headers.contentType = ContentType(
|
||||
'application',
|
||||
'x-www-form-urlencoded',
|
||||
);
|
||||
req.write(
|
||||
form.entries
|
||||
.map(
|
||||
(e) =>
|
||||
'${Uri.encodeQueryComponent(e.key)}=${Uri.encodeQueryComponent(e.value)}',
|
||||
)
|
||||
.join('&'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
if (resp.statusCode != 200) {
|
||||
throw HttpException('token request failed (${resp.statusCode}): $body');
|
||||
}
|
||||
return jsonDecode(body) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<TokenGrantResponse> _authenticate(HttpClient client) async {
|
||||
final code = await _fetchLoginCode(client);
|
||||
final json = await _postToken(client, {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
});
|
||||
return TokenGrantResponse.fromJson(json);
|
||||
}
|
||||
|
||||
Future<dynamic> _getAuthed(
|
||||
HttpClient client,
|
||||
String path,
|
||||
String accessToken,
|
||||
) async {
|
||||
final req = await client.getUrl(Uri.parse('$_serverUrl$path'));
|
||||
req.headers.set('Authorization', 'Bearer $accessToken');
|
||||
final resp = await req.close();
|
||||
final body = await resp.transform(utf8.decoder).join();
|
||||
if (resp.statusCode != 200) {
|
||||
throw HttpException('$path failed (${resp.statusCode}): $body');
|
||||
}
|
||||
return jsonDecode(body);
|
||||
}
|
||||
|
||||
void main() {
|
||||
late HttpClient client;
|
||||
|
||||
setUp(() => client = HttpClient());
|
||||
tearDown(() => client.close(force: true));
|
||||
|
||||
group('mock_kreta_server', () {
|
||||
test('authorization_code grant returns a usable token', () async {
|
||||
final token = await _authenticate(client);
|
||||
|
||||
expect(token.accessToken, isNotEmpty);
|
||||
expect(token.refreshToken, isNotEmpty);
|
||||
expect(token.tokenType, 'Bearer');
|
||||
});
|
||||
|
||||
test('an authorization code can only be redeemed once', () async {
|
||||
final code = await _fetchLoginCode(client);
|
||||
await _postToken(client, {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
});
|
||||
|
||||
await expectLater(
|
||||
_postToken(client, {'grant_type': 'authorization_code', 'code': code}),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('refresh_token grant issues a new token and consumes the old one', () async {
|
||||
final first = await _authenticate(client);
|
||||
|
||||
final refreshed = TokenGrantResponse.fromJson(
|
||||
await _postToken(client, {
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': first.refreshToken,
|
||||
}),
|
||||
);
|
||||
expect(refreshed.accessToken, isNotEmpty);
|
||||
expect(refreshed.accessToken, isNot(first.accessToken));
|
||||
|
||||
await expectLater(
|
||||
_postToken(client, {
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': first.refreshToken,
|
||||
}),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('student profile matches the Student DTO contract', () async {
|
||||
final token = await _authenticate(client);
|
||||
final json = await _getAuthed(
|
||||
client,
|
||||
Uri.parse(KretaEndpoints.getStudent('dummy')).path,
|
||||
token.accessToken,
|
||||
);
|
||||
|
||||
final student = Student.fromJson(json as Map<String, dynamic>);
|
||||
expect(student.name, isNotEmpty);
|
||||
expect(student.uid, isNotEmpty);
|
||||
expect(student.instituteCode, isNotEmpty);
|
||||
});
|
||||
|
||||
test('class groups match the ClassGroup DTO contract', () async {
|
||||
final token = await _authenticate(client);
|
||||
final json = await _getAuthed(
|
||||
client,
|
||||
Uri.parse(KretaEndpoints.getClassGroups('dummy')).path,
|
||||
token.accessToken,
|
||||
);
|
||||
|
||||
final list = (json as List)
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map(ClassGroup.fromJson)
|
||||
.toList();
|
||||
expect(list, isNotEmpty);
|
||||
for (final group in list) {
|
||||
expect(group.uid, isNotEmpty);
|
||||
expect(group.name, isNotEmpty);
|
||||
}
|
||||
});
|
||||
|
||||
test('protected endpoints reject requests without a token', () async {
|
||||
final req = await client.getUrl(
|
||||
Uri.parse('$_serverUrl/ellenorzo/v3/sajat/TanuloAdatlap'),
|
||||
);
|
||||
final resp = await req.close();
|
||||
await resp.drain();
|
||||
expect(resp.statusCode, HttpStatus.unauthorized);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user