forked from firka/firka
ref: cache system rewrite
This commit is contained in:
48
cache.md
Normal file
48
cache.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Cache
|
||||
|
||||
Entry:
|
||||
|
||||
név|típus|
|
||||
-|-|
|
||||
latestElement|idő|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
|
||||
Legutóbbi = Legutóbbi sikeres adatlekérdezés listájának legfrissebb elemének ideje.
|
||||
|
||||
## Timetable
|
||||
|
||||
TimetableDay entry.
|
||||
|
||||
Frissíteni|Korábbi|Múlt hét|Jelenlegi hét|Jövő hét|Későbbi|
|
||||
-|-|-|-|-|-|
|
||||
belépéskor?|✖️|✖️|✔️|✔️|✖️|
|
||||
kijelzéskor?|✖️|✖️|✖️|✖️|✔️|
|
||||
|
||||
Új mulasztáskor a mulasztás napját MINDIG frissíti.
|
||||
|
||||
## Értékelések/Tesztek/Faliújság/Feljegyzések/Házi feladatok
|
||||
|
||||
Frissíteni|Korábbi|Legutóbbi létrehozástól|
|
||||
-|-|-|
|
||||
belépéskor?|✖️|✔️|
|
||||
kijelzéskor?|✖️|✖️|
|
||||
|
||||
## Mulasztások
|
||||
|
||||
Összes
|
||||
|
||||
## Egyéb
|
||||
|
||||
Belépéskor
|
||||
|
||||
--------
|
||||
# IMPL
|
||||
|
||||
### GenericCache
|
||||
Entry:
|
||||
név|típus|
|
||||
-|-|
|
||||
userId|id|
|
||||
createdAt|idő|
|
||||
response|Json|
|
||||
@@ -1,22 +1,34 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/data/models/generic_cache_model.dart';
|
||||
import 'package:firka/data/models/timetable_cache_model.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/data/cache_manager.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/util.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka/services/watch_sync_helper.dart';
|
||||
import '../consts.dart';
|
||||
import '../token_grant.dart';
|
||||
|
||||
import 'dart:io';
|
||||
@@ -30,15 +42,116 @@ const backoffMin = 100;
|
||||
const backoffStep = 500;
|
||||
|
||||
class KretaClient {
|
||||
Completer<void>? _tokenMutexCompleter;
|
||||
TokenModel model;
|
||||
Isar isar;
|
||||
Future<TokenModel>? _tokenMutexCompleter;
|
||||
final CacheManager cache;
|
||||
final ReauthCubit _reauthCubit;
|
||||
|
||||
KretaClient(this.model, this.isar, this._reauthCubit);
|
||||
KretaClient(TokenModel model, this._reauthCubit)
|
||||
: cache = CacheManager(model);
|
||||
|
||||
bool get needsReauth => _reauthCubit.state.needsReauth;
|
||||
|
||||
static int lessonStartToMins(LessonCacheModel lesson) {
|
||||
return Duration(
|
||||
hours: lesson.start.hour,
|
||||
minutes: lesson.start.minute,
|
||||
).inMinutes;
|
||||
}
|
||||
|
||||
Future<List<LessonCacheModel>> resolveDailyNth(
|
||||
List<LessonCacheModel> lessons,
|
||||
) async {
|
||||
HashSet<int> lessonsStarts = HashSet();
|
||||
lessonsStarts.addAll(
|
||||
lessons.where((l) => !l.isEvent()).map(lessonStartToMins),
|
||||
);
|
||||
|
||||
List<int> ordered = lessonsStarts.toList()..sort();
|
||||
int offset = ordered.indexOf(8 * 60);
|
||||
offset = offset == -1 ? 0 : -offset;
|
||||
HashMap<int, int> indexed = HashMap.fromEntries(
|
||||
ordered.indexed.map((k) => MapEntry(k.$2, k.$1 + 1 + offset)),
|
||||
);
|
||||
|
||||
for (LessonCacheModel l in lessons) {
|
||||
if (l.isEvent()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
l.dailyNth ??= indexed[lessonStartToMins(l)];
|
||||
}
|
||||
|
||||
return lessons;
|
||||
}
|
||||
|
||||
Future<void> renewTimetable() async {
|
||||
DateTime from =
|
||||
/*(await isarInit.lessonCacheModels
|
||||
.filter()
|
||||
.endLessThan(
|
||||
timeNow().getMidnight().getMonday().subtract(
|
||||
Duration(days: 7),
|
||||
),
|
||||
include: true,
|
||||
)
|
||||
.sortByEndDesc()
|
||||
.findFirst())
|
||||
?.end ??*/
|
||||
timeNow().getFirstSchoolDay();
|
||||
DateTime to = timeNow().getMonday().add(Duration(days: 14));
|
||||
DateTime date = from;
|
||||
List<Future> requests = [];
|
||||
int i = 0;
|
||||
int waitAfter = 5;
|
||||
while (date.isBefore(to)) {
|
||||
DateTime tmpTo = date.add(Duration(days: 14));
|
||||
requests.add(getLessons(date, tmpTo));
|
||||
date = tmpTo;
|
||||
|
||||
i++;
|
||||
if (waitAfter == i) {
|
||||
await Future.wait(requests);
|
||||
i = 0;
|
||||
}
|
||||
}
|
||||
await Future.wait(requests);
|
||||
}
|
||||
|
||||
Future<void> renewMessages() async {
|
||||
DateTime from =
|
||||
(await isarInit.messageCacheModels
|
||||
.where()
|
||||
.sortByCreatedAtDesc()
|
||||
.findFirst())
|
||||
?.createdAt ??
|
||||
timeNow().getFirstSchoolDay();
|
||||
await getInfoBoard(from: from);
|
||||
await getNoticeBoard(from: from);
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await getStudent();
|
||||
await getClassGroups();
|
||||
}
|
||||
|
||||
Future<void> renewCache({bool reInit = false}) async {
|
||||
if (reInit) {
|
||||
await init();
|
||||
}
|
||||
await Future.wait([
|
||||
getTests(),
|
||||
getHomework(),
|
||||
renewMessages(),
|
||||
getGrades(),
|
||||
]);
|
||||
await renewTimetable();
|
||||
|
||||
// manual link
|
||||
await getOmissions();
|
||||
|
||||
cache.resolveTeachers();
|
||||
}
|
||||
|
||||
void clearReauthFlag() {
|
||||
_reauthCubit.clear();
|
||||
debugPrint('[KretaClient] Reauth flag cleared');
|
||||
@@ -60,7 +173,7 @@ class KretaClient {
|
||||
Future<TokenModel> _refreshModelWithCrossDeviceLease(
|
||||
TokenModel sourceToken,
|
||||
) async {
|
||||
final studentIdNorm = sourceToken.studentIdNorm;
|
||||
final studentIdNorm = sourceToken.key;
|
||||
String? leaseOperationId;
|
||||
|
||||
try {
|
||||
@@ -123,39 +236,10 @@ class KretaClient {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _reloadActiveTokenModel({int? preferredStudentIdNorm}) async {
|
||||
final allTokens = await isar.tokenModels.where().findAll();
|
||||
if (allTokens.isEmpty) return;
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = allTokens;
|
||||
final selected = pickActiveToken(
|
||||
tokens: allTokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: preferredStudentIdNorm ?? model.studentIdNorm,
|
||||
);
|
||||
if (selected != null) {
|
||||
model = selected;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredStudentIdNorm != null) {
|
||||
for (final token in allTokens) {
|
||||
if (token.studentIdNorm == preferredStudentIdNorm) {
|
||||
model = token;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
model = allTokens.first;
|
||||
}
|
||||
|
||||
Future<bool> recoverToken() async {
|
||||
logger.info("[Recovery] Starting central token recovery...");
|
||||
final now = timeNow();
|
||||
final localExpiry = model.expiryDate;
|
||||
final now = DateTime.now();
|
||||
final localExpiry = cache.token.expiryDate;
|
||||
if (localExpiry != null &&
|
||||
localExpiry.isAfter(now.add(const Duration(seconds: 60)))) {
|
||||
logger.info(
|
||||
@@ -167,14 +251,14 @@ class KretaClient {
|
||||
|
||||
logger.info("[Recovery] Step 1: Trying local token refresh...");
|
||||
try {
|
||||
var tokenModel = await _refreshModelWithCrossDeviceLease(model);
|
||||
var tokenModel = await _refreshModelWithCrossDeviceLease(cache.token);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
await isarInit.writeTxn(() async {
|
||||
await isarInit.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
model = tokenModel;
|
||||
await _syncTokenToAppleTargets(model);
|
||||
cache.token = tokenModel;
|
||||
await _syncTokenToAppleTargets(cache.token);
|
||||
clearReauthFlag();
|
||||
logger.info("[Recovery] Step 1 SUCCESS: Local refresh succeeded");
|
||||
return true;
|
||||
@@ -186,6 +270,7 @@ class KretaClient {
|
||||
logger.warning(
|
||||
"[Recovery] Not iOS or not initialized, cannot try iCloud",
|
||||
);
|
||||
await _setReauthFlag();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -212,19 +297,15 @@ class KretaClient {
|
||||
);
|
||||
|
||||
final recovered = await WatchSyncHelper.checkAndRecoverFromiCloud(
|
||||
isar: isar,
|
||||
tokens: initData.tokens,
|
||||
isar: isarInit,
|
||||
client: this,
|
||||
allowExpiredAccessToken: true,
|
||||
);
|
||||
|
||||
if (recovered) {
|
||||
iCloudHasToken = true;
|
||||
await _reloadActiveTokenModel(
|
||||
preferredStudentIdNorm: model.studentIdNorm,
|
||||
);
|
||||
|
||||
final recoveredExpiry = model.expiryDate;
|
||||
final recoveredExpiry = cache.token.expiryDate;
|
||||
if (recoveredExpiry != null &&
|
||||
recoveredExpiry.isAfter(
|
||||
timeNow().add(const Duration(seconds: 60)),
|
||||
@@ -240,14 +321,14 @@ class KretaClient {
|
||||
"[Recovery] Found iCloud token close to expiry, trying refresh...",
|
||||
);
|
||||
try {
|
||||
var tokenModel = await _refreshModelWithCrossDeviceLease(model);
|
||||
var tokenModel = await _refreshModelWithCrossDeviceLease(cache.token);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
await isarInit.writeTxn(() async {
|
||||
await isarInit.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
model = tokenModel;
|
||||
await _syncTokenToAppleTargets(model);
|
||||
cache.token = tokenModel;
|
||||
await _syncTokenToAppleTargets(cache.token);
|
||||
clearReauthFlag();
|
||||
logger.info("[Recovery] Step 2 SUCCESS on attempt ${attempt + 1}");
|
||||
return true;
|
||||
@@ -268,6 +349,7 @@ class KretaClient {
|
||||
}
|
||||
|
||||
logger.warning("[Recovery] All recovery attempts failed");
|
||||
await _setReauthFlag();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -275,8 +357,8 @@ class KretaClient {
|
||||
final now = timeNow();
|
||||
final fiveMinutesFromNow = now.add(const Duration(minutes: 5));
|
||||
|
||||
if (model.expiryDate == null ||
|
||||
model.expiryDate!.isBefore(fiveMinutesFromNow)) {
|
||||
if (cache.token.expiryDate == null ||
|
||||
cache.token.expiryDate!.isBefore(fiveMinutesFromNow)) {
|
||||
logger.info(
|
||||
"[Proactive] Token expired or expiring soon, starting recovery...",
|
||||
);
|
||||
@@ -299,74 +381,42 @@ class KretaClient {
|
||||
}
|
||||
|
||||
logger.fine(
|
||||
"[Proactive] Token still valid until ${model.expiryDate}, no refresh needed",
|
||||
"[Proactive] Token still valid until ${cache.token.expiryDate}, no refresh needed",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<T> _mutexCallback<T>(Future<T> Function() callback) async {
|
||||
const maxWaitTime = Duration(seconds: 30);
|
||||
|
||||
if (_tokenMutexCompleter != null) {
|
||||
try {
|
||||
await _tokenMutexCompleter!.future.timeout(
|
||||
maxWaitTime,
|
||||
onTimeout: () {
|
||||
logger.warning(
|
||||
"[Mutex] Timeout waiting for token mutex, forcing release",
|
||||
);
|
||||
if (_tokenMutexCompleter != null &&
|
||||
!_tokenMutexCompleter!.isCompleted) {
|
||||
_tokenMutexCompleter!.complete();
|
||||
}
|
||||
},
|
||||
Future<TokenModel> _lockAndRecoverToken() {
|
||||
return _tokenMutexCompleter ??= Future(() async {
|
||||
final recovered = await recoverToken();
|
||||
if (!recovered) {
|
||||
logger.warning(
|
||||
"Token recovery failed for user: ${cache.token.username}",
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
_tokenMutexCompleter = Completer<void>();
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
final completer = _tokenMutexCompleter;
|
||||
_tokenMutexCompleter = null;
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.complete();
|
||||
throw TokenExpiredException();
|
||||
}
|
||||
}
|
||||
return cache.token;
|
||||
}).whenComplete(() => _tokenMutexCompleter = null);
|
||||
}
|
||||
|
||||
Future<Response> _authReq(String method, String url, [Object? data]) async {
|
||||
var localToken = await _mutexCallback<String>(() async {
|
||||
var now = timeNow();
|
||||
|
||||
if (now.millisecondsSinceEpoch >=
|
||||
model.expiryDate!.millisecondsSinceEpoch) {
|
||||
logger.info(
|
||||
"Token expired at ${model.expiryDate}, starting recovery for user: ${model.studentId}",
|
||||
);
|
||||
|
||||
final recovered = await recoverToken();
|
||||
if (!recovered) {
|
||||
logger.warning("Token recovery failed for user: ${model.studentId}");
|
||||
throw TokenExpiredException();
|
||||
}
|
||||
}
|
||||
|
||||
return model.accessToken!;
|
||||
});
|
||||
var localToken = (await _lockAndRecoverToken()).accessToken;
|
||||
|
||||
final headers = <String, String>{
|
||||
// "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": Constants.userAgent,
|
||||
"user-agent": initData.userAgent,
|
||||
"authorization": "Bearer $localToken",
|
||||
"apiKey": "21ff6c25-d1da-4a68-a811-c881a6057463",
|
||||
};
|
||||
|
||||
return await dio.get(
|
||||
url,
|
||||
options: Options(method: method, headers: headers),
|
||||
options: Options(
|
||||
method: method,
|
||||
headers: headers,
|
||||
receiveTimeout: Duration(seconds: 20),
|
||||
),
|
||||
data: data,
|
||||
);
|
||||
}
|
||||
@@ -381,19 +431,23 @@ class KretaClient {
|
||||
try {
|
||||
logger.finest("Sending authenticated request to: $url");
|
||||
resp = await _authReq(method, url, data);
|
||||
if (!url.endsWith("TanuloAdatlap")) {
|
||||
logger.finest("Response: ${resp.statusCode} ${resp.data}");
|
||||
|
||||
bool isEmpty(dynamic responseData) {
|
||||
return responseData == null ||
|
||||
(responseData is String && responseData.isEmpty) ||
|
||||
(responseData is List && responseData.isEmpty) ||
|
||||
(responseData is Map && responseData.isEmpty);
|
||||
}
|
||||
|
||||
if (resp.statusCode == 200 || resp.statusCode == 201) {
|
||||
final responseData = resp.data;
|
||||
if (responseData == null ||
|
||||
(responseData is List && responseData.isEmpty) ||
|
||||
(responseData is Map && responseData.isEmpty)) {
|
||||
if (isEmpty(resp.data)) {
|
||||
logger.warning(
|
||||
"API returned ${resp.statusCode} with empty data for: $url - possible stale session",
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.warning("Invalid response: ${resp.statusCode} ${resp.data}");
|
||||
logger.warning("Headers: ${resp.headers}");
|
||||
}
|
||||
} catch (ex) {
|
||||
if (ex is Error) {
|
||||
@@ -412,432 +466,194 @@ class KretaClient {
|
||||
return (resp.data, resp.statusCode!);
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<Lesson>>> _timetableCachingGet(
|
||||
DateTime weekday,
|
||||
bool forceCache,
|
||||
) async {
|
||||
var from = weekday.getMonday();
|
||||
return await _cachingGet(
|
||||
genCacheKey(from, model.studentIdNorm!),
|
||||
KretaEndpoints.getTimeTable(
|
||||
model.iss!,
|
||||
from,
|
||||
from.add(Duration(days: 6)),
|
||||
),
|
||||
forceCache,
|
||||
0,
|
||||
isar.timetableCacheModels,
|
||||
(key, resp) => TimetableCacheModel()
|
||||
..cacheKey = key
|
||||
..values = (resp as List<dynamic>)
|
||||
.map((item) => jsonEncode(item))
|
||||
.toList(),
|
||||
(cache) => cache.values
|
||||
.map((data) => Lesson.fromJson(jsonDecode(data)))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<R>>> _genericListedCachingGet<R>(
|
||||
CacheId id,
|
||||
Future<List<C>>
|
||||
_renewCache<C extends GenericCacheModel<I>, I extends Identifiable>(
|
||||
String url,
|
||||
bool forceCache,
|
||||
R Function(dynamic) mapResultEntries,
|
||||
) async {
|
||||
return await _genericCachingGet(
|
||||
id,
|
||||
url,
|
||||
forceCache,
|
||||
(data) => (data as List<dynamic>).map(mapResultEntries).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<ApiResponse<R>> _genericCachingGet<R>(
|
||||
CacheId id,
|
||||
String url,
|
||||
bool forceCache,
|
||||
R Function(dynamic) makeResult,
|
||||
) async {
|
||||
return await _cachingGet(
|
||||
// it would be *ideal* to use xor and left shift here, however
|
||||
// binary operations seem to round the number down to
|
||||
// 32 bits for some reason???
|
||||
(model.studentIdNorm! + ((id.index + 1) * pow(10, 11))) as Id,
|
||||
url,
|
||||
forceCache,
|
||||
0,
|
||||
isar.genericCacheModels,
|
||||
(key, resp) => GenericCacheModel()
|
||||
..cacheKey = key
|
||||
..cacheData = jsonEncode(resp),
|
||||
(cache) {
|
||||
return makeResult(jsonDecode(cache.cacheData!));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<ApiResponse<R>> _cachingGet<T, R>(
|
||||
Id cacheKey,
|
||||
String url,
|
||||
bool forceCache,
|
||||
int counter,
|
||||
IsarCollection<T> collection,
|
||||
T Function(Id, dynamic) makeCache,
|
||||
R Function(T) makeResult,
|
||||
) async {
|
||||
var cache = await collection.get(cacheKey);
|
||||
|
||||
if (forceCache && cache != null) {
|
||||
logger.finest(
|
||||
"_cachingGet(forceCache: $forceCache}): decoding cached response for: $url",
|
||||
);
|
||||
return ApiResponse.cached(makeResult(cache));
|
||||
}
|
||||
|
||||
C Function() makeCache,
|
||||
I Function(Map<String, dynamic>) makeDto, [
|
||||
int counter = 0,
|
||||
]) async {
|
||||
try {
|
||||
var (resp, statusCode) = await _authJson("GET", url);
|
||||
|
||||
if (statusCode >= 400 && cache != null) {
|
||||
logger.finest("request failed: $statusCode, using cache for: $url");
|
||||
return ApiResponse(makeResult(cache), statusCode, null, true);
|
||||
var data = resp;
|
||||
final caches = <C>[];
|
||||
if (data is Map<String, dynamic>) {
|
||||
data = [data];
|
||||
}
|
||||
if (data is List) {
|
||||
for (final e in data) {
|
||||
if (e is Map<String, dynamic>) {
|
||||
late I dto;
|
||||
try {
|
||||
dto = makeDto(e);
|
||||
} catch (ex) {
|
||||
logger.shout(
|
||||
"failed to make dto for $C",
|
||||
ex,
|
||||
ex is Error ? ex.stackTrace : null,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
caches.add(
|
||||
makeCache()
|
||||
..createdAt = DateTime.now()
|
||||
..cacheKey = cache.genCacheKey(dto)
|
||||
..apply(CacheContext(cache, dto)),
|
||||
);
|
||||
} catch (ex) {
|
||||
logger.shout(
|
||||
"failed to make cache $C: ${ex.toString()}",
|
||||
ex,
|
||||
ex is Error ? ex.stackTrace : null,
|
||||
);
|
||||
logger.shout("object: $e");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var newCache = makeCache(cacheKey, resp);
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
collection.put(newCache);
|
||||
});
|
||||
|
||||
return ApiResponse(makeResult(newCache), statusCode, null, false);
|
||||
return caches;
|
||||
} catch (ex) {
|
||||
if (_isTokenExpired(ex)) {
|
||||
logger.warning("Token expired, setting needsReauth flag");
|
||||
await _setReauthFlag();
|
||||
|
||||
return ApiResponse(null, 0, ex, false);
|
||||
if (isTokenExpired(ex)) {
|
||||
rethrow;
|
||||
}
|
||||
|
||||
if (ex is DioException && counter < backoffCount) {
|
||||
if ((ex is DioException &&
|
||||
ex.type != .connectionTimeout &&
|
||||
ex.type != .connectionError) &&
|
||||
counter < backoffCount) {
|
||||
logger.finest("Retrying: $counter / $backoffCount");
|
||||
final backoffDelay = backoffMin + (counter * backoffStep);
|
||||
logger.finest("Waiting: $backoffDelay");
|
||||
await Future.delayed(Duration(milliseconds: backoffDelay));
|
||||
|
||||
return _cachingGet(
|
||||
cacheKey,
|
||||
url,
|
||||
forceCache,
|
||||
counter + 1,
|
||||
collection,
|
||||
makeCache,
|
||||
makeResult,
|
||||
);
|
||||
return await _renewCache(url, makeCache, makeDto, counter + 1);
|
||||
}
|
||||
|
||||
if (cache != null) {
|
||||
logger.finest("request failed, using cache for: $url");
|
||||
return ApiResponse(makeResult(cache), 0, ex, true);
|
||||
}
|
||||
|
||||
logger.finest("request failed, no cache for: $url");
|
||||
return ApiResponse(null, 0, ex, false);
|
||||
logger.finest("request failed: $ex, no cache for: $url");
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
ApiResponse<List<ClassGroupSubjectAverage>>? classGroupAveragesCache;
|
||||
Future<List<C>> _save<C extends GenericCacheModel<I>, I extends Identifiable>(
|
||||
List<C> caches,
|
||||
) async {
|
||||
isarInit.writeTxnSync(() {
|
||||
isarInit.collection<C>().putAllSync(caches);
|
||||
});
|
||||
return caches;
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<ClassGroupSubjectAverage>>> getClassGroupAverages(
|
||||
ClassGroup classGroup, {
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (classGroup.studyTask == null) {
|
||||
String? err = "classGroup.studyTask is null";
|
||||
logger.warning(err);
|
||||
return ApiResponse([], 0, err, false);
|
||||
}
|
||||
if (!forceCache) {
|
||||
classGroupAveragesCache = null;
|
||||
} else if (classGroupAveragesCache != null) {
|
||||
return classGroupAveragesCache!;
|
||||
}
|
||||
Future<List<ClassAverageCacheModel>> getClassGroupAverages(
|
||||
ClassGroup classGroup,
|
||||
) async {
|
||||
var studyTaskUid = classGroup.studyTask!.uid.toString().split(",").first;
|
||||
var resp = await _genericListedCachingGet(
|
||||
CacheId.getClassGroupAvg,
|
||||
KretaEndpoints.getClassGroupAvg(model.iss!, studyTaskUid),
|
||||
forceCache,
|
||||
(item) => ClassGroupSubjectAverage.fromJson(item),
|
||||
);
|
||||
|
||||
if (resp.err == null) {
|
||||
classGroupAveragesCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getClassGroupAvg(cache.token.iss, studyTaskUid),
|
||||
ClassAverageCacheModel.new,
|
||||
(json) => ClassGroupSubjectAverage.fromJson(json),
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
ApiResponse<Student>? studentCache;
|
||||
|
||||
Future<ApiResponse<Student>> getStudent({bool forceCache = true}) async {
|
||||
if (!forceCache) {
|
||||
studentCache = null;
|
||||
} else if (studentCache != null) {
|
||||
return studentCache!;
|
||||
}
|
||||
|
||||
return await _genericCachingGet(
|
||||
CacheId.getStudent,
|
||||
KretaEndpoints.getStudentUrl(model.iss!),
|
||||
forceCache,
|
||||
Future<StudentCacheModel> getStudent() async {
|
||||
return (await _renewCache<StudentCacheModel, Student>(
|
||||
KretaEndpoints.getStudent(cache.token.iss),
|
||||
StudentCacheModel.new,
|
||||
(cache) => Student.fromJson(cache),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
studentCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
).then(_save)).first;
|
||||
}
|
||||
|
||||
ApiResponse<List<ClassGroup>>? classGroupCache;
|
||||
|
||||
Future<ApiResponse<List<ClassGroup>>> getClassGroups({
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (!forceCache) {
|
||||
classGroupCache = null;
|
||||
} else {
|
||||
if (classGroupCache != null) return classGroupCache!;
|
||||
}
|
||||
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getClassGroup,
|
||||
KretaEndpoints.getClassGroups(model.iss!),
|
||||
forceCache,
|
||||
Future<List<ClassGroupCacheModel>> getClassGroups() async {
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getClassGroups(cache.token.iss),
|
||||
ClassGroupCacheModel.new,
|
||||
(item) => ClassGroup.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
classGroupCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
ApiResponse<List<NoticeBoardItem>>? noticeBoardCache;
|
||||
|
||||
Future<ApiResponse<List<NoticeBoardItem>>> getNoticeBoard({
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (!forceCache) {
|
||||
noticeBoardCache = null;
|
||||
} else if (noticeBoardCache != null) {
|
||||
return noticeBoardCache!;
|
||||
}
|
||||
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getNoticeBoard,
|
||||
KretaEndpoints.getNoticeBoard(model.iss!),
|
||||
forceCache,
|
||||
(item) => NoticeBoardItem.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
noticeBoardCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
}
|
||||
|
||||
ApiResponse<List<InfoBoardItem>>? infoBoardCache;
|
||||
|
||||
Future<ApiResponse<List<InfoBoardItem>>> getInfoBoard({
|
||||
Future<List<MessageCacheModel>> getNoticeBoard({
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (forceCache && infoBoardCache != null) return infoBoardCache!;
|
||||
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getInfoBoard,
|
||||
KretaEndpoints.getInfoBoard(model.iss!, from, to),
|
||||
forceCache,
|
||||
(item) => InfoBoardItem.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
infoBoardCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getNoticeBoard(cache.token.iss, from, to),
|
||||
MessageCacheModel.new,
|
||||
(item) => NoticeBoardItem.fromJson(item) as MessageItem,
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
ApiResponse<List<Grade>>? gradeCache;
|
||||
|
||||
Future<ApiResponse<List<Grade>>> getGrades({bool forceCache = true}) async {
|
||||
if (!forceCache) {
|
||||
gradeCache = null;
|
||||
} else if (gradeCache != null) {
|
||||
return gradeCache!;
|
||||
}
|
||||
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getGrades,
|
||||
KretaEndpoints.getGrades(model.iss!),
|
||||
forceCache,
|
||||
(item) => Grade.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
resp.response!.sort((a, b) => b.recordDate.compareTo(a.recordDate));
|
||||
gradeCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
}
|
||||
|
||||
ApiResponse<List<SubjectAverage>>? subjectAverageCache;
|
||||
|
||||
Future<ApiResponse<List<SubjectAverage>>> getSubjectAverage(
|
||||
ClassGroup classGroup, {
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
String? err;
|
||||
if (classGroup.studyTask == null) {
|
||||
err = "classGroup.studyTask is null";
|
||||
logger.warning(err);
|
||||
return ApiResponse(
|
||||
List<SubjectAverage>.empty(growable: true),
|
||||
0,
|
||||
err,
|
||||
false,
|
||||
);
|
||||
}
|
||||
if (!forceCache) {
|
||||
subjectAverageCache = null;
|
||||
} else if (subjectAverageCache != null) {
|
||||
return subjectAverageCache!;
|
||||
}
|
||||
var studyTaskUid = classGroup.studyTask!.uid.toString().split(",").first;
|
||||
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getSubjectAvg,
|
||||
KretaEndpoints.getSubjectAvg(model.iss!, studyTaskUid),
|
||||
forceCache,
|
||||
(item) => SubjectAverage.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
subjectAverageCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<Homework>>> getHomework({
|
||||
Future<List<MessageCacheModel>> getInfoBoard({
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
}) async {
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getInfoBoard(cache.token.iss, from, to),
|
||||
MessageCacheModel.new,
|
||||
(json) => InfoBoardItem.fromJson(json) as MessageItem,
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
Future<List<GradeCacheModel>> getGrades() async {
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getGrades(cache.token.iss),
|
||||
GradeCacheModel.new,
|
||||
(json) => Grade.fromJson(json),
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
Future<List<HomeworkCacheModel>> getHomework({
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (from == null && to == null) {
|
||||
DateTime now = timeNow();
|
||||
DateTime start = now.copyWith(month: 9, day: 1);
|
||||
from = now.isBefore(start) ? start.subtract(Duration(days: 365)) : start;
|
||||
from = timeNow().getFirstSchoolDay();
|
||||
}
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getHomework,
|
||||
KretaEndpoints.getHomework(model.iss!, from, to),
|
||||
forceCache,
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getHomework(cache.token.iss, from, to),
|
||||
HomeworkCacheModel.new,
|
||||
(item) => Homework.fromJson(item),
|
||||
);
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
/// Automatically aligns requests to start at Monday and end at Sunday
|
||||
Future<ApiResponse<List<Lesson>>> getTimeTable(
|
||||
DateTime from,
|
||||
DateTime to, {
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
var lessons = List<Lesson>.empty(growable: true);
|
||||
String? err;
|
||||
bool cached = true;
|
||||
|
||||
for (
|
||||
var i = from.millisecondsSinceEpoch;
|
||||
i < to.millisecondsSinceEpoch;
|
||||
i += 604800000
|
||||
) {
|
||||
var weekday = DateTime.fromMillisecondsSinceEpoch(i);
|
||||
|
||||
var resp = await _timetableCachingGet(weekday, forceCache);
|
||||
if (resp.err != null) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
lessons.addAll(resp.response!);
|
||||
|
||||
if (!resp.cached) cached = false;
|
||||
}
|
||||
|
||||
lessons =
|
||||
lessons
|
||||
.where(
|
||||
(lesson) => lesson.start.isAfter(from) && lesson.end.isBefore(to),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => a.start.compareTo(b.start));
|
||||
|
||||
return ApiResponse(lessons, 200, err, cached);
|
||||
Future<List<LessonCacheModel>> getLessons(DateTime from, DateTime to) async {
|
||||
assert(from.difference(to).inDays < 30);
|
||||
return (await _renewCache(
|
||||
KretaEndpoints.getTimeTable(cache.token.iss, from, to),
|
||||
LessonCacheModel.new,
|
||||
(json) => Lesson.fromJson(json),
|
||||
).then(resolveDailyNth).then(_save))
|
||||
..sort((a, b) => a.start.compareTo(b.start));
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<AllLessons>>> getLessons({
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getLessons,
|
||||
KretaEndpoints.getLessons(model.iss!),
|
||||
forceCache,
|
||||
(item) => AllLessons.fromJson(item),
|
||||
);
|
||||
}
|
||||
|
||||
Future<ApiResponse<List<Test>>> getTests({
|
||||
DateTime? from,
|
||||
DateTime? to,
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getTests,
|
||||
KretaEndpoints.getTests(model.iss!, from, to),
|
||||
forceCache,
|
||||
Future<List<TestCacheModel>> getTests({DateTime? from, DateTime? to}) async {
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getTests(cache.token.iss, from, to),
|
||||
TestCacheModel.new,
|
||||
(item) => Test.fromJson(item),
|
||||
);
|
||||
).then(_save);
|
||||
}
|
||||
|
||||
ApiResponse<List<Omission>>? omissionsCache;
|
||||
|
||||
Future<ApiResponse<List<Omission>>> getOmissions({
|
||||
bool forceCache = true,
|
||||
}) async {
|
||||
if (!forceCache) {
|
||||
omissionsCache = null;
|
||||
} else {
|
||||
if (omissionsCache != null) return omissionsCache!;
|
||||
}
|
||||
return await _genericListedCachingGet(
|
||||
CacheId.getOmissions,
|
||||
KretaEndpoints.getOmissions(model.iss!),
|
||||
forceCache,
|
||||
Future<List<OmissionCacheModel>> getOmissions() async {
|
||||
return (await _renewCache(
|
||||
KretaEndpoints.getOmissions(cache.token.iss),
|
||||
OmissionCacheModel.new,
|
||||
(item) => Omission.fromJson(item),
|
||||
).then((resp) {
|
||||
if (resp.err == null) {
|
||||
resp.response!.sort((a, b) => a.date.compareTo(b.date));
|
||||
omissionsCache = ApiResponse.cached(resp.response);
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
).then(_save))..sort((a, b) => a.createdAt.compareTo(b.createdAt));
|
||||
}
|
||||
|
||||
void evictMemCache() {
|
||||
studentCache = null;
|
||||
noticeBoardCache = null;
|
||||
gradeCache = null;
|
||||
omissionsCache = null;
|
||||
classGroupCache = null;
|
||||
Future<List<SubjectCacheModel>> getSubjects() async {
|
||||
return await _renewCache(
|
||||
KretaEndpoints.getDktSubjects(cache.token.iss),
|
||||
SubjectCacheModel.new,
|
||||
(item) => DktSubject.fromJson(item),
|
||||
).then(_save);
|
||||
}
|
||||
}
|
||||
|
||||
bool _isTokenExpired(Object ex) =>
|
||||
bool isTokenExpired(Object ex) =>
|
||||
ex is TokenExpiredException || ex is InvalidGrantException;
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'kreta_client.dart';
|
||||
|
||||
bool getStudentFL = false;
|
||||
bool getClassGroupsFL = false;
|
||||
bool getNoticeBoardStreamFL = false;
|
||||
bool getInfoBoardStreamFL = false;
|
||||
bool getGradesStreamFL = false;
|
||||
bool getSubjectAverageStreamFL = false;
|
||||
bool getHomeworkStreamFL = false;
|
||||
bool getTimeTableStreamFL = false;
|
||||
bool getTestsStreamFL = false;
|
||||
bool getOmissionsStreamFL = false;
|
||||
|
||||
extension KretaStream on KretaClient {
|
||||
Stream<ApiResponse<Student>> getStudentStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getStudentFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getStudentFL = true;
|
||||
yield await getStudent(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getStudent(forceCache: false);
|
||||
}
|
||||
getStudentFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<ClassGroup>>> getClassGroupsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getClassGroupsFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getClassGroupsFL = true;
|
||||
yield await getClassGroups(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getClassGroups(forceCache: false);
|
||||
}
|
||||
getClassGroupsFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<NoticeBoardItem>>> getNoticeBoardStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getNoticeBoardStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getNoticeBoardStreamFL = true;
|
||||
yield await getNoticeBoard(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getNoticeBoard(forceCache: false);
|
||||
}
|
||||
getNoticeBoardStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<InfoBoardItem>>> getInfoBoardStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getInfoBoardStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getInfoBoardStreamFL = true;
|
||||
yield await getInfoBoard(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getInfoBoard(forceCache: false);
|
||||
}
|
||||
getInfoBoardStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Grade>>> getGradesStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getGradesStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getGradesStreamFL = true;
|
||||
yield await getGrades(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getGrades(forceCache: false);
|
||||
}
|
||||
getGradesStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<SubjectAverage>>> getSubjectAverageStream(
|
||||
ClassGroup classGroup, {
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getSubjectAverageStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getSubjectAverageStreamFL = true;
|
||||
yield await getSubjectAverage(classGroup, forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getSubjectAverage(classGroup, forceCache: false);
|
||||
}
|
||||
getSubjectAverageStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Homework>>> getHomeworkStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getHomeworkStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getHomeworkStreamFL = true;
|
||||
yield await getHomework(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getHomework(forceCache: false);
|
||||
}
|
||||
getHomeworkStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Lesson>>> getTimeTableStream(
|
||||
DateTime from,
|
||||
DateTime to, {
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getTimeTableStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getTimeTableStreamFL = true;
|
||||
yield await getTimeTable(from, to, forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getTimeTable(from, to, forceCache: false);
|
||||
}
|
||||
getTimeTableStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Test>>> getTestsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getTestsStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getTestsStreamFL = true;
|
||||
yield await getTests(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getTests(forceCache: false);
|
||||
}
|
||||
getTestsStreamFL = false;
|
||||
}
|
||||
|
||||
Stream<ApiResponse<List<Omission>>> getOmissionsStream({
|
||||
bool cacheOnly = true,
|
||||
}) async* {
|
||||
while (getOmissionsStreamFL) {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
}
|
||||
getOmissionsStreamFL = true;
|
||||
yield await getOmissions(forceCache: true);
|
||||
|
||||
if (!cacheOnly) {
|
||||
yield await getOmissions(forceCache: false);
|
||||
}
|
||||
getOmissionsStreamFL = false;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'consts.dart';
|
||||
|
||||
Future<TokenGrantResponse> getAccessToken(String code) async {
|
||||
final headers = <String, String>{
|
||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": Constants.userAgent,
|
||||
"user-agent": initData.userAgent,
|
||||
};
|
||||
|
||||
final formData = <String, String>{
|
||||
@@ -47,13 +48,13 @@ const _tokenRefreshRetryDelays = [1000, 3000, 5000];
|
||||
|
||||
Future<TokenGrantResponse> extendToken(TokenModel model) async {
|
||||
logger.info(
|
||||
"Extending token for user: ${model.studentId}, institute: ${model.iss}",
|
||||
"Extending token for user: ${model.username}, institute: ${model.iss}",
|
||||
);
|
||||
|
||||
final headers = <String, String>{
|
||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"accept": "*/*",
|
||||
"user-agent": Constants.userAgent,
|
||||
"user-agent": initData.userAgent,
|
||||
};
|
||||
|
||||
final formData = <String, String>{
|
||||
@@ -84,20 +85,20 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
|
||||
switch (response.statusCode) {
|
||||
case 200:
|
||||
logger.info(
|
||||
"Token extended successfully for user: ${model.studentId}",
|
||||
"Token extended successfully for user: ${model.username}",
|
||||
);
|
||||
return TokenGrantResponse.fromJson(response.data);
|
||||
case 400:
|
||||
case 401:
|
||||
logger.warning(
|
||||
"Token refresh failed (${response.statusCode}) - refresh token invalid for user: ${model.studentId}",
|
||||
"Token refresh failed (${response.statusCode}) - refresh token invalid for user: ${model.username}",
|
||||
);
|
||||
throw response.statusCode == 400
|
||||
? TokenExpiredException()
|
||||
: InvalidGrantException();
|
||||
default:
|
||||
logger.warning(
|
||||
"Token refresh failed (${response.statusCode}) for user: ${model.studentId}, attempt ${attempt + 1}",
|
||||
"Token refresh failed (${response.statusCode}) for user: ${model.username}, attempt ${attempt + 1}",
|
||||
);
|
||||
lastError = Exception(
|
||||
"Failed to get access token, response code: ${response.statusCode}",
|
||||
@@ -111,19 +112,19 @@ Future<TokenGrantResponse> extendToken(TokenModel model) async {
|
||||
rethrow;
|
||||
} on DioException catch (e) {
|
||||
logger.warning(
|
||||
"Token refresh network error for user: ${model.studentId}, attempt ${attempt + 1}: $e",
|
||||
"Token refresh network error for user: ${model.username}, attempt ${attempt + 1}: $e",
|
||||
);
|
||||
lastError = e;
|
||||
continue;
|
||||
} catch (e) {
|
||||
logger.severe("Token refresh exception for user: ${model.studentId}: $e");
|
||||
logger.severe("Token refresh exception for user: ${model.username}: $e");
|
||||
lastError = e is Exception ? e : Exception(e.toString());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
logger.severe(
|
||||
"All token refresh attempts failed for user: ${model.studentId}",
|
||||
"All token refresh attempts failed for user: ${model.username}",
|
||||
);
|
||||
throw lastError ?? Exception("Token refresh failed after all retries");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
@@ -8,7 +10,6 @@ import 'package:firka/core/bloc/profile_picture_cubit.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.dart';
|
||||
import 'package:firka/core/bloc/settings_cubit.dart';
|
||||
import 'package:firka/core/bloc/theme_cubit.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
@@ -48,20 +49,20 @@ class AppInitialization {
|
||||
final Directory appDir;
|
||||
final PackageInfo packageInfo;
|
||||
final DeviceInfo devInfo;
|
||||
late KretaClient client;
|
||||
List<TokenModel> tokens;
|
||||
KretaClient? client;
|
||||
bool hasWatchListener = false;
|
||||
|
||||
/// Set by the wear pairing modal; called when watch sends init_done or sync_done to dismiss the sheet.
|
||||
void Function()? dismissWearPairingSheet;
|
||||
Uint8List? profilePicture;
|
||||
SettingsStore settings;
|
||||
ThemeCubit? themeCubit;
|
||||
SettingsCubit? settingsCubit;
|
||||
ProfilePictureCubit? profilePictureCubit;
|
||||
ReauthCubit? reauthCubit;
|
||||
HomeRefreshCubit? homeRefreshCubit;
|
||||
final ThemeCubit themeCubit = ThemeCubit();
|
||||
final SettingsCubit settingsCubit = SettingsCubit();
|
||||
final ProfilePictureCubit profilePictureCubit = ProfilePictureCubit();
|
||||
final ReauthCubit reauthCubit = ReauthCubit();
|
||||
final HomeRefreshCubit homeRefreshCubit = HomeRefreshCubit();
|
||||
AppLocalizations l10n;
|
||||
String userAgent;
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
AppInitialization({
|
||||
@@ -69,9 +70,13 @@ class AppInitialization {
|
||||
required this.appDir,
|
||||
required this.devInfo,
|
||||
required this.packageInfo,
|
||||
required this.tokens,
|
||||
required this.settings,
|
||||
required this.l10n,
|
||||
required this.navigatorKey,
|
||||
});
|
||||
}) : userAgent = Platform.isAndroid
|
||||
? "${Constants.applicationId}/${Constants.applicationVersion}"
|
||||
"/${devInfo.model}"
|
||||
"/${devInfo.versionRelease}"
|
||||
"/${devInfo.versionSdkInt}"
|
||||
: "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0";
|
||||
}
|
||||
|
||||
@@ -1,22 +1,15 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/core/bloc/profile_picture_cubit.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.dart';
|
||||
import 'package:firka/core/bloc/settings_cubit.dart';
|
||||
import 'package:firka/core/bloc/theme_cubit.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/data/models/generic_cache_model.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka/data/models/timetable_cache_model.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/services/watch_sync_helper.dart';
|
||||
@@ -32,28 +25,6 @@ import 'package:isar_community/isar.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
Isar? isarInit;
|
||||
|
||||
Future<Isar> initDB() async {
|
||||
if (isarInit != null) return isarInit!;
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
|
||||
isarInit = await Isar.open(
|
||||
[
|
||||
TokenModelSchema,
|
||||
GenericCacheModelSchema,
|
||||
TimetableCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
HomeworkDoneModelSchema,
|
||||
],
|
||||
inspector: true,
|
||||
directory: dir.path,
|
||||
);
|
||||
|
||||
return isarInit!;
|
||||
}
|
||||
|
||||
Future<void> initLang(AppInitialization data) async {
|
||||
String? languageCode;
|
||||
|
||||
@@ -107,7 +78,6 @@ Future<void> initLang(AppInitialization data) async {
|
||||
|
||||
void initTheme(AppInitialization data) {
|
||||
final themeCubit = data.themeCubit;
|
||||
if (themeCubit == null) return;
|
||||
|
||||
final brightness =
|
||||
SchedulerBinding.instance.platformDispatcher.platformBrightness;
|
||||
@@ -135,11 +105,6 @@ void initTheme(AppInitialization data) {
|
||||
}
|
||||
|
||||
Future<void> _initData(AppInitialization init) async {
|
||||
init.themeCubit ??= ThemeCubit();
|
||||
init.settingsCubit ??= SettingsCubit();
|
||||
init.profilePictureCubit ??= ProfilePictureCubit();
|
||||
init.reauthCubit ??= ReauthCubit();
|
||||
init.homeRefreshCubit ??= HomeRefreshCubit();
|
||||
await init.settings.load(init.isar.appSettingsModels);
|
||||
await initLang(init);
|
||||
initTheme(init);
|
||||
@@ -174,9 +139,6 @@ Future<void> _initData(AppInitialization init) async {
|
||||
}());
|
||||
};
|
||||
|
||||
resetOldTimeTableCache(init.isar);
|
||||
resetOldHomeworkCache(init.isar);
|
||||
|
||||
var didRunFreshInstallCleanup = false;
|
||||
if (Platform.isIOS) {
|
||||
try {
|
||||
@@ -187,50 +149,41 @@ Future<void> _initData(AppInitialization init) async {
|
||||
'[Init] Fresh-install cleanup completed; skipping startup iCloud recovery on this launch',
|
||||
);
|
||||
} else {
|
||||
await WatchSyncHelper.checkAndRecoverFromiCloud(
|
||||
isar: init.isar,
|
||||
tokens: init.tokens,
|
||||
);
|
||||
await WatchSyncHelper.checkAndRecoverFromiCloud(isar: init.isar);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning('[Init] iCloud bootstrap/recovery failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
final allTokens = await init.isar.tokenModels.where().findAll();
|
||||
init.tokens = allTokens;
|
||||
final token = init.settings.getSelectedToken();
|
||||
if (token == null) {
|
||||
logger.warning("[Init] No token available!");
|
||||
return;
|
||||
}
|
||||
logger.fine("Initializing kréta client as: ${token.username}");
|
||||
init.client = KretaClient(token, init.reauthCubit!);
|
||||
await init.client!.init();
|
||||
|
||||
if (allTokens.isNotEmpty) {
|
||||
final token = pickActiveToken(tokens: allTokens, settings: init.settings);
|
||||
if (token == null) {
|
||||
logger.warning(
|
||||
"[Init] Tokens disappeared during initialization; skipping client setup",
|
||||
);
|
||||
return;
|
||||
if (Platform.isIOS) {
|
||||
final expiryDate = token.expiryDate;
|
||||
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
|
||||
init.reauthCubit?.clear();
|
||||
}
|
||||
logger.fine("Initializing kréta client as: ${token.studentId}");
|
||||
init.client = KretaClient(token, init.isar, init.reauthCubit!);
|
||||
|
||||
if (Platform.isIOS) {
|
||||
final expiryDate = token.expiryDate;
|
||||
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
|
||||
init.reauthCubit?.clear();
|
||||
unawaited(() async {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to iCloud: $e');
|
||||
}
|
||||
|
||||
unawaited(() async {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to iCloud: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenModelToWatch(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to Watch: $e');
|
||||
}
|
||||
}());
|
||||
}
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenModelToWatch(token);
|
||||
} catch (e) {
|
||||
logger.warning('[Init] Failed to sync active token to Watch: $e');
|
||||
}
|
||||
}());
|
||||
}
|
||||
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
@@ -239,12 +192,14 @@ Future<void> _initData(AppInitialization init) async {
|
||||
if (await pfpFile.exists()) {
|
||||
init.profilePicture = await pfpFile.readAsBytes();
|
||||
}
|
||||
|
||||
init.homeRefreshCubit.requestRefresh();
|
||||
}
|
||||
|
||||
Future<AppInitialization> initializeApp() async {
|
||||
Future<void> initializeApp() async {
|
||||
if (initDone) {
|
||||
await _initData(initData);
|
||||
return initData;
|
||||
return;
|
||||
}
|
||||
final isar = await initDB();
|
||||
final tokens = await isar.tokenModels.where().findAll();
|
||||
@@ -274,12 +229,11 @@ Future<AppInitialization> initializeApp() async {
|
||||
logger.fine("Fetched device info: ${devInfoFetched ? "yes" : "no"}");
|
||||
logger.fine("Using device info: ${devInfo.toString()}");
|
||||
|
||||
var init = AppInitialization(
|
||||
initData = AppInitialization(
|
||||
isar: isar,
|
||||
appDir: await getApplicationDocumentsDirectory(),
|
||||
devInfo: devInfo,
|
||||
packageInfo: await PackageInfo.fromPlatform(),
|
||||
tokens: tokens,
|
||||
settings: SettingsStore(AppLocalizationsHu()),
|
||||
l10n: AppLocalizationsHu(),
|
||||
navigatorKey: navigatorKey,
|
||||
@@ -297,9 +251,9 @@ Future<AppInitialization> initializeApp() async {
|
||||
}
|
||||
}
|
||||
|
||||
await _initData(init);
|
||||
await _initData(initData);
|
||||
|
||||
return init;
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
Future<void> setupLogging() async {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka_common/core/debug_helper.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -31,9 +34,7 @@ class InitializationScreen extends StatefulWidget {
|
||||
|
||||
class _InitializationScreenState extends State<InitializationScreen> {
|
||||
GoRouter? _router;
|
||||
final Future<AppInitialization> _init = initializeApp().timeout(
|
||||
const Duration(seconds: 20),
|
||||
);
|
||||
final Future<void> _init = initializeApp();
|
||||
|
||||
ThemeData _buildTheme(FirkaStyle style) {
|
||||
return ThemeData(
|
||||
@@ -54,11 +55,13 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<AppInitialization>(
|
||||
return FutureBuilder<void>(
|
||||
future: _init,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.done) {
|
||||
if (snapshot.hasError) {
|
||||
initDone = false;
|
||||
|
||||
logger.shout(
|
||||
"Error in InitializationScreen",
|
||||
snapshot.error.toString(),
|
||||
@@ -83,10 +86,6 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
assert(snapshot.data != null);
|
||||
initData = snapshot.data!;
|
||||
initDone = true;
|
||||
|
||||
FlutterNativeSplash.remove();
|
||||
|
||||
WatchSyncHelper.initialize();
|
||||
@@ -113,24 +112,20 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
|
||||
switch (msg["id"]) {
|
||||
case "ping":
|
||||
if (initData.tokens.isNotEmpty) {
|
||||
logger.finest("WatchOS IPC [Phone -> Watch]: pong");
|
||||
unawaited(
|
||||
WatchSyncHelper.sendMessageToWatch({'id': 'pong'}),
|
||||
);
|
||||
_router?.go('/home');
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final ctx = navigatorKey.currentContext;
|
||||
if (ctx != null && ctx.mounted) {
|
||||
logger.info('Watch init_data: ${jsonEncode(msg)}');
|
||||
showWearBottomSheet(
|
||||
ctx,
|
||||
initData,
|
||||
Platform.isAndroid ? msg['model'] : 'Apple Watch',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
logger.finest("WatchOS IPC [Phone -> Watch]: pong");
|
||||
unawaited(WatchSyncHelper.sendMessageToWatch({'id': 'pong'}));
|
||||
_router?.go('/home');
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final ctx = navigatorKey.currentContext;
|
||||
if (ctx != null && ctx.mounted) {
|
||||
logger.info('Watch init_data: ${jsonEncode(msg)}');
|
||||
showWearBottomSheet(
|
||||
ctx,
|
||||
initData,
|
||||
Platform.isAndroid ? msg['model'] : 'Apple Watch',
|
||||
);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "init_done":
|
||||
case "sync_done":
|
||||
@@ -157,7 +152,7 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
);
|
||||
}
|
||||
await WatchSyncHelper.runWearSyncInForeground(
|
||||
initData.client,
|
||||
initData.client!,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -165,7 +160,7 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
unawaited(() async {
|
||||
try {
|
||||
await WatchSyncHelper.startWearSyncServiceWithFreshCache(
|
||||
initData.client,
|
||||
initData.client!,
|
||||
initData.appDir.path,
|
||||
);
|
||||
} catch (e) {
|
||||
@@ -203,15 +198,18 @@ class _InitializationScreenState extends State<InitializationScreen> {
|
||||
final isLight = themeState.isLightMode;
|
||||
final overlay = SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.transparent,
|
||||
statusBarIconBrightness:
|
||||
isLight ? Brightness.dark : Brightness.light,
|
||||
statusBarBrightness:
|
||||
isLight ? Brightness.light : Brightness.dark,
|
||||
statusBarIconBrightness: isLight
|
||||
? Brightness.dark
|
||||
: Brightness.light,
|
||||
statusBarBrightness: isLight
|
||||
? Brightness.light
|
||||
: Brightness.dark,
|
||||
systemStatusBarContrastEnforced: false,
|
||||
);
|
||||
|
||||
final themeMode =
|
||||
isLight ? ThemeMode.light : ThemeMode.dark;
|
||||
logger.info("asked");
|
||||
|
||||
final themeMode = isLight ? ThemeMode.light : ThemeMode.dark;
|
||||
|
||||
final fallbackBg = isLight
|
||||
? lightStyle.colors.background
|
||||
|
||||
@@ -209,16 +209,12 @@ extension DateExtension on DateTime {
|
||||
return subtract(Duration(days: weekday - 1));
|
||||
}
|
||||
|
||||
DateTime getMidnight() {
|
||||
return subtract(
|
||||
Duration(
|
||||
hours: hour,
|
||||
minutes: minute,
|
||||
seconds: second,
|
||||
milliseconds: millisecond,
|
||||
microseconds: microsecond,
|
||||
),
|
||||
);
|
||||
DateTime getMonthFirstDay() {
|
||||
return DateTime(year, month, 1);
|
||||
}
|
||||
|
||||
DateTime getMonthLastDay() {
|
||||
return DateTime(year, month + 1, 1).subtract(Duration(days: 1));
|
||||
}
|
||||
|
||||
Cycle getDayCycle() {
|
||||
@@ -238,6 +234,11 @@ extension DateExtension on DateTime {
|
||||
|
||||
return Cycle.night;
|
||||
}
|
||||
|
||||
DateTime getFirstSchoolDay() {
|
||||
DateTime start = copyWith(month: 9, day: 1);
|
||||
return isBefore(start) ? start.copyWith(year: start.year - 1) : start;
|
||||
}
|
||||
}
|
||||
|
||||
extension DateGrouper<T> on Iterable<T> {
|
||||
|
||||
@@ -4,9 +4,6 @@ import 'package:flutter/services.dart';
|
||||
class FirkaBundle extends CachingAssetBundle {
|
||||
@override
|
||||
Future<ByteData> load(String key) async {
|
||||
logger.finest(
|
||||
"Loading asset from root bundle: assets/flutter_assets/$key",
|
||||
);
|
||||
return rootBundle.load(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -99,7 +98,6 @@ class ImagePreloader {
|
||||
AssetBundle bundle,
|
||||
String assetPath,
|
||||
) async {
|
||||
logger.finest("Caching: $assetPath");
|
||||
final ByteData data = await bundle.load(assetPath);
|
||||
final Uint8List bytes = data.buffer.asUint8List();
|
||||
return await _decodeImageFromBytes(bytes);
|
||||
|
||||
@@ -2,11 +2,13 @@ import 'dart:collection';
|
||||
import 'dart:core';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka_common/firka_common.dart' as common;
|
||||
import 'package:firka_common/core/grade_helper.dart' as helper;
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -240,8 +242,7 @@ class SettingsStore {
|
||||
initData.settings = SettingsStore(initData.l10n);
|
||||
await initData.settings.load(initData.isar.appSettingsModels);
|
||||
|
||||
initData.themeCubit?.refresh();
|
||||
runApp(InitializationScreen());
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
},
|
||||
),
|
||||
}),
|
||||
@@ -353,6 +354,7 @@ class SettingsStore {
|
||||
always,
|
||||
() async {
|
||||
initTheme(initData);
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
},
|
||||
),
|
||||
}),
|
||||
@@ -384,7 +386,7 @@ class SettingsStore {
|
||||
await Permission.notification.request();
|
||||
}
|
||||
await WatchSyncHelper.startWearSyncServiceWithFreshCache(
|
||||
initData.client,
|
||||
initData.client!,
|
||||
initData.appDir.path,
|
||||
);
|
||||
} else {
|
||||
@@ -722,7 +724,7 @@ class SettingsStore {
|
||||
final rounding = group(
|
||||
"settings",
|
||||
).subGroup("application").subGroup("rounding");
|
||||
return common.roundGrade(
|
||||
return helper.roundGrade(
|
||||
grade,
|
||||
t1: rounding.dbl("1"),
|
||||
t2: rounding.dbl("2"),
|
||||
@@ -745,6 +747,14 @@ class SettingsStore {
|
||||
return appStyle.colors.grade1;
|
||||
}
|
||||
}
|
||||
|
||||
TokenModel? getSelectedToken() {
|
||||
final accountPicker =
|
||||
(group("profile_settings")["e_kreta_account_picker"]
|
||||
as SettingsKretenAccountPicker);
|
||||
return isarInit.tokenModels.getSync(accountPicker.accountKey) ??
|
||||
isarInit.tokenModels.where().findFirstSync();
|
||||
}
|
||||
}
|
||||
|
||||
extension SettingExt on LinkedHashMap<String, SettingsItem> {
|
||||
@@ -1062,10 +1072,12 @@ class SettingsKretenAccountPicker implements SettingsItem {
|
||||
@override
|
||||
bool Function() visibilityProvider;
|
||||
@override
|
||||
Future<void> Function() postUpdate = () async {};
|
||||
Future<void> Function() postUpdate = () async {
|
||||
await initializeApp();
|
||||
};
|
||||
String title = "";
|
||||
String icon = "";
|
||||
int accountIndex = 0;
|
||||
int accountKey = 0;
|
||||
|
||||
SettingsKretenAccountPicker(this.key, this.visibilityProvider);
|
||||
|
||||
@@ -1073,9 +1085,9 @@ class SettingsKretenAccountPicker implements SettingsItem {
|
||||
Future<void> load(IsarCollection<AppSettingsModel> model) async {
|
||||
var v = await model.get(key);
|
||||
if (v == null || v.valueIndex == null) {
|
||||
accountIndex = 0;
|
||||
accountKey = 0;
|
||||
} else {
|
||||
accountIndex = v.valueIndex!;
|
||||
accountKey = v.valueIndex!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1083,7 +1095,7 @@ class SettingsKretenAccountPicker implements SettingsItem {
|
||||
Future<void> save(IsarCollection<AppSettingsModel> model) async {
|
||||
var v = AppSettingsModel();
|
||||
v.id = key;
|
||||
v.valueIndex = accountIndex;
|
||||
v.valueIndex = accountKey;
|
||||
|
||||
await model.put(v);
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ class IOSWidgetHelper {
|
||||
'description': subject.category.description,
|
||||
},
|
||||
'sortIndex': subject.sortIndex,
|
||||
'teacherName': subject.teacherName,
|
||||
'teacherName': null,
|
||||
}
|
||||
: {
|
||||
'uid': '',
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
part 'generic_cache_model.g.dart';
|
||||
|
||||
enum CacheId {
|
||||
getStudent,
|
||||
getNoticeBoard,
|
||||
getInfoBoard,
|
||||
getGrades,
|
||||
getOmissions,
|
||||
getTests,
|
||||
getClassGroup,
|
||||
getSubjectAvg,
|
||||
getLessons,
|
||||
getHomework,
|
||||
getClassGroupAvg,
|
||||
}
|
||||
|
||||
@collection
|
||||
class GenericCacheModel {
|
||||
Id? cacheKey;
|
||||
String? cacheData;
|
||||
|
||||
GenericCacheModel();
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/util.dart';
|
||||
|
||||
part 'homework_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class HomeworkCacheModel extends DatedCacheEntry {
|
||||
HomeworkCacheModel();
|
||||
}
|
||||
|
||||
Future<void> resetOldHomeworkCache(Isar isar) async {
|
||||
var now = timeNow();
|
||||
var weeks = await isar.homeworkCacheModels.where().findAll();
|
||||
var weeksToRemove = List<Id>.empty(growable: true);
|
||||
|
||||
for (var week in weeks) {
|
||||
var date = getDate(week.cacheKey!);
|
||||
|
||||
if (date.millisecondsSinceEpoch <
|
||||
now.subtract(Duration(days: 120)).millisecondsSinceEpoch) {
|
||||
weeksToRemove.add(week.cacheKey!);
|
||||
}
|
||||
}
|
||||
await isar.writeTxn(() async {
|
||||
await isar.homeworkCacheModels.deleteAll(weeksToRemove);
|
||||
});
|
||||
}
|
||||
|
||||
@collection
|
||||
class HomeworkDoneModel {
|
||||
Id? id;
|
||||
|
||||
late String homeworkId;
|
||||
late DateTime doneAt;
|
||||
|
||||
HomeworkDoneModel();
|
||||
}
|
||||
|
||||
Future<void> markAsDone(Isar isar, String homeWorkUid) async {
|
||||
await isar.writeTxn(() async {
|
||||
await isar.homeworkDoneModels.put(
|
||||
HomeworkDoneModel()
|
||||
..homeworkId = homeWorkUid
|
||||
..doneAt = DateTime.now(),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> markAsNotDone(Isar isar, String homeWorkUid) async {
|
||||
await isar.writeTxn(() async {
|
||||
final idsToDelete = await isar.homeworkDoneModels
|
||||
.filter()
|
||||
.homeworkIdEqualTo(homeWorkUid)
|
||||
.idProperty()
|
||||
.findAll();
|
||||
await isar.homeworkDoneModels.deleteAll(idsToDelete);
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> isHomeworkDone(Isar isar, String homeWorkUid) async {
|
||||
var existing = await isar.homeworkDoneModels
|
||||
.filter()
|
||||
.homeworkIdEqualTo(homeWorkUid)
|
||||
.findFirst();
|
||||
return existing != null;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/util.dart';
|
||||
|
||||
part 'timetable_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class TimetableCacheModel extends DatedCacheEntry {
|
||||
TimetableCacheModel();
|
||||
}
|
||||
|
||||
Future<void> resetOldTimeTableCache(Isar isar) async {
|
||||
var now = timeNow();
|
||||
var weeks = await isar.timetableCacheModels.where().findAll();
|
||||
var weeksToRemove = List<Id>.empty(growable: true);
|
||||
|
||||
for (var week in weeks) {
|
||||
var date = getDate(week.cacheKey!);
|
||||
|
||||
if (date.millisecondsSinceEpoch <
|
||||
now.subtract(Duration(days: 120)).millisecondsSinceEpoch) {
|
||||
weeksToRemove.add(week.cacheKey!);
|
||||
}
|
||||
}
|
||||
await isar.writeTxn(() async {
|
||||
await isar.timetableCacheModels.deleteAll(weeksToRemove);
|
||||
});
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
|
||||
class DatedCacheEntry {
|
||||
Id? cacheKey;
|
||||
late List<String> values;
|
||||
}
|
||||
|
||||
int genCacheKey(DateTime date, int studentId) {
|
||||
var md = date.month * pow(10, 2) + date.day;
|
||||
|
||||
return (md * pow(10, 11) + studentId) as int;
|
||||
}
|
||||
|
||||
DateTime getDate(int key) {
|
||||
var md = key ~/ pow(10, 11);
|
||||
var month = md ~/ pow(10, 2);
|
||||
var day = (md - month * pow(10, 2)) as int;
|
||||
|
||||
return DateTime(timeNow().year, month, day);
|
||||
}
|
||||
@@ -3,10 +3,12 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
import 'package:firka/data/ios_widget_helper.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/data/ios_widget_helper.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
@@ -16,13 +18,12 @@ import 'package:path_provider/path_provider.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class WidgetCacheHelper {
|
||||
static Map<String, dynamic> toJson(FirkaStyle style, List<Lesson> timetable) {
|
||||
static Map<String, dynamic> toJson(
|
||||
FirkaStyle style,
|
||||
List<LessonCacheModel> timetable,
|
||||
) {
|
||||
List<Map<String, dynamic>> timetableJson = [];
|
||||
|
||||
for (var lesson in timetable) {
|
||||
timetableJson.add(lesson.toJson());
|
||||
}
|
||||
|
||||
return {'colors': _colorsMap(style), 'timetable': timetableJson};
|
||||
}
|
||||
|
||||
@@ -86,20 +87,13 @@ class WidgetCacheHelper {
|
||||
|
||||
final start = now.subtract(Duration(days: 7));
|
||||
final end = now.add(Duration(days: 14));
|
||||
final lessons = await client.getTimeTable(start, end, forceCache: false);
|
||||
final lessons = await client.getLessons(start, end);
|
||||
|
||||
final widgetFile = File(p.join(dataDir.path, "widget_state.json"));
|
||||
|
||||
if (lessons.response != null) {
|
||||
debugPrint(
|
||||
'Android widget cache: ${lessons.response!.length} lessons (cached: ${lessons.cached})',
|
||||
);
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons.response!)),
|
||||
);
|
||||
} else {
|
||||
debugPrint('Android widget cache: No lessons to cache');
|
||||
}
|
||||
widgetFile.writeAsString(
|
||||
jsonEncode(WidgetCacheHelper.toJson(style, lessons)),
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> generateWidgetStateForDate(
|
||||
@@ -110,14 +104,8 @@ class WidgetCacheHelper {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final dayStart = DateTime(date.year, date.month, date.day);
|
||||
final dayEnd = dayStart.add(Duration(hours: 23, minutes: 59));
|
||||
final lessons = await client.getTimeTable(
|
||||
dayStart,
|
||||
dayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
final dayLessons = lessons.response ?? [];
|
||||
|
||||
final json = toJson(style, dayLessons);
|
||||
final json = toJson(style, []);
|
||||
json['displayDate'] =
|
||||
'${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
|
||||
|
||||
@@ -125,32 +113,6 @@ class WidgetCacheHelper {
|
||||
await widgetFile.writeAsString(jsonEncode(json));
|
||||
}
|
||||
|
||||
static Future<void> updateIOSWidgets({
|
||||
required String locale,
|
||||
required String theme,
|
||||
required List<Lesson> todayLessons,
|
||||
required List<Lesson> tomorrowLessons,
|
||||
List<Lesson> nextSchoolDayLessons = const [],
|
||||
DateTime? nextSchoolDayDate,
|
||||
required List<Grade> grades,
|
||||
required Map<String, double> subjectAverages,
|
||||
required double? overallAverage,
|
||||
WidgetBreakInfo? currentBreak,
|
||||
}) async {
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: locale,
|
||||
theme: theme,
|
||||
todayLessons: todayLessons,
|
||||
tomorrowLessons: tomorrowLessons,
|
||||
nextSchoolDayLessons: nextSchoolDayLessons,
|
||||
nextSchoolDayDate: nextSchoolDayDate,
|
||||
grades: grades,
|
||||
subjectAverages: subjectAverages,
|
||||
overallAverage: overallAverage,
|
||||
currentBreak: currentBreak,
|
||||
);
|
||||
}
|
||||
|
||||
/// Comprehensive iOS widget refresh that collects all necessary data
|
||||
/// Call this on: app open, user switch, data refresh
|
||||
static Future<void> refreshIOSWidgets(
|
||||
@@ -203,19 +165,17 @@ class WidgetCacheHelper {
|
||||
final todayMidnight = DateTime(now.year, now.month, now.day);
|
||||
final tomorrowMidnight = todayMidnight.add(Duration(days: 1));
|
||||
|
||||
final todayResponse = await client.getTimeTable(
|
||||
final todayResponse = await client.getLessons(
|
||||
todayMidnight,
|
||||
todayMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
final tomorrowResponse = await client.getTimeTable(
|
||||
final tomorrowResponse = await client.getLessons(
|
||||
tomorrowMidnight,
|
||||
tomorrowMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
final todayLessons = todayResponse.response ?? [];
|
||||
final tomorrowLessons = tomorrowResponse.response ?? [];
|
||||
final todayLessons = [];
|
||||
final tomorrowLessons = [];
|
||||
|
||||
debugPrint(
|
||||
'iOS widget refresh: ${todayLessons.length} today lessons, ${tomorrowLessons.length} tomorrow lessons',
|
||||
@@ -226,12 +186,11 @@ class WidgetCacheHelper {
|
||||
if (tomorrowLessons.isEmpty) {
|
||||
for (int i = 2; i <= 7; i++) {
|
||||
final dayMidnight = todayMidnight.add(Duration(days: i));
|
||||
final dayResponse = await client.getTimeTable(
|
||||
final dayResponse = await client.getLessons(
|
||||
dayMidnight,
|
||||
dayMidnight.add(Duration(hours: 23, minutes: 59)),
|
||||
forceCache: false,
|
||||
);
|
||||
final dayLessons = dayResponse.response ?? [];
|
||||
final dayLessons = <Lesson>[];
|
||||
if (dayLessons.isNotEmpty) {
|
||||
nextSchoolDayLessons = dayLessons;
|
||||
nextSchoolDayDate = dayMidnight;
|
||||
@@ -243,11 +202,11 @@ class WidgetCacheHelper {
|
||||
}
|
||||
}
|
||||
|
||||
final gradesResponse = await client.getGrades(forceCache: false);
|
||||
final grades = gradesResponse.response ?? [];
|
||||
final gradesResponse = await client.getGrades();
|
||||
final grades = [];
|
||||
|
||||
debugPrint(
|
||||
'iOS widget refresh: ${grades.length} grades fetched (cached: ${gradesResponse.cached})',
|
||||
'iOS widget refresh: ${grades.length} grades fetched (cached: ${gradesResponse})',
|
||||
);
|
||||
|
||||
final Map<String, double> subjectAverages = {};
|
||||
@@ -258,25 +217,18 @@ class WidgetCacheHelper {
|
||||
|
||||
subjects.addAll(grades.map((g) => g.subject));
|
||||
|
||||
for (var subject in subjects) {
|
||||
final average = grades.getAverageBySubject(subject);
|
||||
if (average != null) {
|
||||
subjectAverages[subject.uid] = average;
|
||||
}
|
||||
}
|
||||
|
||||
WidgetBreakInfo? currentBreak;
|
||||
|
||||
await updateIOSWidgets(
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: locale,
|
||||
theme: theme,
|
||||
todayLessons: todayLessons,
|
||||
tomorrowLessons: tomorrowLessons,
|
||||
todayLessons: [],
|
||||
tomorrowLessons: [],
|
||||
nextSchoolDayLessons: nextSchoolDayLessons,
|
||||
nextSchoolDayDate: nextSchoolDayDate,
|
||||
grades: grades,
|
||||
grades: [],
|
||||
subjectAverages: subjectAverages,
|
||||
overallAverage: grades.getSubjectAverage(),
|
||||
overallAverage: 0.0,
|
||||
currentBreak: currentBreak,
|
||||
);
|
||||
|
||||
@@ -291,7 +243,7 @@ class WidgetCacheHelper {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
try {
|
||||
await updateIOSWidgets(
|
||||
await IOSWidgetHelper.updateWidgetData(
|
||||
locale: 'hu',
|
||||
theme: 'light',
|
||||
todayLessons: [],
|
||||
|
||||
@@ -13,6 +13,10 @@ void main() async {
|
||||
dio.options.receiveTimeout = Duration(seconds: 3);
|
||||
dio.options.validateStatus = (status) => status != null && status < 500;
|
||||
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.presentError(details);
|
||||
};
|
||||
|
||||
runZonedGuarded(
|
||||
() async {
|
||||
logger.finest("Initializing app");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka/ui/phone/pages/home/home_omissions.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
@@ -30,7 +31,9 @@ GoRouter createAppRouter() {
|
||||
builder: (context, state) {
|
||||
return DefaultAssetBundle(
|
||||
bundle: FirkaBundle(),
|
||||
child: HomeGradesSubjectScreen(state.extra as Subject, initData),
|
||||
child: HomeGradesSubjectScreen.subject(
|
||||
state.extra as SubjectCacheModel,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -200,7 +203,7 @@ GoRouter createAppRouter() {
|
||||
|
||||
String get _initialLocation {
|
||||
if (!initDone) return '/';
|
||||
if (initData.tokens.isEmpty) return '/login';
|
||||
if (initData.client == null) return '/login';
|
||||
final betaWarning = initData.settings
|
||||
.group('settings')
|
||||
.boolean('beta_warning');
|
||||
@@ -211,7 +214,7 @@ String get _initialLocation {
|
||||
String? _redirect(BuildContext context, GoRouterState state) {
|
||||
if (!initDone) return null;
|
||||
final location = state.matchedLocation;
|
||||
final hasTokens = initData.tokens.isNotEmpty;
|
||||
final hasTokens = initData.client != null;
|
||||
final betaWarning = initData.settings
|
||||
.group('settings')
|
||||
.boolean('beta_warning');
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
|
||||
int resolveActiveAccountIndex(dynamic settings) {
|
||||
try {
|
||||
final dynamic profileSettings = settings.group("profile_settings");
|
||||
final dynamic accountPicker = profileSettings["e_kreta_account_picker"];
|
||||
final dynamic accountIndex = accountPicker.accountIndex;
|
||||
if (accountIndex is int && accountIndex >= 0) {
|
||||
return accountIndex;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
TokenModel? pickActiveToken({
|
||||
required List<TokenModel> tokens,
|
||||
required dynamic settings,
|
||||
int? preferredStudentIdNorm,
|
||||
}) {
|
||||
if (tokens.isEmpty) return null;
|
||||
|
||||
if (preferredStudentIdNorm != null) {
|
||||
for (final token in tokens) {
|
||||
if (token.studentIdNorm == preferredStudentIdNorm) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final accountIndex = resolveActiveAccountIndex(settings);
|
||||
if (accountIndex < tokens.length) {
|
||||
return tokens[accountIndex];
|
||||
}
|
||||
|
||||
return tokens.first;
|
||||
}
|
||||
@@ -2,11 +2,10 @@ import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/api/client/live_activity_backend_client.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka/services/live_activity_manager.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/phone/screens/live_activity/live_activity_consent_screen.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -61,12 +60,12 @@ class LiveActivityService {
|
||||
static String? _getCurrentStudentId({KretaClient? client}) {
|
||||
try {
|
||||
if (client != null) {
|
||||
return client.model.studentId;
|
||||
return client.cache.token.username;
|
||||
}
|
||||
if (!initDone) {
|
||||
return null;
|
||||
}
|
||||
return initData.client.model.studentId;
|
||||
return initData.client!.cache.token.username;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting current studentId: $e');
|
||||
return null;
|
||||
@@ -444,7 +443,7 @@ class LiveActivityService {
|
||||
}
|
||||
|
||||
try {
|
||||
final client = initData.client;
|
||||
final client = initData.client!;
|
||||
|
||||
final enabled = await isEnabled(initData.settings, client);
|
||||
if (!enabled) {
|
||||
@@ -465,14 +464,13 @@ class LiveActivityService {
|
||||
_logger.info(
|
||||
'Background fetch: attempting to fetch fresh data from KRÉTA API',
|
||||
);
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
final timetableResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
if (true) {
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'Background fetch: successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
@@ -484,13 +482,12 @@ class LiveActivityService {
|
||||
'Background fetch: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
final cachedResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
if (true) {
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'Background fetch: successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
@@ -525,14 +522,13 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
final response = await client.getLessons(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -660,7 +656,7 @@ class LiveActivityService {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
try {
|
||||
final effectiveClient = client ?? initData.client;
|
||||
final effectiveClient = initData.client!;
|
||||
final studentId = _getCurrentStudentId(client: effectiveClient);
|
||||
if (studentId == null) {
|
||||
_logger.warning('Cannot change LiveActivity state: no current user');
|
||||
@@ -715,13 +711,8 @@ class LiveActivityService {
|
||||
}
|
||||
|
||||
final studentResp = await effectiveClient.getStudent();
|
||||
final activeToken = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: effectiveClient.model.studentIdNorm,
|
||||
);
|
||||
final studentName =
|
||||
studentResp.response?.name ?? activeToken?.studentId ?? "Student";
|
||||
final activeToken = initData.client!.cache.token;
|
||||
final studentName = null ?? activeToken?.username ?? "Student";
|
||||
|
||||
await onUserLogin(
|
||||
client: effectiveClient,
|
||||
@@ -889,14 +880,13 @@ class LiveActivityService {
|
||||
_logger.info(
|
||||
'onUserLogin: Attempting to fetch fresh timetable from KRÉTA API',
|
||||
);
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
final timetableResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
if (true) {
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully fetched ${allLessons.length} lessons from KRÉTA API',
|
||||
);
|
||||
@@ -908,13 +898,12 @@ class LiveActivityService {
|
||||
'onUserLogin: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
final cachedResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
if (true) {
|
||||
allLessons = <Lesson>[];
|
||||
_logger.info(
|
||||
'onUserLogin: Successfully loaded ${allLessons.length} lessons from cache',
|
||||
);
|
||||
@@ -944,14 +933,13 @@ class LiveActivityService {
|
||||
|
||||
List<Lesson> nextWeekBreakEvents = [];
|
||||
try {
|
||||
final nextWeekResponse = await client.getTimeTable(
|
||||
final nextWeekResponse = await client.getLessons(
|
||||
nextWeekStart,
|
||||
nextWeekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (nextWeekResponse.response != null) {
|
||||
nextWeekBreakEvents = nextWeekResponse.response!.where((lesson) {
|
||||
if (true) {
|
||||
nextWeekBreakEvents = <Lesson>[].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -1049,14 +1037,13 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
final response = await client.getLessons(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -1228,14 +1215,13 @@ class LiveActivityService {
|
||||
List<Lesson> allLessons = [];
|
||||
|
||||
try {
|
||||
final timetableResponse = await client.getTimeTable(
|
||||
final timetableResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (timetableResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(timetableResponse.response!);
|
||||
if (true) {
|
||||
allLessons = List<Lesson>.from([]);
|
||||
} else {
|
||||
throw Exception('KRÉTA API returned null response');
|
||||
}
|
||||
@@ -1244,13 +1230,12 @@ class LiveActivityService {
|
||||
'checkAndUpdateTimetable: KRÉTA API failed ($e), falling back to cache',
|
||||
);
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
final cachedResponse = await client.getLessons(
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
forceCache: true,
|
||||
);
|
||||
if (cachedResponse.response != null) {
|
||||
allLessons = List<Lesson>.from(cachedResponse.response!);
|
||||
if (true) {
|
||||
allLessons = <Lesson>[];
|
||||
} else {
|
||||
_logger.severe(
|
||||
'checkAndUpdateTimetable: Both API and cache failed',
|
||||
@@ -1274,14 +1259,13 @@ class LiveActivityService {
|
||||
|
||||
List<Lesson> nextWeekBreakEvents = [];
|
||||
try {
|
||||
final nextWeekResponse = await client.getTimeTable(
|
||||
final nextWeekResponse = await client.getLessons(
|
||||
nextWeekStart,
|
||||
nextWeekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (nextWeekResponse.response != null) {
|
||||
nextWeekBreakEvents = nextWeekResponse.response!.where((lesson) {
|
||||
if (true) {
|
||||
nextWeekBreakEvents = <Lesson>[].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -1375,14 +1359,13 @@ class LiveActivityService {
|
||||
|
||||
try {
|
||||
final candidateDayEnd = candidateDay.add(const Duration(days: 1));
|
||||
final response = await client.getTimeTable(
|
||||
final response = await client.getLessons(
|
||||
candidateDay,
|
||||
candidateDayEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final schoolLessons = response.response!.where((lesson) {
|
||||
if (true) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
@@ -1893,14 +1876,12 @@ class LiveActivityService {
|
||||
'Morning notifications re-enabled, fetching timetable to recreate notifications',
|
||||
);
|
||||
try {
|
||||
final client = initData.client;
|
||||
final client = initData.client!;
|
||||
final settingsStore = initData.settings;
|
||||
|
||||
final studentResp = await client.getStudent();
|
||||
final studentName =
|
||||
studentResp.response?.name ??
|
||||
client.model.studentId ??
|
||||
'Student';
|
||||
studentResp.name ?? client.cache.token.username ?? 'Student';
|
||||
|
||||
await checkAndUpdateTimetable(
|
||||
client: client,
|
||||
@@ -2014,16 +1995,10 @@ class LiveActivityService {
|
||||
);
|
||||
|
||||
try {
|
||||
final response = await client.getTimeTable(
|
||||
weekStart,
|
||||
weekEnd,
|
||||
forceCache: false,
|
||||
);
|
||||
final response = await client.getLessons(weekStart, weekEnd);
|
||||
|
||||
if (response.response != null && response.response!.isNotEmpty) {
|
||||
final weekLessons = response.response!;
|
||||
|
||||
final breakEvents = weekLessons.where((lesson) {
|
||||
if (true) {
|
||||
final breakEvents = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
final name = lesson.name.toLowerCase();
|
||||
return uid.contains('tanevrendjeesemeny') &&
|
||||
@@ -2035,26 +2010,26 @@ class LiveActivityService {
|
||||
name.contains('nem órarendi nap'));
|
||||
}).toList();
|
||||
|
||||
final schoolLessons = weekLessons.where((lesson) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
uid.contains('uresora');
|
||||
}).toList();
|
||||
|
||||
allLessons.addAll(weekLessons);
|
||||
allLessons.addAll([]);
|
||||
|
||||
if (breakEvents.isNotEmpty) {
|
||||
breakEvents.sort((a, b) => a.start.compareTo(b.start));
|
||||
lastBreakDay = breakEvents.last;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in week ${weeksSearched + 1}, last: ${lastBreakDay.name} on ${lastBreakDay.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in week ${weeksSearched + 1}, last: ${lastBreakDay} on ${lastBreakDay}',
|
||||
);
|
||||
} else if (schoolLessons.isNotEmpty) {
|
||||
schoolLessons.sort((a, b) => a.start.compareTo(b.start));
|
||||
firstSchoolDayAfterBreak = schoolLessons.first;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found first school day after break: ${firstSchoolDayAfterBreak.name} on ${firstSchoolDayAfterBreak.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found first school day after break: ${firstSchoolDayAfterBreak} on ${firstSchoolDayAfterBreak}',
|
||||
);
|
||||
break;
|
||||
} else {
|
||||
@@ -2084,15 +2059,10 @@ class LiveActivityService {
|
||||
}
|
||||
|
||||
try {
|
||||
final cachedResponse = await client.getTimeTable(
|
||||
weekStart,
|
||||
weekEnd,
|
||||
forceCache: true,
|
||||
);
|
||||
final cachedResponse = await client.getLessons(weekStart, weekEnd);
|
||||
|
||||
if (cachedResponse.response != null &&
|
||||
cachedResponse.response!.isNotEmpty) {
|
||||
final weekLessons = cachedResponse.response!;
|
||||
if (true) {
|
||||
final weekLessons = [];
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Loaded ${weekLessons.length} lessons from cache for week ${weeksSearched + 1}',
|
||||
);
|
||||
@@ -2109,26 +2079,26 @@ class LiveActivityService {
|
||||
name.contains('nem órarendi nap'));
|
||||
}).toList();
|
||||
|
||||
final schoolLessons = weekLessons.where((lesson) {
|
||||
final schoolLessons = [].where((lesson) {
|
||||
final uid = lesson.uid.toLowerCase();
|
||||
return uid.contains('orarendiora') ||
|
||||
uid.contains('tanitasiora') ||
|
||||
uid.contains('uresora');
|
||||
}).toList();
|
||||
|
||||
allLessons.addAll(weekLessons);
|
||||
allLessons.addAll([]);
|
||||
|
||||
if (breakEvents.isNotEmpty) {
|
||||
breakEvents.sort((a, b) => a.start.compareTo(b.start));
|
||||
lastBreakDay = breakEvents.last;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in cached week ${weeksSearched + 1}, last: ${lastBreakDay.name} on ${lastBreakDay.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found ${breakEvents.length} break event(s) in cached week ${weeksSearched + 1}, last: ${lastBreakDay} on ${lastBreakDay}',
|
||||
);
|
||||
} else if (schoolLessons.isNotEmpty) {
|
||||
schoolLessons.sort((a, b) => a.start.compareTo(b.start));
|
||||
firstSchoolDayAfterBreak = schoolLessons.first;
|
||||
_logger.info(
|
||||
'[GlobalBreakSearcher] Found first school day after break in cache: ${firstSchoolDayAfterBreak.name} on ${firstSchoolDayAfterBreak.date.split('T')[0]}',
|
||||
'[GlobalBreakSearcher] Found first school day after break in cache: ${firstSchoolDayAfterBreak} on ${firstSchoolDayAfterBreak}',
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
@@ -9,10 +10,9 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:watch_connectivity/watch_connectivity.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/services/wear_sync_cache.dart';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
|
||||
/// Helper class for Watch ↔ iPhone token sync (iOS) and Wear OS sync (Android).
|
||||
class WatchSyncHelper {
|
||||
@@ -60,42 +60,6 @@ class WatchSyncHelper {
|
||||
}
|
||||
}
|
||||
|
||||
static TokenModel? _resolveCurrentToken({
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) {
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
if (effectiveTokens == null || effectiveTokens.isEmpty) return null;
|
||||
|
||||
final preferredStudentIdNorm = client?.model.studentIdNorm;
|
||||
if (preferredStudentIdNorm != null) {
|
||||
for (final token in effectiveTokens) {
|
||||
if (token.studentIdNorm == preferredStudentIdNorm) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (initDone) {
|
||||
return pickActiveToken(
|
||||
tokens: effectiveTokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: preferredStudentIdNorm,
|
||||
);
|
||||
}
|
||||
|
||||
return effectiveTokens.first;
|
||||
}
|
||||
|
||||
static int? _resolveExpectedStudentIdNorm({
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) {
|
||||
final fromClient = client?.model.studentIdNorm;
|
||||
if (fromClient != null) return fromClient;
|
||||
return _resolveCurrentToken(tokens: tokens, client: client)?.studentIdNorm;
|
||||
}
|
||||
|
||||
static int? _asInt(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is double) return value.toInt();
|
||||
@@ -225,8 +189,8 @@ class WatchSyncHelper {
|
||||
? token.updatedAtMs!
|
||||
: nowMs;
|
||||
final payload = <String, dynamic>{
|
||||
'studentId': token.studentId,
|
||||
'studentIdNorm': token.studentIdNorm,
|
||||
'studentId': token.username,
|
||||
'studentIdNorm': token.key,
|
||||
'iss': token.iss,
|
||||
'idToken': token.idToken,
|
||||
'accessToken': token.accessToken,
|
||||
@@ -448,9 +412,6 @@ class WatchSyncHelper {
|
||||
await isar.tokenModels.clear();
|
||||
});
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = [];
|
||||
}
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
|
||||
await prefs.setBool(_iosFreshInstallHandledKey, true);
|
||||
@@ -523,7 +484,6 @@ class WatchSyncHelper {
|
||||
try {
|
||||
final recovered = await checkAndRecoverFromiCloud(
|
||||
isar: initData.isar,
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
|
||||
@@ -532,10 +492,7 @@ class WatchSyncHelper {
|
||||
'[WatchSync] Token recovered from iCloud, reauth flag cleared',
|
||||
);
|
||||
} else {
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
final token = initData.client!.cache.token;
|
||||
final expiryDate = token?.expiryDate;
|
||||
if (expiryDate != null && expiryDate.isAfter(DateTime.now())) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
@@ -550,15 +507,12 @@ class WatchSyncHelper {
|
||||
}
|
||||
|
||||
static Map<String, dynamic>? _getTokenForWatch() {
|
||||
if (!initDone || initData.tokens.isEmpty) {
|
||||
if (!initDone) {
|
||||
debugPrint('[WatchSync] No token available');
|
||||
return {'error': 'no_token'};
|
||||
}
|
||||
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
final token = initData.client!.cache.token;
|
||||
if (token == null) {
|
||||
debugPrint('[WatchSync] No active token available');
|
||||
return {'error': 'no_token'};
|
||||
@@ -571,7 +525,7 @@ class WatchSyncHelper {
|
||||
return {'error': 'token_incomplete'};
|
||||
}
|
||||
|
||||
if (initData.client.needsReauth) {
|
||||
if (initData.client!.needsReauth) {
|
||||
debugPrint('[WatchSync] iPhone needs reauth');
|
||||
return {'error': 'needsReauth'};
|
||||
}
|
||||
@@ -730,14 +684,8 @@ class WatchSyncHelper {
|
||||
return {'success': false, 'error': 'no_student_id_norm'};
|
||||
}
|
||||
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
final currentToken = initData.client!.cache.token;
|
||||
|
||||
final watchExpiryDate = DateTime.fromMillisecondsSinceEpoch(watchExpiry);
|
||||
if (!_isAccessTokenUsable(watchExpiryDate, skew: const Duration())) {
|
||||
@@ -756,7 +704,7 @@ class WatchSyncHelper {
|
||||
watchStudentIdNorm == expectedStudentIdNorm;
|
||||
if (isForActiveAccount &&
|
||||
currentToken != null &&
|
||||
currentToken.studentIdNorm == watchStudentIdNorm) {
|
||||
currentToken.key == watchStudentIdNorm) {
|
||||
if (!_isIncomingTokenNewerThanCurrent(
|
||||
incomingExpiry: watchExpiryDate,
|
||||
incomingIdToken: watchIdToken,
|
||||
@@ -792,9 +740,8 @@ class WatchSyncHelper {
|
||||
await initData.isar.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
initData.tokens = await initData.isar.tokenModels.where().findAll();
|
||||
if (isForActiveAccount) {
|
||||
initData.client.model = newToken;
|
||||
initData.client!.cache.token = newToken;
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
} else {
|
||||
debugPrint(
|
||||
@@ -894,7 +841,6 @@ class WatchSyncHelper {
|
||||
}
|
||||
|
||||
final effectiveIsar = isar ?? (initDone ? initData.isar : null);
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
|
||||
if (effectiveIsar == null) {
|
||||
@@ -921,10 +867,7 @@ class WatchSyncHelper {
|
||||
return false;
|
||||
}
|
||||
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
|
||||
final iCloudStudentIdNorm = tokenData['studentIdNorm'] as int?;
|
||||
if (expectedStudentIdNorm != null &&
|
||||
@@ -959,10 +902,7 @@ class WatchSyncHelper {
|
||||
final iCloudIdToken = tokenData['idToken'] as String?;
|
||||
final iCloudRefreshToken = tokenData['refreshToken'] as String?;
|
||||
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final currentToken = initData.client!.cache.token;
|
||||
final localExpiry = currentToken?.expiryDate;
|
||||
final shouldAccept = currentToken == null
|
||||
? true
|
||||
@@ -997,22 +937,16 @@ class WatchSyncHelper {
|
||||
await effectiveIsar.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
final updatedTokens = await effectiveIsar.tokenModels.where().findAll();
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = updatedTokens;
|
||||
}
|
||||
|
||||
if (effectiveClient != null &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm)) {
|
||||
effectiveClient.model = newToken;
|
||||
newToken.key == expectedStudentIdNorm)) {
|
||||
effectiveClient.cache.token = newToken;
|
||||
}
|
||||
|
||||
final shouldClearReauth =
|
||||
!iCloudAccessExpired &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm);
|
||||
newToken.key == expectedStudentIdNorm);
|
||||
if (shouldClearReauth) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
}
|
||||
@@ -1071,16 +1005,7 @@ class WatchSyncHelper {
|
||||
List<TokenModel>? tokens,
|
||||
KretaClient? client,
|
||||
}) async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
final effectiveIsar = isar ?? (initDone ? initData.isar : null);
|
||||
final effectiveTokens = tokens ?? (initDone ? initData.tokens : null);
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
|
||||
if (effectiveIsar == null || effectiveTokens == null) {
|
||||
debugPrint('[WatchSync] Cannot sync: no isar or tokens available');
|
||||
return;
|
||||
}
|
||||
if (!Platform.isIOS || !initDone) return;
|
||||
|
||||
try {
|
||||
debugPrint('[WatchSync] Requesting token from Watch...');
|
||||
@@ -1089,14 +1014,8 @@ class WatchSyncHelper {
|
||||
null,
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
final expectedStudentIdNorm = _resolveExpectedStudentIdNorm(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final currentToken = _resolveCurrentToken(
|
||||
tokens: effectiveTokens,
|
||||
client: effectiveClient,
|
||||
);
|
||||
final expectedStudentIdNorm = initData.client!.cache.token.key;
|
||||
final currentToken = initData.client!.cache.token;
|
||||
|
||||
if (result == null) {
|
||||
debugPrint('[WatchSync] No response from Watch');
|
||||
@@ -1213,24 +1132,14 @@ class WatchSyncHelper {
|
||||
watchUpdatedAtMs ?? DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
|
||||
await effectiveIsar.writeTxn(() async {
|
||||
await effectiveIsar.tokenModels.put(newToken);
|
||||
await isarInit.writeTxn(() async {
|
||||
await isarInit.tokenModels.put(newToken);
|
||||
});
|
||||
|
||||
final updatedTokens = await effectiveIsar.tokenModels.where().findAll();
|
||||
|
||||
if (initDone) {
|
||||
initData.tokens = updatedTokens;
|
||||
}
|
||||
|
||||
if (effectiveClient != null &&
|
||||
(expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm)) {
|
||||
effectiveClient.model = newToken;
|
||||
}
|
||||
initData.client!.cache.token = newToken;
|
||||
|
||||
if (expectedStudentIdNorm == null ||
|
||||
newToken.studentIdNorm == expectedStudentIdNorm) {
|
||||
newToken.key == expectedStudentIdNorm) {
|
||||
if (initDone) initData.reauthCubit?.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
@@ -8,11 +9,10 @@ import 'package:watch_connectivity/watch_connectivity.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/data/models/generic_cache_model.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka/data/models/timetable_cache_model.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/services/wear_sync_cache.dart';
|
||||
|
||||
/// Background isolate entrypoint for Wear sync (Android).
|
||||
@@ -29,30 +29,13 @@ void wearSyncBackgroundEntrypoint() {
|
||||
final appDirPath = args?['appDirPath'] as String?;
|
||||
if (cachePath == null || appDirPath == null) return null;
|
||||
try {
|
||||
final isar = await Isar.open([
|
||||
TokenModelSchema,
|
||||
GenericCacheModelSchema,
|
||||
TimetableCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
HomeworkDoneModelSchema,
|
||||
], directory: appDirPath);
|
||||
final tokens = await isar.tokenModels.where().findAll();
|
||||
await isar.close();
|
||||
await initDB();
|
||||
final tokens = await isarInit.tokenModels.where().findAll();
|
||||
if (tokens.isEmpty) return null;
|
||||
final token = tokens.first;
|
||||
final isar2 = await Isar.open([
|
||||
TokenModelSchema,
|
||||
GenericCacheModelSchema,
|
||||
TimetableCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
HomeworkDoneModelSchema,
|
||||
], directory: appDirPath);
|
||||
final reauthCubit = ReauthCubit();
|
||||
final client = KretaClient(token, isar2, reauthCubit);
|
||||
final client = KretaClient(token, reauthCubit);
|
||||
final payload = await buildWearSyncPayload(client);
|
||||
await isar2.close();
|
||||
if (payload == null) return null;
|
||||
await writeWearSyncCache(cachePath, payload);
|
||||
final wc = WatchConnectivity();
|
||||
|
||||
@@ -28,25 +28,11 @@ const String wearSyncCacheFileName = 'wear_sync_cache.json';
|
||||
/// Builds the sync payload (same shape as init_data / sync_data): timetable (2 weeks), grades, lastSyncAt.
|
||||
Future<Map<String, dynamic>?> buildWearSyncPayload(KretaClient client) async {
|
||||
final (start, end) = getWearSyncTimetableRange();
|
||||
final timetableResp = await client.getTimeTable(
|
||||
start,
|
||||
end,
|
||||
forceCache: false,
|
||||
);
|
||||
if (timetableResp.err != null && timetableResp.response == null) {
|
||||
return null;
|
||||
}
|
||||
final gradesResp = await client.getGrades(forceCache: false);
|
||||
if (gradesResp.err != null && gradesResp.response == null) {
|
||||
return null;
|
||||
}
|
||||
final timetableResp = await client.getLessons(start, end);
|
||||
final gradesResp = await client.getGrades();
|
||||
final now = timeNow();
|
||||
final timetable = (timetableResp.response ?? <Lesson>[])
|
||||
.map((l) => l.toJson())
|
||||
.toList();
|
||||
final grades = (gradesResp.response ?? <Grade>[])
|
||||
.map((g) => g.toJson())
|
||||
.toList();
|
||||
final timetable = (<Lesson>[]).map((l) => l.toJson()).toList();
|
||||
final grades = (<Grade>[]).map((g) => g.toJson()).toList();
|
||||
return {
|
||||
'lastSyncAt': now.toUtc().toIso8601String(),
|
||||
'timetable': timetable,
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka/ui/phone/widgets/info_card.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:firka_common/ui/shared/grade_small_card.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
@@ -19,9 +27,9 @@ import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/grade.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
|
||||
Future<void> showFirkaBottomSheet(
|
||||
BuildContext context,
|
||||
@@ -78,12 +86,13 @@ Future<void> showFirkaBottomSheet(
|
||||
Future<void> showLessonBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Lesson lesson,
|
||||
LessonCacheModel lesson,
|
||||
Color accent,
|
||||
Color secondary,
|
||||
Color bgColor,
|
||||
Test? test,
|
||||
) async {
|
||||
// we dont like events
|
||||
assert(lesson.type != TimetableConsts.event);
|
||||
final statsForNerdsEnabled = data.settings
|
||||
.group("settings")
|
||||
.subGroup("developer")
|
||||
@@ -96,8 +105,8 @@ Future<void> showLessonBottomSheet(
|
||||
if (statsForNerdsEnabled) {
|
||||
final stats =
|
||||
"${data.l10n.stats_date}: ${lesson.start.isAfter(y2k) ? lesson.start.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n"
|
||||
"${data.l10n.stats_created_at}: ${lesson.createdAt.isAfter(y2k) ? lesson.createdAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n"
|
||||
"${data.l10n.stats_last_mod}: ${lesson.lastModifiedAt.isAfter(y2k) ? lesson.lastModifiedAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}";
|
||||
"${data.l10n.stats_created_at}: ${lesson.createdAt.isAfter(y2k) ? lesson.createdAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}\n";
|
||||
//"${data.l10n.stats_last_mod}: ${lesson.lastModifiedAt.isAfter(y2k) ? lesson.lastModifiedAt.format(data.l10n, FormatMode.yyyymmddhhmmss) : "N/A"}";
|
||||
statsForNerds = Text(
|
||||
stats,
|
||||
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
|
||||
@@ -106,65 +115,62 @@ Future<void> showLessonBottomSheet(
|
||||
showFirkaBottomSheet(context, [
|
||||
Row(
|
||||
children: [
|
||||
lesson.lessonNumber == null
|
||||
? SizedBox()
|
||||
: SizedBox(
|
||||
SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/icons/subtract.svg",
|
||||
color: bgColor,
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/icons/subtract.svg",
|
||||
color: bgColor,
|
||||
width: 24,
|
||||
height: 24,
|
||||
),
|
||||
Text(
|
||||
lesson.lessonNumber!.toString(),
|
||||
style: appStyle.fonts.B_16R.apply(color: secondary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_16R.apply(color: secondary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledCircle(
|
||||
diameter: 40,
|
||||
color: bgColor,
|
||||
child: ClassIconWidget.subject(
|
||||
subject: lesson.subject!,
|
||||
child: ClassIconWidget(
|
||||
subject: lesson.subject.loadAndGet()!,
|
||||
color: accent,
|
||||
size: 26,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
if (lesson.roomName != null)
|
||||
Card(
|
||||
shadowColor: Colors.transparent,
|
||||
color: appStyle.colors.a15p,
|
||||
margin: EdgeInsets.all(0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
lesson.roomName!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
Card(
|
||||
shadowColor: Colors.transparent,
|
||||
color: appStyle.colors.a15p,
|
||||
margin: EdgeInsets.all(0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
lesson.roomName!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
"${lesson.name} ${statsForNerdsEnabled ? "(${lesson.classGroup?.name ?? ''})" : ""}",
|
||||
"${lesson.name} ${statsForNerdsEnabled ? "(${lesson.subject.loadAndGet()!.name})" : ""}",
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -173,7 +179,7 @@ Future<void> showLessonBottomSheet(
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
lesson.teacher ?? 'N/A',
|
||||
lesson.teacher!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
decoration: lesson.substituteTeacher != null
|
||||
@@ -208,7 +214,7 @@ Future<void> showLessonBottomSheet(
|
||||
SizedBox(
|
||||
width: MediaQuery.of(context).size.width * 0.7,
|
||||
child: Text(
|
||||
lesson.theme ?? 'N/A',
|
||||
lesson.topic ?? 'N/A',
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -222,7 +228,8 @@ Future<void> showLessonBottomSheet(
|
||||
],
|
||||
),
|
||||
SizedBox(height: 6),
|
||||
if (test != null) InfoCard.testDesc(test),
|
||||
if (lesson.test.loadAndGet() != null)
|
||||
InfoCard.testDesc(lesson.test.loadAndGet()!),
|
||||
SizedBox(height: 16),
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
@@ -249,11 +256,11 @@ Future<void> showOmissionBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
String description,
|
||||
List<Omission> omissions,
|
||||
List<OmissionCacheModel> omissions,
|
||||
) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
Text(
|
||||
omissions.first.date.format(data.l10n, FormatMode.yyyymmdd),
|
||||
omissions.first.createdAt.format(data.l10n, FormatMode.yyyymmdd),
|
||||
style: appStyle.fonts.H_18px.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
@@ -264,94 +271,14 @@ Future<void> showOmissionBottomSheet(
|
||||
SizedBox(height: 2),
|
||||
LimitedBox(
|
||||
maxHeight: 336,
|
||||
child: ListView.builder(
|
||||
child: ListView.separated(
|
||||
itemCount: omissions.length,
|
||||
separatorBuilder: (ctx, i) {
|
||||
return const SizedBox(height: 10);
|
||||
},
|
||||
itemBuilder: (b, i) {
|
||||
final o = omissions[i];
|
||||
return FirkaCard.single(
|
||||
height: 64,
|
||||
margin: EdgeInsets.only(bottom: 10),
|
||||
padding: EdgeInsets.only(left: 14, right: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
"assets/icons/subtract.svg",
|
||||
color: appStyle.colors.a15p,
|
||||
width: 18,
|
||||
height: 18,
|
||||
),
|
||||
Text(
|
||||
o.lesson!.classNo?.toString() ?? "-",
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledCircle(
|
||||
diameter: 36,
|
||||
color: appStyle.colors.a15p,
|
||||
child: ClassIconWidget(
|
||||
uid: o.subject.uid,
|
||||
className: o.subject.name,
|
||||
category: o.subject.name,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
o.subject.name,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Text(
|
||||
o.teacher,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
o.lesson!.start.format(data.l10n, FormatMode.hmm),
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
o.lesson!.end.format(data.l10n, FormatMode.hmm),
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return LessonWidget(data, o.lesson.loadAndGet()!);
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -361,9 +288,11 @@ Future<void> showOmissionBottomSheet(
|
||||
Future<void> showTestBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Test test,
|
||||
TestCacheModel test,
|
||||
) async {
|
||||
final date = test.date;
|
||||
final lesson = test.lesson.loadAndGet()!;
|
||||
final subject = lesson.subject.loadAndGet()!;
|
||||
final date = lesson.start;
|
||||
final formattedDate =
|
||||
"${date.format(data.l10n, FormatMode.yearly).firstUpper()}, ${DateFormat.EEEE(data.l10n.localeName).format(date).firstUpper()}";
|
||||
|
||||
@@ -385,13 +314,13 @@ Future<void> showTestBottomSheet(
|
||||
spacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
"${test.theme}",
|
||||
test.topic ?? test.method,
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
test.method.description,
|
||||
test.method,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -438,7 +367,7 @@ Future<void> showTestBottomSheet(
|
||||
height: 18,
|
||||
),
|
||||
Text(
|
||||
test.lessonNumber.toString(),
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
@@ -451,9 +380,7 @@ Future<void> showTestBottomSheet(
|
||||
diameter: 36,
|
||||
color: appStyle.colors.a15p,
|
||||
child: ClassIconWidget(
|
||||
uid: test.uid,
|
||||
className: test.subjectName,
|
||||
category: test.subject.name,
|
||||
subject: subject,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
),
|
||||
@@ -461,7 +388,7 @@ Future<void> showTestBottomSheet(
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
test.subject.name,
|
||||
subject.name,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -477,7 +404,7 @@ Future<void> showTestBottomSheet(
|
||||
Future<void> showGradeBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Grade grade,
|
||||
GradeCacheModel grade,
|
||||
) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
grade.numericValue == null
|
||||
@@ -494,7 +421,7 @@ Future<void> showGradeBottomSheet(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
grade.strValue,
|
||||
grade.textValue,
|
||||
style: appStyle.fonts.H_18px.apply(
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
@@ -505,12 +432,12 @@ Future<void> showGradeBottomSheet(
|
||||
: GradeWidget(grade, size: 40),
|
||||
SizedBox(height: 20),
|
||||
Text(
|
||||
(grade.topic ?? grade.type.description).firstUpper(),
|
||||
(grade.topic ?? grade.type).firstUpper(),
|
||||
style: appStyle.fonts.H_18px.apply(color: appStyle.colors.textPrimary),
|
||||
),
|
||||
grade.mode != null
|
||||
? Text(
|
||||
grade.mode!.description,
|
||||
grade.mode!,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -518,11 +445,11 @@ Future<void> showGradeBottomSheet(
|
||||
: SizedBox(),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
grade.recordDate.format(data.l10n, FormatMode.yyyymmdd),
|
||||
grade.writtenAt.format(data.l10n, FormatMode.yyyymmdd),
|
||||
style: appStyle.fonts.B_14R.apply(color: appStyle.colors.textSecondary),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeSmallCard([], null, grade.subject),
|
||||
GradeSmallCard(null, null, grade.subject.loadAndGet()!),
|
||||
SizedBox(height: 10),
|
||||
FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
@@ -531,13 +458,13 @@ Future<void> showGradeBottomSheet(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
"${data.l10n.grade_teacherName}${grade.teacher}",
|
||||
"${data.l10n.grade_teacherName}${grade.teacherName}",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${data.l10n.tt_added}${grade.creationDate.format(data.l10n, FormatMode.yyyymmdd)}",
|
||||
"${data.l10n.tt_added}${grade.createdAt.format(data.l10n, FormatMode.yyyymmdd)}",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -562,7 +489,7 @@ Future<void> showGradeBottomSheet(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: grade.subject);
|
||||
context.go('/grades/subject', extra: grade.subject.loadAndGet());
|
||||
},
|
||||
),
|
||||
]);
|
||||
@@ -571,8 +498,9 @@ Future<void> showGradeBottomSheet(
|
||||
Future<void> showHomeworkBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Homework homework,
|
||||
HomeworkCacheModel homework,
|
||||
) async {
|
||||
final subject = homework.subject.loadAndGet()!;
|
||||
showFirkaBottomSheet(context, [
|
||||
Text(
|
||||
data.l10n.homework,
|
||||
@@ -584,7 +512,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
style: appStyle.fonts.B_14R.apply(color: appStyle.colors.textSecondary),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeSmallCard([], null, homework.subject),
|
||||
GradeSmallCard(null, null, subject),
|
||||
SizedBox(height: 20),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
@@ -602,42 +530,34 @@ Future<void> showHomeworkBottomSheet(
|
||||
),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
FutureBuilder<bool>(
|
||||
future: isHomeworkDone(data.isar, homework.uid),
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return SizedBox(); // or a loading indicator
|
||||
}
|
||||
|
||||
final done = snapshot.data!;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
left: [],
|
||||
center: [
|
||||
Text(
|
||||
!done ? data.l10n.mark_as_done : data.l10n.mark_as_not_done,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimaryLight,
|
||||
),
|
||||
),
|
||||
],
|
||||
color: appStyle.colors.accent,
|
||||
Column(
|
||||
children: [
|
||||
GestureDetector(
|
||||
child: FirkaCard(
|
||||
margin: EdgeInsets.all(0),
|
||||
left: [],
|
||||
center: [
|
||||
Text(
|
||||
!homework.isDone
|
||||
? data.l10n.mark_as_done
|
||||
: data.l10n.mark_as_not_done,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimaryLight,
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
context.read<HomeRefreshCubit>().requestRefresh();
|
||||
Navigator.pop(context);
|
||||
!done
|
||||
? markAsDone(data.isar, homework.uid)
|
||||
: markAsNotDone(data.isar, homework.uid);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
],
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
onTap: () {
|
||||
data.isar.writeTxnSync(() {
|
||||
homework.isDone = true;
|
||||
data.isar.homeworkCacheModels.putSync(homework);
|
||||
});
|
||||
context.read<HomeRefreshCubit>().requestRefresh();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
GestureDetector(
|
||||
@@ -655,7 +575,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
color: appStyle.colors.buttonSecondaryFill,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/home/subject', extra: homework.subject);
|
||||
context.go('/home/subject', extra: subject);
|
||||
},
|
||||
),
|
||||
]);
|
||||
@@ -664,7 +584,7 @@ Future<void> showHomeworkBottomSheet(
|
||||
Future<void> showGradeCalculatorBottomSheet(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Subject subject, {
|
||||
SubjectCacheModel subject, {
|
||||
void Function(int grade, int weight)? onAdd,
|
||||
}) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
@@ -674,7 +594,7 @@ Future<void> showGradeCalculatorBottomSheet(
|
||||
|
||||
class _GradeCalculatorSheetContent extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
final Subject subject;
|
||||
final SubjectCacheModel subject;
|
||||
final void Function(int grade, int weight)? onAdd;
|
||||
|
||||
const _GradeCalculatorSheetContent({
|
||||
@@ -862,7 +782,7 @@ class _GradeCalculatorSheetContentState
|
||||
Future<void> showSubjectBottomSheetSettings(
|
||||
BuildContext context,
|
||||
AppInitialization data,
|
||||
Subject subject, {
|
||||
SubjectCacheModel subject, {
|
||||
void Function(int grade, int weight)? onAddFromCalculator,
|
||||
}) async {
|
||||
showFirkaBottomSheet(context, [
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/firka_card.dart';
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/firka_shadow.dart';
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/grade.dart';
|
||||
@@ -1 +0,0 @@
|
||||
export 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
@@ -5,8 +5,8 @@ import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/theme_cubit.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/ui/components/firka_shadow.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/ui/components/firka_shadow.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/widgets/login_webview.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void showReauthBottomSheet(
|
||||
@@ -9,18 +10,6 @@ void showReauthBottomSheet(
|
||||
AppInitialization data,
|
||||
String message,
|
||||
) {
|
||||
final accountPicker =
|
||||
(data.settings.group("profile_settings")["e_kreta_account_picker"]
|
||||
as SettingsKretenAccountPicker);
|
||||
|
||||
final currentToken =
|
||||
data.tokens.isNotEmpty && accountPicker.accountIndex < data.tokens.length
|
||||
? data.tokens[accountPicker.accountIndex]
|
||||
: null;
|
||||
|
||||
final username = currentToken?.studentId;
|
||||
final schoolId = currentToken?.iss;
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
elevation: 100,
|
||||
@@ -54,8 +43,8 @@ void showReauthBottomSheet(
|
||||
Expanded(
|
||||
child: LoginWebviewWidget(
|
||||
data,
|
||||
username: username,
|
||||
schoolId: schoolId,
|
||||
username: data.client!.cache.token.username,
|
||||
schoolId: data.client!.cache.token.iss,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -4,7 +4,7 @@ import 'package:firka/services/wear_sync_cache.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
void showWearBottomSheet(
|
||||
@@ -12,7 +12,7 @@ void showWearBottomSheet(
|
||||
AppInitialization data,
|
||||
String model,
|
||||
) async {
|
||||
final payload = await buildWearSyncPayload(data.client);
|
||||
final payload = await buildWearSyncPayload(data.client!);
|
||||
if (payload == null) return;
|
||||
if (!context.mounted) return;
|
||||
|
||||
@@ -66,12 +66,12 @@ class _WearPairSheetContentState extends State<_WearPairSheetContent> {
|
||||
|
||||
void _onPairTap() {
|
||||
setState(() => _syncing = true);
|
||||
final m = widget.data.client.model;
|
||||
final m = widget.data.client!.cache.token;
|
||||
WatchSyncHelper.sendMessageToWatch({
|
||||
'id': 'init_data',
|
||||
'auth': {
|
||||
'studentId': m.studentId,
|
||||
'studentIdNorm': m.studentIdNorm,
|
||||
'studentId': m.username,
|
||||
'studentIdNorm': m.key,
|
||||
'iss': m.iss,
|
||||
'idToken': m.idToken,
|
||||
'accessToken': m.accessToken,
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_chart.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_summary_bar.dart';
|
||||
import 'package:firka/ui/shared/grade_small_card.dart';
|
||||
@@ -11,7 +18,6 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
@@ -30,297 +36,224 @@ class HomeGradesScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeGradesScreen extends FirkaState<HomeGradesScreen> {
|
||||
ApiResponse<List<Grade>>? grades;
|
||||
ApiResponse<List<Lesson>>? week;
|
||||
ApiResponse<List<ClassGroup>>? classGroups;
|
||||
ApiResponse<List<SubjectAverage>>? lessons;
|
||||
ApiResponse<List<ClassGroupSubjectAverage>>? classAvgs;
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
var now = timeNow();
|
||||
var start = now.subtract(Duration(days: now.weekday - 1));
|
||||
var end = start.add(Duration(days: 6));
|
||||
|
||||
grades = await widget.data.client.getGrades(forceCache: false);
|
||||
week = await widget.data.client.getTimeTable(start, end, forceCache: false);
|
||||
classGroups = await widget.data.client.getClassGroups(forceCache: false);
|
||||
if (classGroups?.response?.isNotEmpty ?? false) {
|
||||
var group = classGroups!.response!.first;
|
||||
lessons = await widget.data.client.getSubjectAverage(
|
||||
group,
|
||||
forceCache: false,
|
||||
);
|
||||
classAvgs = await widget.data.client.getClassGroupAverages(
|
||||
group,
|
||||
forceCache: false,
|
||||
);
|
||||
await Future.delayed(Duration(milliseconds: 100));
|
||||
}
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
(() async {
|
||||
var now = timeNow();
|
||||
var start = now.subtract(Duration(days: now.weekday - 1));
|
||||
var end = start.add(Duration(days: 6));
|
||||
|
||||
grades = await widget.data.client.getGrades();
|
||||
week = await widget.data.client.getTimeTable(start, end);
|
||||
classGroups = await widget.data.client.getClassGroups();
|
||||
if (classGroups?.response?.isNotEmpty ?? false) {
|
||||
var group = classGroups!.response!.first;
|
||||
lessons = await widget.data.client.getSubjectAverage(group);
|
||||
classAvgs = await widget.data.client.getClassGroupAverages(group);
|
||||
await Future.delayed(Duration(milliseconds: 100));
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
})();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<HomeRefreshCubit, HomeRefreshState>(
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (grades == null ||
|
||||
lessons == null ||
|
||||
classAvgs == null ||
|
||||
week == null) {
|
||||
return SizedBox(
|
||||
height: MediaQuery.of(context).size.height / 1.35,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [SizedBox(), DelayedSpinnerWidget(), SizedBox()],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
final allGrades = grades!.response!;
|
||||
final allLessons = lessons!.response!;
|
||||
final allGrades = widget.data.client!.cache.getGrades().findAllSync();
|
||||
|
||||
final subjectAverage = allGrades.getSubjectAverage();
|
||||
final roundedSubjectAverage = allGrades.getRoundedSubjectAverage();
|
||||
final classAverages = classAvgs!.response!
|
||||
.map((c) => c.classGroupAverage)
|
||||
.nonNulls;
|
||||
final subjectAverage = allGrades.getSubjectAverage();
|
||||
final roundedSubjectAverage = allGrades.getRoundedSubjectAverage();
|
||||
final classAverages = widget.data.client!.cache
|
||||
.getClassAverages()
|
||||
.findAllSync();
|
||||
|
||||
double? classAverage = classAverages.isNotEmpty
|
||||
? classAverages.reduce((f, s) => f + s) / classAverages.length
|
||||
: null;
|
||||
double? classAverage = classAverages.isNotEmpty
|
||||
? classAverages.map((c) => c.classAverage).reduce((f, s) => f + s) /
|
||||
classAverages.length
|
||||
: null;
|
||||
|
||||
final Set<Subject> subjects = HashSet(
|
||||
hashCode: (s) => s.uid.hashCode,
|
||||
equals: (s, s2) => s.uid == s2.uid,
|
||||
);
|
||||
final List<Widget> gradeCards = [];
|
||||
final List<SubjectCacheModel> subjects = widget.data.client!.cache
|
||||
.getSubjects()
|
||||
.findAllSync();
|
||||
final List<Widget> gradeCards = [];
|
||||
|
||||
allGrades.map((g) => g.subject).forEach(subjects.add);
|
||||
allLessons.map((l) => l.subject).forEach(subjects.add);
|
||||
|
||||
for (var subject
|
||||
in subjects.toList()..sort((s1, s2) => s1.name.compareTo(s2.name))) {
|
||||
gradeCards.add(
|
||||
GestureDetector(
|
||||
child: GradeSmallCard(
|
||||
allGrades,
|
||||
classAvgs!.response!
|
||||
.firstWhereOrNull((s) => s.subject.uid == subject.uid)
|
||||
?.classGroupAverage,
|
||||
subject,
|
||||
),
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: subject);
|
||||
},
|
||||
for (var subject
|
||||
in subjects.toList()..sort((s1, s2) => s1.name.compareTo(s2.name))) {
|
||||
gradeCards.add(
|
||||
GestureDetector(
|
||||
child: GradeSmallCard(
|
||||
allGrades.getAverageBySubject(subject),
|
||||
subject.classAverage.loadAndGet()?.classAverage,
|
||||
subject,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.subjects,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeChartWithInteraction(grades: allGrades),
|
||||
SizedBox(height: 10),
|
||||
GradeSummaryBar(grades: allGrades, l10n: widget.data.l10n),
|
||||
SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.your_subjects,
|
||||
style: appStyle.fonts.H_14px.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Column(
|
||||
spacing: 16,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: gradeCards,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
widget.data.l10n.data,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (subjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(subjectAverage).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
subjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(subjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg_rounded,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (roundedSubjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(
|
||||
roundedSubjectAverage,
|
||||
).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
roundedSubjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(roundedSubjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (classAverage != null)
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
classAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_n,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Text(
|
||||
week!.response!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.type.name != TimetableConsts.event,
|
||||
)
|
||||
.length
|
||||
.toString(),
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
onTap: () {
|
||||
context.go('/grades/subject', extra: subject);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.subjects,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
GradeChartWithInteraction(grades: allGrades),
|
||||
SizedBox(height: 10),
|
||||
GradeSummaryBar(grades: allGrades, l10n: widget.data.l10n),
|
||||
SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
children: [
|
||||
Text(
|
||||
widget.data.l10n.your_subjects,
|
||||
style: appStyle.fonts.H_14px.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Column(
|
||||
spacing: 16,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: gradeCards,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
widget.data.l10n.data,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (subjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(subjectAverage).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
subjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(subjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.subject_avg_rounded,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
if (roundedSubjectAverage != null)
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: getGradeColor(
|
||||
roundedSubjectAverage,
|
||||
).withAlpha(38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
roundedSubjectAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(roundedSubjectAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (classAverage != null)
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_avg,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 26,
|
||||
decoration: ShapeDecoration(
|
||||
color: Colors.transparent,
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
classAverage.toStringAsFixed(2),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: getGradeColor(classAverage),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
/*
|
||||
FirkaCard(
|
||||
left: [
|
||||
Text(
|
||||
widget.data.l10n.class_n,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Text(
|
||||
week!.response!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.type.name != TimetableConsts.event,
|
||||
)
|
||||
.length
|
||||
.toString(),
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),*/
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import 'package:firka/ui/phone/widgets/grade_summary_bar.dart';
|
||||
import 'package:firka/ui/phone/widgets/info_card.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/teacher_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/common_bottom_sheets.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/phone/pages/home/home_grades.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_chart.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
@@ -14,6 +15,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
import 'package:firka/app/app_state.dart';
|
||||
@@ -22,77 +24,56 @@ import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class HomeGradesSubjectScreen extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
final Subject subject;
|
||||
final SubjectCacheModel subject;
|
||||
final String teacherName;
|
||||
final Iterable<GradeCacheModel> grades;
|
||||
|
||||
const HomeGradesSubjectScreen(this.subject, this.data, {super.key});
|
||||
factory HomeGradesSubjectScreen.subject(SubjectCacheModel subject) {
|
||||
return HomeGradesSubjectScreen(
|
||||
subject,
|
||||
initData.client!.cache
|
||||
.getGrades()
|
||||
.subject((s) => s.cacheKeyEqualTo(subject.cacheKey))
|
||||
.sortByCreatedAtDesc()
|
||||
.findAllSync(),
|
||||
);
|
||||
}
|
||||
|
||||
HomeGradesSubjectScreen(this.subject, this.grades, {super.key})
|
||||
: teacherName = subject.teachers
|
||||
.loadAndGet()
|
||||
.map((t) => "${t.name} (${t.classGroup.loadAndGet()!.type})")
|
||||
.join("\n");
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _HomeGradesSubjectScreen();
|
||||
}
|
||||
|
||||
class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
Iterable<Grade>? grades;
|
||||
final List<(int grade, int weight)> _ghostEntries = [];
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
grades = (await widget.data.client.getGrades(
|
||||
forceCache: false,
|
||||
)).response!.where((grade) => grade.subject.uid == widget.subject.uid);
|
||||
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
(() async {
|
||||
grades = (await widget.data.client.getGrades()).response!.where(
|
||||
(grade) => grade.subject.uid == widget.subject.uid,
|
||||
);
|
||||
|
||||
if (mounted) setState(() {});
|
||||
})();
|
||||
}
|
||||
|
||||
List<Grade> _gradesWithGhosts(Subject subject) {
|
||||
final real = grades?.toList() ?? [];
|
||||
List<GradeCacheModel> _gradesWithGhosts() {
|
||||
final real = widget.grades.toList();
|
||||
if (_ghostEntries.isEmpty) return real;
|
||||
final baseDate = real.isEmpty
|
||||
? DateTime.now()
|
||||
: real
|
||||
.map((g) => g.creationDate)
|
||||
.reduce((a, b) => a.isAfter(b) ? a : b);
|
||||
final osztalyzat = NameUidDesc(
|
||||
uid: '1,Osztalyzat',
|
||||
name: 'Osztalyzat',
|
||||
description: '',
|
||||
);
|
||||
final ghostGrades = <Grade>[];
|
||||
: real.map((g) => g.createdAt).reduce((a, b) => a.isAfter(b) ? a : b);
|
||||
for (var i = 0; i < _ghostEntries.length; i++) {
|
||||
final e = _ghostEntries[i];
|
||||
ghostGrades.add(
|
||||
Grade(
|
||||
uid: 'ghost-$i-${e.$1}-${e.$2}',
|
||||
recordDate: baseDate.add(Duration(seconds: i)),
|
||||
creationDate: baseDate.add(Duration(seconds: i)),
|
||||
subject: subject,
|
||||
type: osztalyzat,
|
||||
valueType: osztalyzat,
|
||||
teacher: '',
|
||||
strValue: '${e.$1}',
|
||||
sortIndex: 0,
|
||||
numericValue: e.$1,
|
||||
weightPercentage: e.$2,
|
||||
),
|
||||
real.add(
|
||||
GradeCacheModel()
|
||||
..type = "Ertekeles"
|
||||
..valueType = "Osztalyzat"
|
||||
..writtenAt = baseDate.add(Duration(seconds: i))
|
||||
..numericValue = e.$1
|
||||
..weightPercentage = e.$2
|
||||
..textValue = e.$1.toString()
|
||||
..teacherName = widget
|
||||
.teacherName // TODO: teacher name
|
||||
..subject.value = widget.subject,
|
||||
);
|
||||
}
|
||||
return [...real, ...ghostGrades];
|
||||
return real;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -101,14 +82,14 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() => {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (grades == null || grades!.isEmpty) {
|
||||
if (widget.grades.isEmpty) {
|
||||
return Container(
|
||||
color: appStyle.colors.background,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20),
|
||||
@@ -133,7 +114,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 1),
|
||||
child: Text(
|
||||
widget.data.l10n.subjects,
|
||||
initData.l10n.subjects,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -154,7 +135,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsetsGeometry.all(6),
|
||||
child: ClassIconWidget.subject(
|
||||
child: ClassIconWidget(
|
||||
subject: widget.subject,
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
@@ -169,7 +150,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
widget.data.l10n.unknown_teacher,
|
||||
initData.l10n.unknown_teacher,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -186,7 +167,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
widget.data.l10n.no_grades,
|
||||
initData.l10n.no_grades,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -202,7 +183,6 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
var aGrade = grades!.first;
|
||||
|
||||
final ghostGradeWidgets = _ghostEntries.indexed
|
||||
.map((e) {
|
||||
@@ -246,7 +226,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
Transform.translate(
|
||||
offset: const Offset(-4, 0),
|
||||
child: Text(
|
||||
widget.data.l10n.subjects,
|
||||
initData.l10n.subjects,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -270,8 +250,8 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
onTap: () {
|
||||
showSubjectBottomSheetSettings(
|
||||
context,
|
||||
widget.data,
|
||||
aGrade.subject,
|
||||
initData,
|
||||
widget.subject,
|
||||
onAddFromCalculator: (g, w) {
|
||||
setState(() => _ghostEntries.add((g, w)));
|
||||
},
|
||||
@@ -290,22 +270,23 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
FilledCircle(
|
||||
diameter: 36,
|
||||
color: appStyle.colors.a15p,
|
||||
child: ClassIconWidget.subject(
|
||||
subject: aGrade.subject,
|
||||
child: ClassIconWidget(
|
||||
subject: widget.subject,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
aGrade.subject.name,
|
||||
widget.subject.name,
|
||||
style: appStyle.fonts.H_H2.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
aGrade.teacher,
|
||||
widget.teacherName,
|
||||
textAlign: TextAlign.center,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -313,13 +294,11 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
],
|
||||
),
|
||||
SizedBox(height: 24),
|
||||
GradeChartWithInteraction(
|
||||
grades: _gradesWithGhosts(aGrade.subject),
|
||||
),
|
||||
GradeChartWithInteraction(grades: _gradesWithGhosts()),
|
||||
SizedBox(height: 10),
|
||||
GradeSummaryBar(
|
||||
grades: _gradesWithGhosts(aGrade.subject),
|
||||
l10n: widget.data.l10n,
|
||||
grades: _gradesWithGhosts(),
|
||||
l10n: initData.l10n,
|
||||
showAverage: ghostGradeWidgets.isNotEmpty,
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
@@ -341,8 +320,8 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
...ghostGradeWidgets,
|
||||
],
|
||||
),
|
||||
...grades!
|
||||
.groupList((e) => e.recordDate)
|
||||
...widget.grades
|
||||
.groupList((e) => e.writtenAt)
|
||||
.entries
|
||||
.map(
|
||||
(e) => Column(
|
||||
@@ -350,7 +329,7 @@ class _HomeGradesSubjectScreen extends FirkaState<HomeGradesSubjectScreen> {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
e.key.format(widget.data.l10n, FormatMode.main),
|
||||
e.key.format(initData.l10n, FormatMode.main),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
|
||||
@@ -2,16 +2,23 @@ import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:carousel_slider/carousel_slider.dart';
|
||||
import 'package:firka/api/client/kreta_stream.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka/ui/phone/widgets/info_card.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson_slider.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/phone/widgets/home_main_starting_soon.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson_small.dart';
|
||||
import 'package:firka/ui/shared/delayed_spinner.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -19,7 +26,7 @@ import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
@@ -39,161 +46,14 @@ class HomeMainScreen extends StatefulWidget {
|
||||
class _HomeMainScreen extends FirkaState<HomeMainScreen> {
|
||||
_HomeMainScreen();
|
||||
|
||||
List<Lesson>? lessons;
|
||||
List<NoticeBoardItem>? noticeBoard;
|
||||
List<InfoBoardItem>? infoBoard;
|
||||
List<Test>? tests;
|
||||
List<Grade>? grades;
|
||||
List<Homework>? homework;
|
||||
List<Omission>? omissions;
|
||||
Student? student;
|
||||
Timer? timer;
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
setState(() {});
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchData({bool cacheOnly = false}) async {
|
||||
final midnight = timeNow().getMidnight();
|
||||
|
||||
var lessonsFetched = 0;
|
||||
var noticeBoardFetched = 0;
|
||||
var infoBoardFetched = 0;
|
||||
var studentFetched = 0;
|
||||
var testsFetched = 0;
|
||||
var gradesFetched = 0;
|
||||
var homeworkFetched = 0;
|
||||
var omissionFetched = 0;
|
||||
|
||||
widget.data.client
|
||||
.getTimeTableStream(
|
||||
midnight,
|
||||
midnight.add(Duration(hours: 23, minutes: 59)),
|
||||
cacheOnly: cacheOnly,
|
||||
)
|
||||
.forEach((lessons) {
|
||||
lessonsFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.lessons = lessons.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getNoticeBoardStream(cacheOnly: cacheOnly).forEach((
|
||||
items,
|
||||
) {
|
||||
noticeBoardFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
noticeBoard = items.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getInfoBoardStream(cacheOnly: cacheOnly).forEach((
|
||||
items,
|
||||
) {
|
||||
infoBoardFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
infoBoard = items.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getStudentStream(cacheOnly: cacheOnly).forEach((
|
||||
student,
|
||||
) {
|
||||
studentFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.student = student.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getTestsStream(cacheOnly: cacheOnly).forEach((tests) {
|
||||
testsFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.tests = tests.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getGradesStream(cacheOnly: cacheOnly).forEach((grades) {
|
||||
gradesFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.grades = grades.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getOmissionsStream(cacheOnly: cacheOnly).forEach((
|
||||
omission,
|
||||
) {
|
||||
omissionFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.omissions = omission.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
widget.data.client.getHomeworkStream(cacheOnly: cacheOnly).forEach((
|
||||
homework,
|
||||
) {
|
||||
homeworkFetched++;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.homework = homework.response;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
final r = cacheOnly ? 1 : 2;
|
||||
final startTime = DateTime.now();
|
||||
const maxWaitTime = Duration(seconds: 30);
|
||||
|
||||
while (lessonsFetched < r ||
|
||||
noticeBoardFetched < r ||
|
||||
infoBoardFetched < r ||
|
||||
studentFetched < r ||
|
||||
testsFetched < r ||
|
||||
gradesFetched < r ||
|
||||
homeworkFetched < r ||
|
||||
omissionFetched < r) {
|
||||
if (DateTime.now().difference(startTime) > maxWaitTime) {
|
||||
debugPrint('[HomeMain] Data fetch timed out after 30s');
|
||||
break;
|
||||
}
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
(() async {
|
||||
await fetchData();
|
||||
})();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<HomeRefreshCubit, HomeRefreshState>(
|
||||
@@ -207,118 +67,104 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (student != null && lessons != null) {
|
||||
final now = timeNow();
|
||||
final infoItems = [...(infoBoard ?? []), ...(noticeBoard ?? [])];
|
||||
final gradeItems = grades ?? [];
|
||||
final testItems = tests ?? [];
|
||||
final homeworkItems = homework ?? [];
|
||||
final omissionItems = omissions?.groupList((o) => o.date).values ?? [];
|
||||
final noticeBoardWidgets = <(Widget, DateTime)>[];
|
||||
final now = timeNow();
|
||||
final infoItems = widget.data.client!.cache.getMessages().findAllSync();
|
||||
final gradeItems = widget.data.client!.cache.getGrades().findAllSync();
|
||||
final testItems = widget.data.client!.cache.getTests().findAllSync();
|
||||
final homeworkItems = widget.data.client!.cache
|
||||
.getHomeworks()
|
||||
.findAllSync();
|
||||
final omissionItems = widget.data.client!.cache
|
||||
.getOmissions()
|
||||
.findAllSync()
|
||||
.groupList((o) => o.lesson.loadAndGet()!.start);
|
||||
final noticeBoardWidgets = <(Widget, DateTime)>[];
|
||||
final todayLesson = widget.data.client!.cache
|
||||
.getClassLessons()
|
||||
.on(now)
|
||||
.findAllSync();
|
||||
|
||||
for (final item in infoItems) {
|
||||
noticeBoardWidgets.add((InfoCard.messageItem(item), item.date));
|
||||
}
|
||||
for (final item in infoItems) {
|
||||
noticeBoardWidgets.add((InfoCard.messageItem(item), item.createdAt));
|
||||
}
|
||||
|
||||
for (final test in testItems) {
|
||||
noticeBoardWidgets.add((InfoCard.test(test), test.reportDate));
|
||||
}
|
||||
for (final test in testItems) {
|
||||
noticeBoardWidgets.add((InfoCard.test(test), test.createdAt));
|
||||
}
|
||||
|
||||
for (final grade in gradeItems) {
|
||||
noticeBoardWidgets.add((InfoCard.gradeSubj(grade), grade.creationDate));
|
||||
}
|
||||
for (final grade in gradeItems) {
|
||||
noticeBoardWidgets.add((InfoCard.gradeSubj(grade), grade.createdAt));
|
||||
}
|
||||
|
||||
for (final entry in homeworkItems) {
|
||||
noticeBoardWidgets.add((InfoCard.homework(entry), entry.creationDate));
|
||||
}
|
||||
for (final entry in homeworkItems) {
|
||||
noticeBoardWidgets.add((InfoCard.homework(entry), entry.createdAt));
|
||||
}
|
||||
|
||||
for (final omission in omissionItems) {
|
||||
noticeBoardWidgets.add((
|
||||
InfoCard.omission(omission),
|
||||
omission.first.date,
|
||||
));
|
||||
}
|
||||
for (final entry in omissionItems.entries) {
|
||||
noticeBoardWidgets.add((InfoCard.omission(entry.value), entry.key));
|
||||
}
|
||||
|
||||
noticeBoardWidgets.sort(
|
||||
(item1, item2) => item2.$2.difference(item1.$2).inMilliseconds,
|
||||
);
|
||||
noticeBoardWidgets.sort(
|
||||
(item1, item2) => item2.$2.difference(item1.$2).inMilliseconds,
|
||||
);
|
||||
|
||||
LinkedHashMap<Lesson, Test?> lessonTestMap = LinkedHashMap.fromEntries(
|
||||
lessons!.indexed.map(
|
||||
(i) => MapEntry(
|
||||
i.$2,
|
||||
testItems.firstWhereOrNull(
|
||||
(t) =>
|
||||
t.date.getMidnight() == i.$2.start.getMidnight() &&
|
||||
(i.$2.lessonNumber ?? i.$1) == t.lessonNumber,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
int testsTomorrow = testItems
|
||||
.where(
|
||||
(test) =>
|
||||
test.lesson.loadAndGet() != null &&
|
||||
test.lesson.loadAndGet()!.start.isAfter(
|
||||
now.getMidnight().add(Duration(hours: 23, minutes: 59)),
|
||||
) &&
|
||||
test.lesson.loadAndGet()!.start.isBefore(
|
||||
now.getMidnight().add(Duration(days: 2)),
|
||||
),
|
||||
)
|
||||
.length;
|
||||
|
||||
int testsTomorrow = testItems
|
||||
.where(
|
||||
(test) =>
|
||||
test.date.isAfter(
|
||||
now.getMidnight().add(Duration(hours: 23, minutes: 59)),
|
||||
) &&
|
||||
test.date.isBefore(now.getMidnight().add(Duration(days: 2))),
|
||||
)
|
||||
.length;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20.0),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => fetchData(),
|
||||
notificationPredicate: (ScrollNotification notification) {
|
||||
return notification.depth == 0;
|
||||
},
|
||||
triggerMode: RefreshIndicatorTriggerMode.onEdge,
|
||||
displacement: 0,
|
||||
child: ListView(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
SizedBox(height: 24),
|
||||
WelcomeWidget(widget.data.l10n, now, student!, lessons!),
|
||||
SizedBox(height: 48),
|
||||
LessonSlider(lessonTestMap, testsTomorrow),
|
||||
SizedBox(height: 24),
|
||||
...noticeBoardWidgets
|
||||
.groupList((e) => e.$2)
|
||||
.entries
|
||||
.map(
|
||||
(e) => Column(
|
||||
spacing: 10,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
e.key.format(widget.data.l10n, FormatMode.main),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
...e.value.map((v) => v.$1),
|
||||
SizedBox(height: 10),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20.0),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => Future.value(),
|
||||
notificationPredicate: (ScrollNotification notification) {
|
||||
return notification.depth == 0;
|
||||
},
|
||||
triggerMode: RefreshIndicatorTriggerMode.onEdge,
|
||||
displacement: 0,
|
||||
child: ListView(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [DelayedSpinnerWidget()],
|
||||
SizedBox(height: 24),
|
||||
WelcomeWidget(
|
||||
widget.data.l10n,
|
||||
now,
|
||||
widget.data.client!.cache.findStudent(),
|
||||
todayLesson,
|
||||
),
|
||||
SizedBox(height: 48),
|
||||
LessonSlider(todayLesson, testsTomorrow),
|
||||
SizedBox(height: 24),
|
||||
...noticeBoardWidgets
|
||||
.groupList((e) => e.$2)
|
||||
.entries
|
||||
.map(
|
||||
(e) => Column(
|
||||
spacing: 10,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
e.key.format(widget.data.l10n, FormatMode.main),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
...e.value.map((v) => v.$1),
|
||||
SizedBox(height: 10),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/phone/widgets/info_card.dart';
|
||||
import 'package:firka/ui/phone/widgets/omission_bar.dart';
|
||||
import 'package:firka_common/firka_common.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/shared/firka_icon.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_chart.dart';
|
||||
import 'package:firka/ui/phone/widgets/grade_summary_bar.dart';
|
||||
import 'package:firka/ui/shared/grade_small_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/shared/delayed_spinner.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
class HomeOmissionsScreen extends StatefulWidget {
|
||||
@@ -34,45 +28,22 @@ class HomeOmissionsScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeOmissionsScreen extends FirkaState<HomeOmissionsScreen> {
|
||||
ApiResponse<List<Omission>>? omissions;
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
omissions = await widget.data.client.getOmissions(forceCache: false);
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
(() async {
|
||||
omissions = await widget.data.client.getOmissions(forceCache: false);
|
||||
if (mounted) setState(() {});
|
||||
})();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<HomeRefreshCubit, HomeRefreshState>(
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (omissions == null) {
|
||||
return Center(child: DelayedSpinnerWidget());
|
||||
}
|
||||
|
||||
final omissionItems = omissions!.response ?? [];
|
||||
final omissionItems = widget.data.client!.cache
|
||||
.getOmissions()
|
||||
.findAllSync();
|
||||
|
||||
final overallExcused = omissionItems
|
||||
.where((o) => o.state == OmissionState.excused)
|
||||
@@ -203,7 +174,7 @@ class _HomeOmissionsScreen extends FirkaState<HomeOmissionsScreen> {
|
||||
],
|
||||
),
|
||||
SizedBox(height: 10),
|
||||
OmissionBar(omissions: omissions!.response!),
|
||||
OmissionBar(),
|
||||
SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
@@ -217,13 +188,18 @@ class _HomeOmissionsScreen extends FirkaState<HomeOmissionsScreen> {
|
||||
SizedBox(height: 10),
|
||||
...omissionItems
|
||||
.fold(
|
||||
LinkedHashMap<Subject, List<Omission>>(
|
||||
equals: (a, b) => a.uid == b.uid,
|
||||
hashCode: (a) => a.uid.hashCode,
|
||||
LinkedHashMap<
|
||||
SubjectCacheModel,
|
||||
List<OmissionCacheModel>
|
||||
>(
|
||||
equals: (a, b) => a.cacheKey == b.cacheKey,
|
||||
hashCode: (a) => a.cacheKey,
|
||||
),
|
||||
(map, o) =>
|
||||
map
|
||||
..putIfAbsent(o.subject, () => <Omission>[]).add(o),
|
||||
(map, o) => map
|
||||
..putIfAbsent(
|
||||
o.lesson.loadAndGet()!.subject.loadAndGet()!,
|
||||
() => [],
|
||||
).add(o),
|
||||
)
|
||||
.entries
|
||||
.map((entry) {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:carousel_slider/carousel_slider.dart';
|
||||
import 'package:firka/api/client/kreta_stream.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/phone/widgets/bottom_tt_icon.dart';
|
||||
import 'package:firka/ui/phone/widgets/tt_day.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/screens/settings/settings_screen.dart';
|
||||
import 'package:firka/ui/phone/widgets/bubble_test.dart';
|
||||
import 'package:firka/ui/shared/delayed_spinner.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -18,14 +19,12 @@ import 'package:flutter/services.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:transparent_pointer/transparent_pointer.dart';
|
||||
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/core/bloc/settings_cubit.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import '../../widgets/bottom_tt_icon.dart';
|
||||
import '../../widgets/tt_day.dart';
|
||||
|
||||
class HomeTimetableScreen extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
@@ -38,16 +37,13 @@ class HomeTimetableScreen extends StatefulWidget {
|
||||
|
||||
class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
with TickerProviderStateMixin {
|
||||
List<Lesson>? lessons;
|
||||
List<Lesson>? events;
|
||||
List<Test>? tests;
|
||||
|
||||
// Original dates list for display
|
||||
List<DateTime>? dates;
|
||||
LinkedHashMap<DateTime, List<LessonCacheModel>> dates =
|
||||
LinkedHashMap.identity();
|
||||
|
||||
// Dates list for carousel animation
|
||||
List<DateTime>? _animationDates;
|
||||
DateTime? now;
|
||||
List<DateTime> _animationDates = [];
|
||||
late DateTime currentMonday;
|
||||
int active = 0;
|
||||
final CarouselSliderController _controller = CarouselSliderController();
|
||||
|
||||
@@ -64,194 +60,12 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
now = timeNow();
|
||||
initForWeek(now!);
|
||||
|
||||
_cardAnimationController = AnimationController(
|
||||
duration: Duration(milliseconds: 300),
|
||||
vsync: this,
|
||||
);
|
||||
}
|
||||
|
||||
void setActiveToToday() {
|
||||
final todayMid = now!.getMidnight();
|
||||
int idx = dates!.indexWhere(
|
||||
(d) =>
|
||||
d.year == todayMid.year &&
|
||||
d.month == todayMid.month &&
|
||||
d.day == todayMid.day,
|
||||
);
|
||||
|
||||
if (idx >= 0) {
|
||||
final todaysLessons = lessons?.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(todayMid) &&
|
||||
lesson.end.isBefore(todayMid.add(Duration(hours: 23, minutes: 59))),
|
||||
);
|
||||
|
||||
if (todaysLessons != null && todaysLessons.isNotEmpty) {
|
||||
final lastLessonToday = todaysLessons.reduce(
|
||||
(a, b) => a.end.isAfter(b.end) ? a : b,
|
||||
);
|
||||
|
||||
if (now!.isAfter(lastLessonToday.end)) {
|
||||
int nextIdx = idx + 1;
|
||||
if (nextIdx < dates!.length) {
|
||||
active = nextIdx;
|
||||
} else {
|
||||
active = idx;
|
||||
}
|
||||
} else {
|
||||
active = idx;
|
||||
}
|
||||
} else {
|
||||
active = idx;
|
||||
}
|
||||
} else if (now!.isAfter(dates!.last)) {
|
||||
active = dates!.length - 1;
|
||||
} else {
|
||||
idx = dates!.indexWhere((d) => d.isAfter(todayMid));
|
||||
active = idx >= 0 ? idx : 0;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> maybeCacheNextWeek(int active) async {
|
||||
DateTime monday = now!.getMonday().getMidnight();
|
||||
if (active >= 3) {
|
||||
// thursday
|
||||
monday = monday.add(Duration(days: 14));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (timeNow().add(Duration(days: 31)).isBefore(monday)) return;
|
||||
logger.finest("caching next week for $monday");
|
||||
var sunday = monday.add(Duration(days: 6));
|
||||
await widget.data.client.getTimeTable(monday, sunday);
|
||||
await widget.data.client.getTests();
|
||||
}
|
||||
|
||||
Future<void> maybeCachePreviousWeek(int active) async {
|
||||
DateTime monday = now!.getMonday().getMidnight();
|
||||
if (active <= 2) {
|
||||
// wednesday
|
||||
monday = monday.subtract(Duration(days: 7));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (timeNow().subtract(Duration(days: 120)).isAfter(monday)) return;
|
||||
logger.finest("caching previous week for $monday");
|
||||
var sunday = monday.add(Duration(days: 6));
|
||||
await widget.data.client.getTimeTable(monday, sunday);
|
||||
await widget.data.client.getTests();
|
||||
}
|
||||
|
||||
Future<void> _updateState(
|
||||
DateTime now,
|
||||
ApiResponse<List<Lesson>> lessonsResp,
|
||||
ApiResponse<List<Test>> testsResp,
|
||||
) async {
|
||||
var monday = now.getMonday().getMidnight();
|
||||
|
||||
List<DateTime> dates = List.empty(growable: true);
|
||||
|
||||
if (lessonsResp.response != null) {
|
||||
lessons = lessonsResp.response
|
||||
?.where((lesson) => lesson.type.name != TimetableConsts.event)
|
||||
.toList();
|
||||
events = lessonsResp.response
|
||||
?.where((lesson) => lesson.type.name == TimetableConsts.event)
|
||||
.toList();
|
||||
tests = testsResp.response;
|
||||
|
||||
for (var i = 0; i < 7; i++) {
|
||||
var t = monday.add(Duration(days: i));
|
||||
|
||||
var hasLessons =
|
||||
i < 5 ||
|
||||
lessons!.firstWhereOrNull((lesson) {
|
||||
return lesson.start.getMidnight().millisecondsSinceEpoch ==
|
||||
t.getMidnight().millisecondsSinceEpoch;
|
||||
}) !=
|
||||
null;
|
||||
|
||||
if (hasLessons) {
|
||||
dates.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
this.dates = dates;
|
||||
_animationDates = List.from(dates);
|
||||
_isTemporaryOrder = false;
|
||||
|
||||
if (now.getMonday().getMidnight().millisecondsSinceEpoch ==
|
||||
timeNow().getMonday().getMidnight().millisecondsSinceEpoch) {
|
||||
setActiveToToday();
|
||||
} else {
|
||||
active = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> initForWeek(DateTime now, {bool forceCache = true}) async {
|
||||
var monday = now.getMonday().getMidnight();
|
||||
var sunday = monday.add(Duration(days: 6));
|
||||
|
||||
ApiResponse<List<Lesson>>? lessonsResp;
|
||||
var lessonsFetched = 0;
|
||||
ApiResponse<List<Test>>? testsResp;
|
||||
var testsFetched = 0;
|
||||
|
||||
widget.data.client
|
||||
.getTimeTableStream(monday, sunday, cacheOnly: forceCache)
|
||||
.forEach((lessons) {
|
||||
lessonsResp = lessons;
|
||||
lessonsFetched++;
|
||||
});
|
||||
|
||||
widget.data.client.getTestsStream(cacheOnly: forceCache).forEach((tests) {
|
||||
testsResp = tests;
|
||||
testsFetched++;
|
||||
});
|
||||
|
||||
final startTime = DateTime.now();
|
||||
const maxWaitTime = Duration(seconds: 15);
|
||||
|
||||
while (lessonsFetched < 1 || testsFetched < 1) {
|
||||
if (DateTime.now().difference(startTime) > maxWaitTime) {
|
||||
debugPrint('[Timetable] Cache load timed out after 15s');
|
||||
return;
|
||||
}
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
}
|
||||
await _updateState(now, lessonsResp!, testsResp!);
|
||||
|
||||
if (!forceCache) {
|
||||
final networkStartTime = DateTime.now();
|
||||
while (lessonsFetched < 2 || testsFetched < 2) {
|
||||
if (DateTime.now().difference(networkStartTime) > maxWaitTime) {
|
||||
debugPrint('[Timetable] Network load timed out after 15s');
|
||||
break;
|
||||
}
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
}
|
||||
if (lessonsFetched >= 2 && testsFetched >= 2) {
|
||||
await _updateState(now, lessonsResp!, testsResp!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
if (now != null) {
|
||||
await initForWeek(now!, forceCache: false);
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
updateWeek(timeNow());
|
||||
}
|
||||
|
||||
bool animating = false;
|
||||
@@ -260,18 +74,13 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
if (animating) return;
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
// Save the real target index
|
||||
final realTargetIndex = targetIndex;
|
||||
|
||||
maybeCacheNextWeek(realTargetIndex);
|
||||
maybeCachePreviousWeek(realTargetIndex);
|
||||
final original = _animationDates;
|
||||
|
||||
// If the target is not adjacent, create temporary order
|
||||
int tempTargetIndex = targetIndex;
|
||||
if ((targetIndex - oldIndex).abs() > 1) {
|
||||
// Determine the temporary target position next to the current position
|
||||
int tempTargetIndex = oldIndex < targetIndex
|
||||
? oldIndex + 1
|
||||
: oldIndex - 1;
|
||||
tempTargetIndex = oldIndex < targetIndex ? oldIndex + 1 : oldIndex - 1;
|
||||
|
||||
// Create a new order where target day is next to current day
|
||||
List<DateTime> reorderedDates = List.from(_animationDates!);
|
||||
@@ -281,7 +90,6 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
setState(() {
|
||||
_animationDates = reorderedDates;
|
||||
_isTemporaryOrder = true;
|
||||
targetIndex = tempTargetIndex; // Update target for animation
|
||||
});
|
||||
}
|
||||
|
||||
@@ -291,12 +99,8 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
const double spacing = 16.0;
|
||||
final double totalCardWidth = cardWidth + spacing;
|
||||
|
||||
// Calculate animation positions based on real display indices
|
||||
final oldDisplayIndex = dates!.indexOf(_animationDates![oldIndex]);
|
||||
final targetDisplayIndex = dates!.indexOf(_animationDates![targetIndex]);
|
||||
|
||||
final double start = oldDisplayIndex * totalCardWidth;
|
||||
final double end = targetDisplayIndex * totalCardWidth;
|
||||
final double start = oldIndex * totalCardWidth;
|
||||
final double end = targetIndex * totalCardWidth;
|
||||
|
||||
_cardAnimationController!.reset();
|
||||
_cardOffsetAnimation =
|
||||
@@ -315,39 +119,52 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
|
||||
animating = true;
|
||||
await _controller.animateToPage(
|
||||
targetIndex,
|
||||
tempTargetIndex,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
);
|
||||
|
||||
// After animation, restore the original order if necessary
|
||||
if (_isTemporaryOrder) {
|
||||
// Calculate the real display index for the target
|
||||
final displayIndex = dates!.indexOf(_animationDates![targetIndex]);
|
||||
|
||||
setState(() {
|
||||
_animationDates = List.from(dates!); // Restore from original dates
|
||||
_animationDates = original; // Restore from original dates
|
||||
_isTemporaryOrder = false;
|
||||
active = displayIndex; // Use the display index
|
||||
});
|
||||
|
||||
// Jump to the correct position without animation
|
||||
_controller.jumpToPage(displayIndex);
|
||||
} else {
|
||||
final displayIndex = dates!.indexOf(_animationDates![targetIndex]);
|
||||
setState(() {
|
||||
active = displayIndex; // Use the display index
|
||||
});
|
||||
_controller.jumpToPage(targetIndex);
|
||||
}
|
||||
|
||||
animating = false;
|
||||
setState(() {
|
||||
active = targetIndex;
|
||||
_showAnimatedCard = false;
|
||||
});
|
||||
|
||||
_cardAnimationController!.reset();
|
||||
}
|
||||
|
||||
void updateWeek(DateTime monday) {
|
||||
currentMonday = monday.getMonday().getMidnight();
|
||||
|
||||
dates.clear();
|
||||
for (int i = 0; i < 7; i++) {
|
||||
final day = currentMonday.add(Duration(days: i));
|
||||
|
||||
dates[day] = widget.data.client!.cache
|
||||
.getTimeTable()
|
||||
.on(day)
|
||||
.sortByStart()
|
||||
.findAllSync();
|
||||
|
||||
if (day.weekday > 5 &&
|
||||
dates[day]!.every((l) => l.type == TimetableConsts.event)) {
|
||||
dates.remove(day);
|
||||
}
|
||||
}
|
||||
_animationDates = List.from(dates.keys);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<SettingsCubit, SettingsState>(
|
||||
@@ -358,7 +175,7 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
),
|
||||
@@ -366,18 +183,6 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (lessons == null || tests == null || events == null || dates == null) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [DelayedSpinnerWidget()],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> ttWidgets = [];
|
||||
List<Widget> ttDays = [];
|
||||
final showABTimetable = widget.data.settings
|
||||
@@ -385,27 +190,19 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
.subGroup("timetable_toast")
|
||||
.boolean("ab_timetable");
|
||||
// Build navigation icons using original dates
|
||||
for (var i = 0; i < dates!.length; i++) {
|
||||
final date = dates![i];
|
||||
final realIndex = i; // Always use real index for nav icons
|
||||
|
||||
final testsOnDate = tests!
|
||||
.where(
|
||||
(test) =>
|
||||
test.date.isAfter(date.subtract(Duration(seconds: 1))) &&
|
||||
test.date.isBefore(date.add(Duration(hours: 23, minutes: 59))),
|
||||
)
|
||||
.toList();
|
||||
|
||||
var i = 0;
|
||||
for (MapEntry<DateTime, List<LessonCacheModel>> e in dates.entries) {
|
||||
var realIndex = i;
|
||||
Widget ttWidget = BottomTimeTableNavIconWidget(
|
||||
widget.data.l10n,
|
||||
() {
|
||||
_handleNavTap(active, realIndex);
|
||||
},
|
||||
active == i,
|
||||
date,
|
||||
e.key,
|
||||
);
|
||||
if (testsOnDate.isNotEmpty) {
|
||||
|
||||
if (e.value.any((l) => l.test.loadAndGet() != null)) {
|
||||
ttWidgets.add(
|
||||
Stack(
|
||||
children: [
|
||||
@@ -417,52 +214,21 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
} else {
|
||||
ttWidgets.add(ttWidget);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
bool isEvent(LessonCacheModel model) {
|
||||
return model.type == TimetableConsts.event;
|
||||
}
|
||||
|
||||
// Build carousel pages using animation dates
|
||||
for (var i = 0; i < _animationDates!.length; i++) {
|
||||
final date = _animationDates![i];
|
||||
|
||||
final lessonsOnDate = lessons!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(date) &&
|
||||
lesson.end.isBefore(date.add(Duration(hours: 24))),
|
||||
)
|
||||
.toList();
|
||||
final lessonsOnDay = lessons!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.start.getMidnight().millisecondsSinceEpoch ==
|
||||
date.getMidnight().millisecondsSinceEpoch,
|
||||
)
|
||||
.toList();
|
||||
final eventsOnDate = events!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(date.subtract(Duration(seconds: 1))) &&
|
||||
lesson.end.isBefore(date.add(Duration(hours: 23, minutes: 59))),
|
||||
)
|
||||
.toList();
|
||||
final testsOnDate = tests!
|
||||
.where(
|
||||
(test) =>
|
||||
test.date.isAfter(date.subtract(Duration(seconds: 1))) &&
|
||||
test.date.isBefore(date.add(Duration(hours: 23, minutes: 59))),
|
||||
)
|
||||
.toList();
|
||||
|
||||
ttDays.add(
|
||||
TimeTableDayWidget(
|
||||
widget.data,
|
||||
date,
|
||||
lessons!,
|
||||
lessonsOnDate,
|
||||
eventsOnDate,
|
||||
testsOnDate,
|
||||
lessonsOnDay,
|
||||
),
|
||||
);
|
||||
for (DateTime date in _animationDates) {
|
||||
final lessons = List<LessonCacheModel>.from(dates[date]!)
|
||||
..removeWhere(isEvent);
|
||||
final events = List<LessonCacheModel>.from(dates[date]!)
|
||||
..retainWhere(isEvent);
|
||||
ttDays.add(TimeTableDayWidget(lessons, events));
|
||||
}
|
||||
|
||||
Widget ttAnimatedCard = BottomTimeTableNavIconWidget(
|
||||
@@ -587,17 +353,11 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
),
|
||||
onTap: () async {
|
||||
var newNow = now!.subtract(Duration(days: 7));
|
||||
if (!mounted) return;
|
||||
onTap: () {
|
||||
setState(() {
|
||||
now = newNow;
|
||||
lessons = null;
|
||||
dates = null;
|
||||
});
|
||||
await initForWeek(newNow);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
updateWeek(
|
||||
currentMonday.subtract(Duration(days: 7)),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
@@ -606,7 +366,7 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
spacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
now!.format(
|
||||
currentMonday.format(
|
||||
widget.data.l10n,
|
||||
FormatMode.yyyymmddwedd,
|
||||
),
|
||||
@@ -622,7 +382,7 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
),
|
||||
),
|
||||
Text(
|
||||
now!.isAWeek()
|
||||
currentMonday.isAWeek()
|
||||
? widget.data.l10n.a_week
|
||||
: widget.data.l10n.b_week,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
@@ -633,9 +393,10 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
now = timeNow();
|
||||
setActiveToToday();
|
||||
_controller.jumpToPage(active);
|
||||
setState(() {
|
||||
updateWeek(timeNow());
|
||||
_controller.jumpToPage(active);
|
||||
});
|
||||
},
|
||||
),
|
||||
GestureDetector(
|
||||
@@ -650,17 +411,9 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
),
|
||||
onTap: () async {
|
||||
var newNow = now!.add(Duration(days: 7));
|
||||
if (!mounted) return;
|
||||
onTap: () {
|
||||
setState(() {
|
||||
now = newNow;
|
||||
lessons = null;
|
||||
dates = null;
|
||||
});
|
||||
await initForWeek(newNow);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
updateWeek(currentMonday.add(Duration(days: 7)));
|
||||
});
|
||||
},
|
||||
),
|
||||
@@ -691,12 +444,8 @@ class _HomeTimetableScreen extends FirkaState<HomeTimetableScreen>
|
||||
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
// Convert animation index to display index
|
||||
final displayIndex = dates!.indexOf(_animationDates![i]);
|
||||
maybeCacheNextWeek(displayIndex);
|
||||
maybeCachePreviousWeek(displayIndex);
|
||||
setState(() {
|
||||
active = displayIndex;
|
||||
active = i;
|
||||
});
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka/ui/phone/screens/settings/settings_screen.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
@@ -16,7 +21,6 @@ import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/bloc/home_refresh_cubit.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import '../../screens/settings/settings_screen.dart';
|
||||
|
||||
class HomeTimetableMonthlyScreen extends StatefulWidget {
|
||||
final AppInitialization data;
|
||||
@@ -32,68 +36,19 @@ enum ActiveFilter { lessonNo, tests, omissions }
|
||||
|
||||
class _HomeTimetableMonthlyScreen
|
||||
extends FirkaState<HomeTimetableMonthlyScreen> {
|
||||
List<Lesson>? lessons;
|
||||
List<Test>? tests;
|
||||
List<DateTime>? dates;
|
||||
List<Omission>? omissions;
|
||||
DateTime? now;
|
||||
List<DateTime> dates = [];
|
||||
late DateTime now;
|
||||
int active = 0;
|
||||
ActiveFilter activeFilter = ActiveFilter.lessonNo;
|
||||
|
||||
_HomeTimetableMonthlyScreen();
|
||||
|
||||
Future<void> initForMonth(DateTime now, {bool forceCache = true}) async {
|
||||
final monthStart = DateTime.utc(now.year, now.month, 1);
|
||||
final monthEnd = DateTime.utc(
|
||||
now.year,
|
||||
now.month + 1,
|
||||
).subtract(Duration(days: 1));
|
||||
|
||||
final start = monthStart.subtract(Duration(days: 7)).getMonday();
|
||||
var end = monthEnd
|
||||
.add(Duration(days: 7))
|
||||
.getMonday()
|
||||
.add(Duration(days: 7));
|
||||
|
||||
var days = end.difference(start).inDays;
|
||||
|
||||
var lessonsResp = await widget.data.client.getTimeTable(
|
||||
monthStart,
|
||||
monthEnd,
|
||||
forceCache: forceCache,
|
||||
void updateDates() {
|
||||
DateTime from = now.getMidnight().getMonthFirstDay().getMonday().subtract(
|
||||
Duration(days: 7),
|
||||
);
|
||||
var testsResp = await widget.data.client.getTests(forceCache: forceCache);
|
||||
var omissionsResp = await widget.data.client.getOmissions(forceCache: true);
|
||||
List<DateTime> dates = List.empty(growable: true);
|
||||
|
||||
for (var i = 0; i < days; i++) {
|
||||
dates.add(start.add(Duration(days: i)));
|
||||
}
|
||||
|
||||
if (lessonsResp.response != null) {
|
||||
lessons = lessonsResp.response
|
||||
?.where((lesson) => lesson.type.name != TimetableConsts.event)
|
||||
.toList();
|
||||
}
|
||||
tests = testsResp.response;
|
||||
omissions = omissionsResp.response;
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
this.dates = dates;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _onRefreshRequested(BuildContext context) async {
|
||||
final cubit = context.read<HomeRefreshCubit>();
|
||||
if (now != null) {
|
||||
await initForMonth(now!, forceCache: false);
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
cubit.onRefreshComplete();
|
||||
}
|
||||
}
|
||||
dates = List.generate(49, (i) => from.add(Duration(days: i)));
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -101,7 +56,8 @@ class _HomeTimetableMonthlyScreen
|
||||
super.initState();
|
||||
|
||||
now = timeNow();
|
||||
initForMonth(now!);
|
||||
|
||||
updateDates();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -110,38 +66,23 @@ class _HomeTimetableMonthlyScreen
|
||||
listenWhen: (previous, current) =>
|
||||
current.refreshTrigger != previous.refreshTrigger,
|
||||
listener: (context, state) {
|
||||
_onRefreshRequested(context);
|
||||
setState(() {});
|
||||
},
|
||||
child: _buildContent(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
if (lessons == null ||
|
||||
omissions == null ||
|
||||
tests == null ||
|
||||
dates == null) {
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [DelayedSpinnerWidget()],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
List<Widget> ttDays = [];
|
||||
|
||||
final meow = dates![20];
|
||||
final currentMonthStart = DateTime.utc(meow.year, meow.month, 1);
|
||||
final currentMonthEnd = DateTime.utc(
|
||||
meow.year,
|
||||
meow.month + 1,
|
||||
).subtract(Duration(days: 1));
|
||||
updateDates();
|
||||
|
||||
final currentMonthStart = now.getMidnight().getMonthFirstDay();
|
||||
final currentMonthEnd = now
|
||||
.getMonthLastDay()
|
||||
.add(Duration(days: 1))
|
||||
.getMidnight()
|
||||
.subtract(Duration(microseconds: 1));
|
||||
|
||||
// column-major -> row-major
|
||||
for (var week = 0; week < 7; week++) {
|
||||
@@ -151,39 +92,39 @@ class _HomeTimetableMonthlyScreen
|
||||
bool outOfRange =
|
||||
d.isBefore(currentMonthStart) || d.isAfter(currentMonthEnd);
|
||||
bool isToday =
|
||||
!outOfRange && timeNow().day == d.day && timeNow().month == d.month;
|
||||
!outOfRange &&
|
||||
timeNow().year == d.year &&
|
||||
timeNow().day == d.day &&
|
||||
timeNow().month == d.month;
|
||||
|
||||
Widget body = SizedBox();
|
||||
Color? todayAccent = isToday ? appStyle.colors.textPrimaryLight : null;
|
||||
Color bodyBgColor = appStyle.colors.a15p;
|
||||
|
||||
var lessonsToday = lessons!.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(d.getMidnight()) &&
|
||||
lesson.end.isBefore(
|
||||
d.getMidnight().add(Duration(hours: 23, minutes: 59)),
|
||||
),
|
||||
);
|
||||
var lessonsToday = widget.data.client!.cache.getClassLessons().on(d);
|
||||
|
||||
var omittedLesson = lessonsToday.firstWhereOrNull(
|
||||
(lesson) =>
|
||||
lesson.studentPresence != null &&
|
||||
lesson.studentPresence?.name != OmissionConsts.na &&
|
||||
lesson.studentPresence?.name != OmissionConsts.present,
|
||||
);
|
||||
int lessonCountToday = lessonsToday.countSync();
|
||||
|
||||
if (lessonsToday.isNotEmpty) {
|
||||
// TODO: Nézze meg a többi órát is
|
||||
var omittedLesson = lessonsToday
|
||||
.and()
|
||||
.not()
|
||||
.omissionIsNull()
|
||||
.findFirstSync();
|
||||
|
||||
if (lessonCountToday > 0) {
|
||||
switch (activeFilter) {
|
||||
case ActiveFilter.lessonNo:
|
||||
body = Center(
|
||||
child: Text(
|
||||
lessonsToday.length.toString(),
|
||||
lessonCountToday.toString(),
|
||||
style: appStyle.fonts.H_16px.apply(
|
||||
color:
|
||||
todayAccent ??
|
||||
(omittedLesson != null
|
||||
? appStyle.colors.errorText
|
||||
: appStyle.colors.secondary),
|
||||
(todayAccent ??
|
||||
(omittedLesson != null
|
||||
? appStyle.colors.errorText
|
||||
: appStyle.colors.secondary))
|
||||
.withAlpha(outOfRange ? 77 : 255),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -193,19 +134,7 @@ class _HomeTimetableMonthlyScreen
|
||||
}
|
||||
break;
|
||||
case ActiveFilter.tests:
|
||||
if (lessonsToday.firstWhereOrNull(
|
||||
(lesson) => tests!.any(
|
||||
(test) =>
|
||||
test.lessonNumber == lesson.lessonNumber &&
|
||||
lesson.start.isAfter(test.date.getMidnight()) &&
|
||||
lesson.end.isBefore(
|
||||
test.date.getMidnight().add(
|
||||
Duration(hours: 23, minutes: 59),
|
||||
),
|
||||
),
|
||||
),
|
||||
) !=
|
||||
null) {
|
||||
if (lessonsToday.not().testIsNull().isNotEmptySync()) {
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
@@ -221,50 +150,41 @@ class _HomeTimetableMonthlyScreen
|
||||
break;
|
||||
}
|
||||
|
||||
// TODO: Nézze meg a többi órát is
|
||||
final omission = omissions!.firstWhereOrNull((omission) {
|
||||
return omission.date.getMidnight().millisecondsSinceEpoch ==
|
||||
omittedLesson.start
|
||||
.getMidnight()
|
||||
.millisecondsSinceEpoch &&
|
||||
omission.subject.uid == omittedLesson.subject?.uid;
|
||||
});
|
||||
|
||||
if (omission?.state == OmissionState.excused) {
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.multiplySolid,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.accent,
|
||||
),
|
||||
);
|
||||
break;
|
||||
var omissionState = omittedLesson.omission.loadAndGet()!.state;
|
||||
switch (omissionState) {
|
||||
case OmissionState.excused:
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.multiplySolid,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.accent,
|
||||
),
|
||||
);
|
||||
break;
|
||||
case OmissionState.pending:
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.timerLine,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.warningAccent,
|
||||
),
|
||||
);
|
||||
bodyBgColor = appStyle.colors.warning15p;
|
||||
break;
|
||||
default:
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.restrictedSolid,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.errorAccent,
|
||||
),
|
||||
);
|
||||
bodyBgColor = appStyle.colors.error15p;
|
||||
break;
|
||||
}
|
||||
|
||||
if (omission?.state == OmissionState.pending) {
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.timerLine,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.warningAccent,
|
||||
),
|
||||
);
|
||||
bodyBgColor = appStyle.colors.warning15p;
|
||||
break;
|
||||
}
|
||||
|
||||
body = Center(
|
||||
child: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.restrictedSolid,
|
||||
size: 20.0,
|
||||
color: todayAccent ?? appStyle.colors.errorAccent,
|
||||
),
|
||||
);
|
||||
bodyBgColor = appStyle.colors.error15p;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -277,7 +197,7 @@ class _HomeTimetableMonthlyScreen
|
||||
bodyBgColor = appStyle.colors.cardTranslucent;
|
||||
}
|
||||
|
||||
bool isWeekend = d.weekday > 5 && lessonsToday.isEmpty;
|
||||
bool isWeekend = d.weekday > 5 && lessonCountToday == 0;
|
||||
Color textColor = (isWeekend
|
||||
? appStyle.colors.errorText
|
||||
: isToday
|
||||
@@ -318,6 +238,11 @@ class _HomeTimetableMonthlyScreen
|
||||
}
|
||||
}
|
||||
|
||||
final lessonsInMonth = widget.data.client!.cache.getClassLessons().between(
|
||||
currentMonthStart,
|
||||
currentMonthEnd,
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: appStyle.colors.background,
|
||||
body: Stack(
|
||||
@@ -415,15 +340,8 @@ class _HomeTimetableMonthlyScreen
|
||||
),
|
||||
),
|
||||
onTap: () async {
|
||||
var newNow = DateTime(now!.year, now!.month - 1);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
lessons = null;
|
||||
dates = null;
|
||||
});
|
||||
await initForMonth(newNow);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
now = DateTime(now!.year, now!.month - 1);
|
||||
});
|
||||
},
|
||||
),
|
||||
@@ -443,15 +361,8 @@ class _HomeTimetableMonthlyScreen
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
onTap: () async {
|
||||
var newNow = DateTime(now!.year, now!.month + 1);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
lessons = null;
|
||||
dates = null;
|
||||
});
|
||||
await initForMonth(newNow);
|
||||
setState(() {
|
||||
now = newNow;
|
||||
now = DateTime(now!.year, now!.month + 1);
|
||||
});
|
||||
},
|
||||
),
|
||||
@@ -490,13 +401,7 @@ class _HomeTimetableMonthlyScreen
|
||||
color: appStyle.colors.accent,
|
||||
size: 16,
|
||||
),
|
||||
lessons!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(currentMonthStart) &&
|
||||
lesson.end.isBefore(currentMonthEnd),
|
||||
)
|
||||
.length,
|
||||
lessonsInMonth.countSync(),
|
||||
activeFilter == ActiveFilter.lessonNo,
|
||||
() {
|
||||
setState(() {
|
||||
@@ -511,20 +416,7 @@ class _HomeTimetableMonthlyScreen
|
||||
color: appStyle.colors.accent,
|
||||
size: 16,
|
||||
),
|
||||
lessons!
|
||||
.where(
|
||||
(lesson) => tests!.any(
|
||||
(test) =>
|
||||
test.lessonNumber == lesson.lessonNumber &&
|
||||
lesson.start.isAfter(test.date.getMidnight()) &&
|
||||
lesson.end.isBefore(
|
||||
test.date.getMidnight().add(
|
||||
Duration(hours: 23, minutes: 59),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.length,
|
||||
lessonsInMonth.and().not().testIsNull().countSync(),
|
||||
activeFilter == ActiveFilter.tests,
|
||||
() {
|
||||
setState(() {
|
||||
@@ -539,18 +431,7 @@ class _HomeTimetableMonthlyScreen
|
||||
color: appStyle.colors.accent,
|
||||
size: 16,
|
||||
),
|
||||
lessons!
|
||||
.where(
|
||||
(lesson) =>
|
||||
lesson.start.isAfter(currentMonthStart) &&
|
||||
lesson.end.isBefore(currentMonthEnd) &&
|
||||
lesson.studentPresence != null &&
|
||||
lesson.studentPresence?.name !=
|
||||
OmissionConsts.na &&
|
||||
lesson.studentPresence?.name !=
|
||||
OmissionConsts.present,
|
||||
)
|
||||
.length,
|
||||
lessonsInMonth.and().not().omissionIsNull().countSync(),
|
||||
activeFilter == ActiveFilter.omissions,
|
||||
() {
|
||||
setState(() {
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/models/generic_cache_model.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka/data/models/timetable_cache_model.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/teacher_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/icon_helper.dart';
|
||||
import 'package:firka/core/profile_picture.dart';
|
||||
@@ -14,7 +22,6 @@ import 'package:image_picker/image_picker.dart';
|
||||
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -142,11 +149,6 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
);
|
||||
if (!context.mounted || d == null) return;
|
||||
try {
|
||||
await WidgetCacheHelper.generateWidgetStateForDate(
|
||||
d,
|
||||
appStyle,
|
||||
widget.data.client,
|
||||
);
|
||||
if (Platform.isAndroid) {
|
||||
await HomeWidget.updateWidget(
|
||||
qualifiedAndroidName:
|
||||
@@ -187,7 +189,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getStudent(): ${await widget.data.client.getStudent(forceCache: useCache)}",
|
||||
"getStudent(): ${await widget.data.client!.getStudent()}",
|
||||
);
|
||||
},
|
||||
child: const Text('getStudent()'),
|
||||
@@ -195,7 +197,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getNoticeBoard(): ${await widget.data.client.getNoticeBoard(forceCache: useCache)}",
|
||||
"getNoticeBoard(): ${await widget.data.client!.getNoticeBoard()}",
|
||||
);
|
||||
},
|
||||
child: const Text('getNoticeBoard()'),
|
||||
@@ -203,7 +205,15 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getGrades(): ${await widget.data.client.getGrades(forceCache: useCache)}",
|
||||
"getInfoBoard(): ${await widget.data.client!.getInfoBoard(from: timeNow())}",
|
||||
);
|
||||
},
|
||||
child: const Text('getInfoBoard()'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getGrades(): ${await widget.data.client!.getGrades()}",
|
||||
);
|
||||
},
|
||||
child: const Text('getGrades()'),
|
||||
@@ -216,7 +226,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
var end = now.add(Duration(days: 7));
|
||||
|
||||
logger.finest(
|
||||
"getLessons(): ${await widget.data.client.getTimeTable(start, end, forceCache: useCache)}",
|
||||
"getLessons(): ${await widget.data.client!.getLessons(start, end)}",
|
||||
);
|
||||
},
|
||||
child: const Text('getLessons()'),
|
||||
@@ -224,7 +234,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getHomework(): ${await widget.data.client.getHomework(forceCache: useCache)}",
|
||||
"getHomework(): ${await widget.data.client!.getHomework(from: timeNow())}",
|
||||
);
|
||||
},
|
||||
child: const Text('getHomework()'),
|
||||
@@ -232,7 +242,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getTests(): ${await widget.data.client.getTests(forceCache: useCache)}",
|
||||
"getTests(): ${await widget.data.client!.getTests(from: timeNow())}",
|
||||
);
|
||||
},
|
||||
child: const Text('getTests()'),
|
||||
@@ -240,7 +250,7 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
logger.finest(
|
||||
"getOmissions(): ${await widget.data.client.getOmissions(forceCache: useCache)}",
|
||||
"getOmissions(): ${await widget.data.client!.getOmissions()}",
|
||||
);
|
||||
},
|
||||
child: const Text('getOmissions()'),
|
||||
@@ -262,13 +272,18 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
onPressed: () async {
|
||||
final isar = widget.data.isar;
|
||||
await isar.writeTxn(() async {
|
||||
await isar.genericCacheModels.clear();
|
||||
await isar.timetableCacheModels.clear();
|
||||
await isar.subjectCacheModels.clear();
|
||||
await isar.testCacheModels.clear();
|
||||
await isar.gradeCacheModels.clear();
|
||||
await isar.omissionCacheModels.clear();
|
||||
await isar.messageCacheModels.clear();
|
||||
await isar.classGroupCacheModels.clear();
|
||||
await isar.classAverageCacheModels.clear();
|
||||
await isar.lessonCacheModels.clear();
|
||||
await isar.teacherModels.clear();
|
||||
await isar.homeworkCacheModels.clear();
|
||||
});
|
||||
widget.data.client.evictMemCache();
|
||||
if (Platform.isIOS) {
|
||||
await WidgetCacheHelper.clearIOSWidgets();
|
||||
} else {
|
||||
final dataDir = await getApplicationDocumentsDirectory();
|
||||
final widgetFile = File(
|
||||
@@ -300,8 +315,6 @@ class _DebugScreen extends FirkaState<DebugScreen> {
|
||||
await isar.tokenModels.clear();
|
||||
});
|
||||
|
||||
widget.data.tokens = List.empty(growable: true);
|
||||
|
||||
if (!context.mounted) return;
|
||||
context.go('/login');
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/components/firka_button.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:firka/api/client/kreta_stream.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/services/active_account_helper.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/services/watch_sync_helper.dart';
|
||||
@@ -18,7 +16,6 @@ import 'package:flutter/services.dart';
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/core/debug_helper.dart';
|
||||
import 'package:firka/core/bloc/profile_picture_cubit.dart';
|
||||
import 'package:firka/core/bloc/reauth_cubit.dart';
|
||||
@@ -31,7 +28,7 @@ import '../../pages/extras/main_error.dart';
|
||||
|
||||
enum ActiveToastType { fetching, error, reauth, none }
|
||||
|
||||
bool _fetching = true;
|
||||
bool _fetching = false;
|
||||
bool _prefetched = false;
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
@@ -49,7 +46,6 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
bool _disposed = false;
|
||||
bool _preloadDone = false;
|
||||
bool _didRunSecondaryICloudRecovery = false;
|
||||
bool _prefetchInProgress = false;
|
||||
bool _didRunLiveActivityLogin = false;
|
||||
bool _hasCompletedFirstPrefetch = false;
|
||||
|
||||
@@ -113,15 +109,11 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
if (!Platform.isIOS || _didRunSecondaryICloudRecovery) return;
|
||||
_didRunSecondaryICloudRecovery = true;
|
||||
|
||||
final activeToken = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: initData.client.model.studentIdNorm,
|
||||
);
|
||||
final activeToken = initData.client!.cache.token;
|
||||
|
||||
final now = DateTime.now();
|
||||
final shouldRunRecovery =
|
||||
initData.client.needsReauth ||
|
||||
initData.client!.needsReauth ||
|
||||
activeToken == null ||
|
||||
activeToken.expiryDate == null ||
|
||||
activeToken.expiryDate!.isBefore(now.add(const Duration(seconds: 60)));
|
||||
@@ -137,7 +129,6 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
try {
|
||||
final recovered = await WatchSyncHelper.checkAndRecoverFromiCloud(
|
||||
isar: initData.isar,
|
||||
tokens: initData.tokens,
|
||||
client: initData.client,
|
||||
);
|
||||
if (!recovered) {
|
||||
@@ -145,17 +136,6 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
return;
|
||||
}
|
||||
|
||||
final refreshedTokens = initDone ? initData.tokens : initData.tokens;
|
||||
initData.tokens = refreshedTokens;
|
||||
|
||||
final selectedToken = pickActiveToken(
|
||||
tokens: refreshedTokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: initData.client.model.studentIdNorm,
|
||||
);
|
||||
if (selectedToken != null) {
|
||||
initData.client.model = selectedToken;
|
||||
}
|
||||
initData.reauthCubit?.clear();
|
||||
logger.info('[Home] Secondary iCloud recovery applied a fresher token');
|
||||
} catch (e) {
|
||||
@@ -164,8 +144,7 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
|
||||
void prefetch() async {
|
||||
if (_prefetched) return;
|
||||
if (_prefetchInProgress) return;
|
||||
if (_prefetched || _fetching) return;
|
||||
|
||||
final lifecycle = WidgetsBinding.instance.lifecycleState;
|
||||
if (lifecycle != null && lifecycle != AppLifecycleState.resumed) {
|
||||
@@ -175,14 +154,16 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
return;
|
||||
}
|
||||
|
||||
_prefetchInProgress = true;
|
||||
setState(() {
|
||||
_fetching = true;
|
||||
});
|
||||
try {
|
||||
_prefetched = true;
|
||||
|
||||
await _runSecondaryICloudRecoveryIfNeeded();
|
||||
|
||||
try {
|
||||
await initData.client.refreshTokenProactively().timeout(
|
||||
await initData.client!.refreshTokenProactively().timeout(
|
||||
const Duration(seconds: 60),
|
||||
onTimeout: () {
|
||||
logger.warning('[Home] Token refresh/recovery timed out after 60s');
|
||||
@@ -193,10 +174,10 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
logger.warning('[Home] Token refresh/recovery failed: $e');
|
||||
}
|
||||
|
||||
await fetchData();
|
||||
await initData.client!.renewCache(reInit: true);
|
||||
initData.homeRefreshCubit.requestRefresh();
|
||||
|
||||
if (Platform.isAndroid) {
|
||||
await WidgetCacheHelper.updateWidgetCache(appStyle, initData.client);
|
||||
await HomeWidget.updateWidget(
|
||||
qualifiedAndroidName:
|
||||
"app.firka.naplo.glance.TimetableWidgetReceiver",
|
||||
@@ -204,20 +185,12 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
|
||||
if (Platform.isIOS) {
|
||||
await WidgetCacheHelper.refreshIOSWidgets(
|
||||
initData.client,
|
||||
initData.settings,
|
||||
);
|
||||
|
||||
if (!_didRunLiveActivityLogin) {
|
||||
_didRunLiveActivityLogin = true;
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
final studentName = token?.studentId ?? "Student";
|
||||
final token = initData.client!.cache.token;
|
||||
final studentName = token?.username ?? "Student";
|
||||
LiveActivityService.onUserLogin(
|
||||
client: initData.client,
|
||||
client: initData.client!,
|
||||
studentName: studentName,
|
||||
settingsStore: initData.settings,
|
||||
).catchError((e, st) {
|
||||
@@ -227,7 +200,8 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
|
||||
if (!_disposed &&
|
||||
(LiveActivityService.isTokenExpired || initData.client.needsReauth)) {
|
||||
(LiveActivityService.isTokenExpired ||
|
||||
initData.client!.needsReauth)) {
|
||||
activeToast = ActiveToastType.reauth;
|
||||
setState(() {
|
||||
toast = buildReauthToast(context, initData, () {
|
||||
@@ -318,7 +292,6 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
_prefetchInProgress = false;
|
||||
_hasCompletedFirstPrefetch = true;
|
||||
if (!_disposed) {
|
||||
setState(() {
|
||||
@@ -329,69 +302,6 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchData() async {
|
||||
var lessonsFetched = 0;
|
||||
var noticeBoardFetched = 0;
|
||||
var infoBoardFetched = 0;
|
||||
var studentFetched = 0;
|
||||
var testsFetched = 0;
|
||||
var gradesFetched = 0;
|
||||
var homeworkFetched = 0;
|
||||
|
||||
final midnight = timeNow().getMidnight();
|
||||
|
||||
initData.client
|
||||
.getTimeTableStream(
|
||||
midnight,
|
||||
midnight.add(Duration(hours: 23, minutes: 59)),
|
||||
cacheOnly: false,
|
||||
)
|
||||
.forEach((lessons) {
|
||||
lessonsFetched++;
|
||||
});
|
||||
|
||||
initData.client.getNoticeBoardStream(cacheOnly: false).forEach((items) {
|
||||
noticeBoardFetched++;
|
||||
});
|
||||
|
||||
initData.client.getInfoBoardStream(cacheOnly: false).forEach((items) {
|
||||
infoBoardFetched++;
|
||||
});
|
||||
|
||||
initData.client.getStudentStream(cacheOnly: false).forEach((student) {
|
||||
studentFetched++;
|
||||
});
|
||||
|
||||
initData.client.getTestsStream(cacheOnly: false).forEach((tests) {
|
||||
testsFetched++;
|
||||
});
|
||||
|
||||
initData.client.getGradesStream(cacheOnly: false).forEach((grades) {
|
||||
gradesFetched++;
|
||||
});
|
||||
|
||||
initData.client.getHomeworkStream(cacheOnly: false).forEach((homework) {
|
||||
homeworkFetched++;
|
||||
});
|
||||
|
||||
final startTime = DateTime.now();
|
||||
const maxWaitTime = Duration(seconds: 30);
|
||||
|
||||
while (lessonsFetched < 2 ||
|
||||
noticeBoardFetched < 2 ||
|
||||
infoBoardFetched < 2 ||
|
||||
studentFetched < 2 ||
|
||||
testsFetched < 2 ||
|
||||
gradesFetched < 2 ||
|
||||
homeworkFetched < 2) {
|
||||
if (DateTime.now().difference(startTime) > maxWaitTime) {
|
||||
logger.warning('[Home] fetchData timed out after 30s');
|
||||
break;
|
||||
}
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -417,7 +327,7 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _preloadImages() async {
|
||||
void _preloadImages() async {
|
||||
final imagePaths = initData.settings.appIcons.keys
|
||||
.map((icon) => "assets/images/icons/$icon.webp")
|
||||
.toList();
|
||||
@@ -425,12 +335,12 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
|
||||
try {
|
||||
await ImagePreloader.preloadMultipleAssets(FirkaBundle(), imagePaths);
|
||||
if (!mounted) return;
|
||||
setState(() => _preloadDone = true);
|
||||
} catch (e) {
|
||||
logger.severe('Home: error preloading images: $e');
|
||||
if (!mounted) return;
|
||||
setState(() => _preloadDone = true);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _preloadDone = true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,43 +365,41 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
|
||||
if (_fetching) {
|
||||
if (_disposed) return const SizedBox.shrink();
|
||||
setState(() {
|
||||
activeToast = ActiveToastType.fetching;
|
||||
toast = Positioned(
|
||||
top: MediaQuery.of(context).size.height / 1.6,
|
||||
left: 0.0,
|
||||
right: 0.0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: Card(
|
||||
color: appStyle.colors.card,
|
||||
shadowColor: Colors.transparent,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
activeToast = ActiveToastType.fetching;
|
||||
toast = Positioned(
|
||||
top: MediaQuery.of(context).size.height / 1.6,
|
||||
left: 0.0,
|
||||
right: 0.0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: Card(
|
||||
color: appStyle.colors.card,
|
||||
shadowColor: Colors.transparent,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
color: appStyle.colors.accent,
|
||||
),
|
||||
SizedBox(width: 16),
|
||||
Text(
|
||||
initData.l10n.refreshing,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 16),
|
||||
Text(
|
||||
initData.l10n.refreshing,
|
||||
style: appStyle.fonts.B_16SB.copyWith(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
@@ -537,6 +445,7 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
_prefetched = false;
|
||||
_didRunSecondaryICloudRecovery = false;
|
||||
prefetch();
|
||||
setState(() {});
|
||||
|
||||
if (Platform.isIOS) {
|
||||
_refreshLiveActivityOnResume();
|
||||
@@ -552,14 +461,9 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
Future.delayed(const Duration(milliseconds: 500), () async {
|
||||
if (_disposed || _didRunLiveActivityLogin) return;
|
||||
_didRunLiveActivityLogin = true;
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
preferredStudentIdNorm: initData.client.model.studentIdNorm,
|
||||
);
|
||||
final studentName = token?.studentId ?? 'Student';
|
||||
final studentName = initData.client!.cache.token.username ?? 'Student';
|
||||
LiveActivityService.onUserLogin(
|
||||
client: initData.client,
|
||||
client: initData.client!,
|
||||
studentName: studentName,
|
||||
settingsStore: initData.settings,
|
||||
).catchError((e, st) {
|
||||
@@ -572,13 +476,9 @@ class _HomeScreenState extends FirkaState<HomeScreen>
|
||||
void _refreshLiveActivityOnResume() async {
|
||||
if (!_hasCompletedFirstPrefetch) return;
|
||||
try {
|
||||
final token = pickActiveToken(
|
||||
tokens: initData.tokens,
|
||||
settings: initData.settings,
|
||||
);
|
||||
final studentName = token?.studentId ?? "Student";
|
||||
final studentName = initData.client!.cache.token.username ?? "Student";
|
||||
await LiveActivityService.checkAndUpdateTimetable(
|
||||
client: initData.client,
|
||||
client: initData.client!,
|
||||
studentName: studentName,
|
||||
settingsStore: initData.settings,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:firka/ui/components/firka_button.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/phone/screens/live_activity/full_privacy_policy_screen.dart';
|
||||
|
||||
@@ -2,11 +2,12 @@ import 'dart:collection';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/core/image_preloader.dart';
|
||||
import 'package:firka/ui/components/firka_button.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
@@ -19,8 +20,6 @@ import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import 'package:firka/data/widget.dart';
|
||||
import 'package:firka/core/firka_bundle.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
@@ -44,6 +43,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
|
||||
bool settingAppIcon = false;
|
||||
late String activeIcon;
|
||||
late List<TokenModel> tokens;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -54,6 +54,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
.subGroup("customization")
|
||||
.subGroup("icon_picker")
|
||||
.iconString("icon_picker");
|
||||
tokens = isarInit.tokenModels.where().sortByUpdatedAtMsDesc().findAllSync();
|
||||
}
|
||||
|
||||
List<Widget> createWidgetTree(
|
||||
@@ -356,15 +357,14 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
return appStyle.colors.secondary;
|
||||
}),
|
||||
onChanged: (_) async {
|
||||
setState(() {
|
||||
item.activeIndex = i;
|
||||
});
|
||||
item.activeIndex = i;
|
||||
|
||||
await widget.data.isar.writeTxn(() async {
|
||||
await item.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
await item.postUpdate();
|
||||
setState(() {});
|
||||
logger.finest('Settings saved');
|
||||
},
|
||||
),
|
||||
@@ -389,15 +389,15 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
right: [SizedBox(height: 16 + 8)],
|
||||
),
|
||||
onTap: () async {
|
||||
setState(() {
|
||||
item.activeIndex = i;
|
||||
});
|
||||
item.activeIndex = i;
|
||||
|
||||
await widget.data.isar.writeTxn(() async {
|
||||
await item.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
await item.postUpdate();
|
||||
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -756,13 +756,23 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
|
||||
await Future.delayed(Duration(seconds: 1));
|
||||
|
||||
const channel = MethodChannel('firka.app/main');
|
||||
await channel.invokeMethod('set_icon', {
|
||||
"icon": activeIcon == "original" ? null : activeIcon,
|
||||
"icons": settings.appIcons.keys
|
||||
logger.info(
|
||||
settings.appIcons.keys
|
||||
.where((e) => e != "original")
|
||||
.join(","),
|
||||
});
|
||||
);
|
||||
|
||||
logger.info(activeIcon);
|
||||
|
||||
const channel = MethodChannel('firka.app/main');
|
||||
logger.info(
|
||||
await channel.invokeMethod('set_icon', {
|
||||
"icon": activeIcon == "original" ? null : activeIcon,
|
||||
"icons": settings.appIcons.keys
|
||||
.where((e) => e != "original")
|
||||
.join(","),
|
||||
}),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
@@ -772,15 +782,14 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
continue;
|
||||
}
|
||||
if (item is SettingsKretenAccountPicker) {
|
||||
for (var i = 0; i < widget.data.tokens.length; i++) {
|
||||
final token = widget.data.tokens[i];
|
||||
for (TokenModel token in tokens) {
|
||||
final jwt = JWT.decode(token.idToken!);
|
||||
String studentRole;
|
||||
final payload = jwt.payload as Map<String, dynamic>;
|
||||
if (payload["role"] == "Tanulo") {
|
||||
String studentRole = payload["role"];
|
||||
if (studentRole == "Tanulo") {
|
||||
studentRole = "Tanuló";
|
||||
} else {
|
||||
studentRole = payload["role"];
|
||||
} else if (studentRole == "Gondviselo") {
|
||||
studentRole = "Gondviselő";
|
||||
}
|
||||
widgets.add(
|
||||
GestureDetector(
|
||||
@@ -803,7 +812,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
),
|
||||
],
|
||||
right: [
|
||||
i != item.accountIndex
|
||||
token.key != item.accountKey
|
||||
? SizedBox()
|
||||
: Checkbox(
|
||||
value: true,
|
||||
@@ -831,82 +840,82 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
onTap: () async {
|
||||
if (i != item.accountIndex) {
|
||||
final previousAccountId =
|
||||
widget.data.client.model.studentIdNorm;
|
||||
if (Platform.isIOS) {
|
||||
await LiveActivityService.onUserLogout();
|
||||
try {
|
||||
await WatchSyncHelper.clearSharedLanguageState();
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to clear shared language state on account switch: $e',
|
||||
);
|
||||
}
|
||||
if (previousAccountId != null) {
|
||||
try {
|
||||
await WatchSyncHelper.clearRefreshLeaseForAccount(
|
||||
previousAccountId,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to clear refresh lease on account switch: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await widget.data.isar.writeTxn(() async {
|
||||
item.accountIndex = i;
|
||||
|
||||
await item.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
await item.postUpdate();
|
||||
|
||||
if (Platform.isIOS) {
|
||||
var watchReachable = false;
|
||||
try {
|
||||
watchReachable = await WatchSyncHelper.isWatchReachable(
|
||||
forceRefreshInstall: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to query Watch reachability on account switch: $e',
|
||||
);
|
||||
}
|
||||
|
||||
if (watchReachable) {
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenModelToWatch(
|
||||
token,
|
||||
allowExpiredAccessToken: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to send switched account token to reachable Watch: $e',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(
|
||||
token,
|
||||
forceAccountSwitch: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to sync switched account token to iCloud: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await initializeApp();
|
||||
if (!mounted) return;
|
||||
final nav = Navigator.of(context);
|
||||
if (nav.canPop()) nav.pop();
|
||||
appRouter?.go('/home');
|
||||
if (token.key == item.accountKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
final previousAccountId = widget.data.client!.cache.token.key;
|
||||
if (Platform.isIOS) {
|
||||
await LiveActivityService.onUserLogout();
|
||||
try {
|
||||
await WatchSyncHelper.clearSharedLanguageState();
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to clear shared language state on account switch: $e',
|
||||
);
|
||||
}
|
||||
if (previousAccountId != null) {
|
||||
try {
|
||||
await WatchSyncHelper.clearRefreshLeaseForAccount(
|
||||
previousAccountId,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to clear refresh lease on account switch: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await widget.data.isar.writeTxn(() async {
|
||||
item.accountKey = token.key;
|
||||
|
||||
await item.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
await item.postUpdate();
|
||||
|
||||
if (Platform.isIOS) {
|
||||
var watchReachable = false;
|
||||
try {
|
||||
watchReachable = await WatchSyncHelper.isWatchReachable(
|
||||
forceRefreshInstall: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to query Watch reachability on account switch: $e',
|
||||
);
|
||||
}
|
||||
|
||||
if (watchReachable) {
|
||||
try {
|
||||
await WatchSyncHelper.sendTokenModelToWatch(
|
||||
token,
|
||||
allowExpiredAccessToken: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to send switched account token to reachable Watch: $e',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await WatchSyncHelper.saveTokenToiCloud(
|
||||
token,
|
||||
forceAccountSwitch: true,
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warning(
|
||||
'[Settings] Failed to sync switched account token to iCloud: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
final nav = Navigator.of(context);
|
||||
if (nav.canPop()) nav.pop();
|
||||
appRouter?.go('/home');
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -964,10 +973,9 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
try {
|
||||
if (Platform.isIOS) {
|
||||
await LiveActivityService.onUserLogout();
|
||||
await WidgetCacheHelper.clearIOSWidgets();
|
||||
}
|
||||
|
||||
final active = widget.data.client.model.studentIdNorm!;
|
||||
final active = widget.data.client!.cache.token.key;
|
||||
if (Platform.isIOS) {
|
||||
try {
|
||||
await WatchSyncHelper.clearRefreshLeaseForAccount(active);
|
||||
@@ -988,7 +996,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
await widget.data.isar.writeTxn(() async {
|
||||
await widget.data.isar.tokenModels.delete(active);
|
||||
|
||||
item.accountIndex = 0;
|
||||
item.accountKey = 0;
|
||||
await item.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
@@ -1006,7 +1014,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
'[Settings] Failed to clear iCloud token: $e',
|
||||
);
|
||||
}
|
||||
initData.client.clearReauthFlag();
|
||||
initData.client!.clearReauthFlag();
|
||||
}
|
||||
} else {
|
||||
if (Platform.isIOS) {
|
||||
@@ -1046,8 +1054,6 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
widget.data.tokens = accounts;
|
||||
}
|
||||
|
||||
await initializeApp();
|
||||
|
||||
@@ -55,7 +55,9 @@ class BottomNavIconWidget extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
FittedBox(
|
||||
alignment: Alignment.bottomCenter,
|
||||
fit: BoxFit.scaleDown,
|
||||
clipBehavior: Clip.none,
|
||||
child: Text(
|
||||
text,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka_common/firka_common.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/routing/chart_interaction_scope.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class GradeChart extends StatefulWidget {
|
||||
final List<Grade> grades;
|
||||
final List<GradeCacheModel> grades;
|
||||
final bool halfYearFallback;
|
||||
GradeChart({
|
||||
super.key,
|
||||
required List<Grade> grades,
|
||||
required List<GradeCacheModel> grades,
|
||||
this.halfYearFallback = true,
|
||||
}) : grades = grades.where((g) => g.hasClassicValue()).toList()
|
||||
..sort((a, b) => a.recordDate.compareTo(b.recordDate));
|
||||
..sort((a, b) => a.writtenAt.compareTo(b.writtenAt));
|
||||
|
||||
@override
|
||||
State<GradeChart> createState() => _GradeChartState();
|
||||
@@ -59,7 +60,7 @@ class _GradeChartState extends State<GradeChart> {
|
||||
.getSubjectAverage(halfYearFallback: widget.halfYearFallback);
|
||||
|
||||
spots.add(
|
||||
DateSpot(spots.length.toDouble(), partialAvg!, grade.recordDate),
|
||||
DateSpot(spots.length.toDouble(), partialAvg!, grade.writtenAt),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ class _GradeChartState extends State<GradeChart> {
|
||||
DateSpot(
|
||||
spots.length.toDouble(),
|
||||
grade.numericValue!.toDouble(),
|
||||
grade.recordDate,
|
||||
grade.writtenAt,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -357,7 +358,7 @@ class _GradeChartState extends State<GradeChart> {
|
||||
/// Wraps [GradeChart] with a [Listener] that updates [ChartInteractionScope]
|
||||
/// so the navigator does not intercept touch/drag (e.g. for swipe back).
|
||||
class GradeChartWithInteraction extends StatelessWidget {
|
||||
final List<Grade> grades;
|
||||
final List<GradeCacheModel> grades;
|
||||
final bool halfYearFallback;
|
||||
|
||||
const GradeChartWithInteraction({
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/grade.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
@@ -10,7 +11,7 @@ import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class GradeSummaryBar extends StatefulWidget {
|
||||
final List<Grade> grades;
|
||||
final List<GradeCacheModel> grades;
|
||||
final AppLocalizations l10n;
|
||||
final bool showAverage;
|
||||
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka/ui/shared/counter_digit.dart';
|
||||
import 'package:firka_common/firka_common.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
class StartingSoonWidget extends StatelessWidget {
|
||||
final AppLocalizations l10n;
|
||||
final List<Lesson> lessons;
|
||||
final List<LessonCacheModel> lessons;
|
||||
final DateTime now;
|
||||
|
||||
const StartingSoonWidget(this.l10n, this.now, this.lessons, {super.key});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'package:confetti/confetti.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
@@ -11,8 +13,8 @@ import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class WelcomeWidget extends StatefulWidget {
|
||||
final AppLocalizations l10n;
|
||||
final Student student;
|
||||
final List<Lesson> lessons;
|
||||
final StudentCacheModel student;
|
||||
final List<LessonCacheModel> lessons;
|
||||
final DateTime now;
|
||||
|
||||
const WelcomeWidget(
|
||||
@@ -37,7 +39,7 @@ class _WelcomeWidgetState extends State<WelcomeWidget> {
|
||||
duration: const Duration(seconds: 2),
|
||||
);
|
||||
|
||||
final birthDate = DateFormat("MM-dd").format(widget.student.birthdate);
|
||||
final birthDate = DateFormat("MM-dd").format(widget.student.birthday);
|
||||
if (birthDate == DateFormat("MM-dd").format(widget.now)) {
|
||||
_controllerCenter.play();
|
||||
}
|
||||
@@ -100,7 +102,7 @@ class _WelcomeWidgetState extends State<WelcomeWidget> {
|
||||
name = widget.student.name;
|
||||
}
|
||||
|
||||
final birthDate = DateFormat("MM-dd").format(widget.student.birthdate);
|
||||
final birthDate = DateFormat("MM-dd").format(widget.student.birthday);
|
||||
if (birthDate == DateFormat("MM-dd").format(widget.now)) {
|
||||
return widget.l10n.happy_birthday(name);
|
||||
} else if (widget.lessons.length > 1 &&
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka/ui/components/common_bottom_sheets.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/grade.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -35,17 +42,19 @@ class InfoCard extends StatelessWidget {
|
||||
super.key,
|
||||
});
|
||||
|
||||
static Widget buildSubject(Color color, Subject subject) {
|
||||
static Widget buildSubject(Color color, SubjectCacheModel subject) {
|
||||
return FilledCircle(
|
||||
diameter: 32,
|
||||
color: color.withAlpha(38),
|
||||
child: ClassIconWidget.subject(subject: subject, color: color, size: 20),
|
||||
child: ClassIconWidget(subject: subject, color: color, size: 20),
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.test(Test test) {
|
||||
factory InfoCard.test(TestCacheModel test) {
|
||||
final color = appStyle.colors.accent;
|
||||
|
||||
final subject = test.lesson.loadAndGet()!.subject.loadAndGet()!;
|
||||
|
||||
return InfoCard(
|
||||
icon: FilledCircle(
|
||||
diameter: 36,
|
||||
@@ -58,19 +67,21 @@ class InfoCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
texts: [
|
||||
test.theme?.firstUpper() ?? test.method.description,
|
||||
test.subject.name.firstUpper(),
|
||||
test.topic?.firstUpper() ?? test.method,
|
||||
subject.name.firstUpper(),
|
||||
],
|
||||
right: [buildSubject(color, test.subject)],
|
||||
right: [buildSubject(color, subject)],
|
||||
onTap: (context) => showTestBottomSheet(context, initData, test),
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.testDesc(Test test) {
|
||||
if (test.theme == null) {
|
||||
factory InfoCard.testDesc(TestCacheModel test) {
|
||||
if (test.topic == null) {
|
||||
return InfoCard.test(test);
|
||||
}
|
||||
|
||||
final subject = test.lesson.loadAndGet()!.subject.loadAndGet()!;
|
||||
|
||||
final color = appStyle.colors.accent;
|
||||
|
||||
return InfoCard(
|
||||
@@ -84,13 +95,13 @@ class InfoCard extends StatelessWidget {
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
texts: [test.theme!.firstUpper(), test.method.description.firstUpper()],
|
||||
right: [buildSubject(color, test.subject)],
|
||||
texts: [test.topic!.firstUpper(), test.method.firstUpper()],
|
||||
right: [buildSubject(color, subject)],
|
||||
onTap: (context) => showTestBottomSheet(context, initData, test),
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.messageItem(MessageItem item) {
|
||||
factory InfoCard.messageItem(MessageCacheModel item) {
|
||||
return InfoCard(
|
||||
icon: FilledCircle(
|
||||
diameter: 36,
|
||||
@@ -105,7 +116,7 @@ class InfoCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.omission(List<Omission> omissions) {
|
||||
factory InfoCard.omission(List<OmissionCacheModel> omissions) {
|
||||
String title = "-";
|
||||
Color color = appStyle.colors.accent;
|
||||
FirkaIconType iconType = FirkaIconType.majesticons;
|
||||
@@ -152,68 +163,56 @@ class InfoCard extends StatelessWidget {
|
||||
title,
|
||||
DateFormat.MMMMd(
|
||||
initData.l10n.localeName,
|
||||
).format(omissions.first.date).firstUpper(),
|
||||
).format(omissions.first.createdAt).firstUpper(),
|
||||
],
|
||||
onTap: (context) =>
|
||||
showOmissionBottomSheet(context, initData, title, omissions),
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.homework(Homework homework) {
|
||||
factory InfoCard.homework(HomeworkCacheModel homework) {
|
||||
final subject = homework.subject.loadAndGet()!;
|
||||
return InfoCard(
|
||||
icon: FilledCircle(
|
||||
diameter: 36,
|
||||
color: appStyle.colors.accent.withAlpha(38),
|
||||
child: FutureBuilder<bool>(
|
||||
future: isHomeworkDone(initData.isar, homework.uid),
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return SizedBox();
|
||||
}
|
||||
final done = snapshot.data!;
|
||||
return done
|
||||
? FirkaIconWidget(
|
||||
FirkaIconType.majesticonsLocal,
|
||||
"homeWithMark",
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
)
|
||||
: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.homeSolid,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
);
|
||||
},
|
||||
),
|
||||
child: homework.isDone
|
||||
? FirkaIconWidget(
|
||||
FirkaIconType.majesticonsLocal,
|
||||
"homeWithMark",
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
)
|
||||
: FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.homeSolid,
|
||||
color: appStyle.colors.accent,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
texts: [initData.l10n.homework, homework.subjectName],
|
||||
right: [buildSubject(appStyle.colors.accent, homework.subject)],
|
||||
texts: [initData.l10n.homework, subject.name],
|
||||
right: [buildSubject(appStyle.colors.accent, subject)],
|
||||
onTap: (context) => showHomeworkBottomSheet(context, initData, homework),
|
||||
);
|
||||
}
|
||||
|
||||
factory InfoCard.gradeSubj(
|
||||
Grade grade, {
|
||||
GradeCacheModel grade, {
|
||||
void Function(BuildContext)? onTap,
|
||||
}) {
|
||||
String? value = grade.numericValue == null ? grade.strValue : null;
|
||||
String? value = grade.numericValue == null ? grade.textValue : null;
|
||||
return InfoCard(
|
||||
icon: GradeWidget(grade),
|
||||
texts: [
|
||||
(value ??
|
||||
grade.topic ??
|
||||
grade.mode?.description ??
|
||||
grade.type.description!)
|
||||
.firstUpper(),
|
||||
grade.subject.name.firstUpper(),
|
||||
(value ?? grade.topic ?? grade.mode ?? grade.type).firstUpper(),
|
||||
grade.subject.loadAndGet()!.name.firstUpper(),
|
||||
],
|
||||
right: [
|
||||
buildSubject(
|
||||
grade.numericValue != null
|
||||
? getGradeColor(grade.numericValue!)
|
||||
: appStyle.colors.accent,
|
||||
grade.subject,
|
||||
grade.subject.loadAndGet()!,
|
||||
),
|
||||
],
|
||||
onTap:
|
||||
@@ -235,12 +234,10 @@ class InfoCard extends StatelessWidget {
|
||||
}
|
||||
|
||||
factory InfoCard.gradeDesc(
|
||||
Grade grade, {
|
||||
GradeCacheModel grade, {
|
||||
void Function(BuildContext)? onTap,
|
||||
}) {
|
||||
List<String> texts = [
|
||||
(grade.mode?.description ?? grade.type.description!).firstUpper(),
|
||||
];
|
||||
List<String> texts = [(grade.mode ?? grade.type).firstUpper()];
|
||||
|
||||
if (grade.topic != null) {
|
||||
texts = [grade.topic!.firstUpper(), ...texts];
|
||||
@@ -249,7 +246,9 @@ class InfoCard extends StatelessWidget {
|
||||
return InfoCard(
|
||||
icon: GradeWidget(grade),
|
||||
texts: texts,
|
||||
right: [buildSubject(appStyle.colors.accent, grade.subject)],
|
||||
right: [
|
||||
buildSubject(appStyle.colors.accent, grade.subject.loadAndGet()!),
|
||||
],
|
||||
onTap:
|
||||
onTap ?? (context) => showGradeBottomSheet(context, initData, grade),
|
||||
);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
@@ -16,25 +19,22 @@ import 'bubble_test.dart';
|
||||
|
||||
class LessonWidget extends StatelessWidget {
|
||||
final AppInitialization data;
|
||||
final Lesson lesson;
|
||||
final LessonCacheModel lesson;
|
||||
final bool active;
|
||||
final Test? test;
|
||||
|
||||
const LessonWidget(
|
||||
this.data,
|
||||
this.lesson,
|
||||
this.test, {
|
||||
this.active = false,
|
||||
super.key,
|
||||
});
|
||||
const LessonWidget(this.data, this.lesson, {this.active = false, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// we dont like events
|
||||
assert(lesson.type != TimetableConsts.event);
|
||||
final showTests = data.settings
|
||||
.group("settings")
|
||||
.subGroup("timetable_toast")
|
||||
.boolean("tests_and_homework");
|
||||
|
||||
final test = lesson.test.loadAndGet();
|
||||
|
||||
final isSubstituted = lesson.substituteTeacher != null;
|
||||
final showSubstitutions =
|
||||
isSubstituted &&
|
||||
@@ -46,7 +46,7 @@ class LessonWidget extends StatelessWidget {
|
||||
.group("settings")
|
||||
.subGroup("timetable_toast")
|
||||
.boolean("lesson_no");
|
||||
final isDismissed = lesson.type.name == "UresOra";
|
||||
final isDismissed = lesson.type == "UresOra";
|
||||
|
||||
var accent = appStyle.colors.accent;
|
||||
var secondary = appStyle.colors.secondary;
|
||||
@@ -65,9 +65,9 @@ class LessonWidget extends StatelessWidget {
|
||||
|
||||
List<Widget> elements = [];
|
||||
|
||||
var subjectName = lesson.subject?.name.firstUpper() ?? 'N/A';
|
||||
var subjectName = lesson.subject.loadAndGet()!.name.firstUpper();
|
||||
|
||||
var roomName = lesson.roomName ?? 'N/A';
|
||||
var roomName = lesson.roomName;
|
||||
|
||||
elements.add(
|
||||
GestureDetector(
|
||||
@@ -79,7 +79,6 @@ class LessonWidget extends StatelessWidget {
|
||||
accent,
|
||||
secondary,
|
||||
bgColor,
|
||||
test,
|
||||
);
|
||||
},
|
||||
child: FirkaCard.single(
|
||||
@@ -113,7 +112,7 @@ class LessonWidget extends StatelessWidget {
|
||||
height: 18,
|
||||
),
|
||||
Text(
|
||||
lesson.lessonNumber?.toString() ?? "-",
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_14SB.apply(
|
||||
color: secondary,
|
||||
),
|
||||
@@ -126,9 +125,7 @@ class LessonWidget extends StatelessWidget {
|
||||
diameter: 36,
|
||||
color: bgColor,
|
||||
child: ClassIconWidget(
|
||||
uid: lesson.uid,
|
||||
className: lesson.name,
|
||||
category: subjectName,
|
||||
subject: lesson.subject.loadAndGet()!,
|
||||
color: accent,
|
||||
size: 24,
|
||||
),
|
||||
@@ -194,7 +191,7 @@ class LessonWidget extends StatelessWidget {
|
||||
horizontal: 6,
|
||||
),
|
||||
child: Text(
|
||||
roomName,
|
||||
roomName!,
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
@@ -242,13 +239,13 @@ class LessonWidget extends StatelessWidget {
|
||||
);
|
||||
|
||||
if (test != null && showTests) {
|
||||
var theme = test!.theme?.firstUpper() ?? "";
|
||||
var method = test!.method.description.firstUpper();
|
||||
var topic = test.topic?.firstUpper() ?? "";
|
||||
var method = test.method.firstUpper();
|
||||
|
||||
elements.add(
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
showTestBottomSheet(context, data, test!);
|
||||
showTestBottomSheet(context, data, test);
|
||||
},
|
||||
child: FirkaCard.single(
|
||||
height: 48,
|
||||
@@ -267,7 +264,7 @@ class LessonWidget extends StatelessWidget {
|
||||
LimitedBox(
|
||||
maxWidth: 160,
|
||||
child: Text(
|
||||
theme,
|
||||
topic,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
@@ -15,24 +18,23 @@ import 'package:firka/ui/shared/firka_icon.dart';
|
||||
|
||||
class LessonBigWidget extends StatelessWidget {
|
||||
final AppInitialization data;
|
||||
final int lessonNo;
|
||||
final Lesson lesson;
|
||||
final Test? test;
|
||||
final LessonCacheModel lesson;
|
||||
final bool active;
|
||||
|
||||
const LessonBigWidget(
|
||||
this.data,
|
||||
this.lessonNo,
|
||||
this.lesson,
|
||||
this.test, {
|
||||
this.lesson, {
|
||||
this.active = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// we dont like events
|
||||
assert(lesson.type != TimetableConsts.event);
|
||||
final isSubstituted = lesson.substituteTeacher != null;
|
||||
final isDismissed = lesson.type.name == "UresOra";
|
||||
final isDismissed = lesson.type == "UresOra";
|
||||
final test = lesson.test.loadAndGet();
|
||||
|
||||
var accent = appStyle.colors.accent;
|
||||
var secondary = appStyle.colors.secondary;
|
||||
@@ -49,9 +51,9 @@ class LessonBigWidget extends StatelessWidget {
|
||||
bgColor = appStyle.colors.error15p;
|
||||
}
|
||||
|
||||
var subjectName = lesson.subject?.name.firstUpper() ?? 'N/A';
|
||||
var subjectName = lesson.subject.loadAndGet()!.name.firstUpper();
|
||||
|
||||
var roomName = lesson.roomName ?? 'N/A';
|
||||
var roomName = lesson.roomName;
|
||||
|
||||
Widget extra = test == null
|
||||
? Column(
|
||||
@@ -112,7 +114,7 @@ class LessonBigWidget extends StatelessWidget {
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
test!.theme ?? "",
|
||||
test.topic ?? "",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -132,7 +134,6 @@ class LessonBigWidget extends StatelessWidget {
|
||||
accent,
|
||||
secondary,
|
||||
bgColor,
|
||||
test,
|
||||
);
|
||||
},
|
||||
child: FirkaCard.single(
|
||||
@@ -163,7 +164,7 @@ class LessonBigWidget extends StatelessWidget {
|
||||
height: 18,
|
||||
),
|
||||
Text(
|
||||
lessonNo.toString(),
|
||||
lesson.dailyNth.toString(),
|
||||
style: appStyle.fonts.B_14SB.apply(color: secondary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
@@ -174,9 +175,7 @@ class LessonBigWidget extends StatelessWidget {
|
||||
diameter: 32,
|
||||
color: bgColor,
|
||||
child: ClassIconWidget(
|
||||
uid: lesson.uid,
|
||||
className: lesson.name,
|
||||
category: subjectName,
|
||||
subject: lesson.subject.loadAndGet()!,
|
||||
color: accent,
|
||||
size: 20,
|
||||
),
|
||||
@@ -225,7 +224,7 @@ class LessonBigWidget extends StatelessWidget {
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
roomName,
|
||||
roomName ?? "",
|
||||
style: appStyle.fonts.B_14R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
|
||||
@@ -2,13 +2,17 @@ import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:carousel_slider/carousel_slider.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/phone/widgets/home_main_starting_soon.dart';
|
||||
import 'package:firka/ui/phone/widgets/lesson_big.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:firka_common/firka_common.dart';
|
||||
import 'package:firka_common/core/debug_helper.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/ui/components/filled_circle.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
@@ -47,18 +51,15 @@ class _LessonSliderState extends State<LessonSlider> {
|
||||
return SizedBox();
|
||||
}
|
||||
|
||||
var lessons = widget.lessons.keys.toList();
|
||||
|
||||
Lesson? currentLesson;
|
||||
LessonCacheModel? currentLesson;
|
||||
int tmpIndex;
|
||||
if (now.isBefore(lessons.first.start)) {
|
||||
if (now.isBefore(widget.lessons.first.start)) {
|
||||
tmpIndex = 0;
|
||||
} else {
|
||||
(int, Lesson)? currentIndex = lessons.indexed.firstWhereOrNull(
|
||||
(e) => now.isBefore(e.$2.end),
|
||||
);
|
||||
(int, LessonCacheModel)? currentIndex = widget.lessons.indexed
|
||||
.firstWhereOrNull((e) => now.isBefore(e.$2.end));
|
||||
|
||||
tmpIndex = (currentIndex?.$1 ?? lessons.length) + 1;
|
||||
tmpIndex = (currentIndex?.$1 ?? widget.lessons.length) + 1;
|
||||
if (currentIndex != null) {
|
||||
currentLesson = currentIndex.$2;
|
||||
}
|
||||
@@ -86,17 +87,15 @@ class _LessonSliderState extends State<LessonSlider> {
|
||||
items: [
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 5),
|
||||
child: StartingSoonWidget(initData.l10n, now, lessons),
|
||||
child: StartingSoonWidget(initData.l10n, now, widget.lessons),
|
||||
),
|
||||
...widget.lessons.entries.map(
|
||||
...widget.lessons.map(
|
||||
(entry) => Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 5),
|
||||
child: LessonBigWidget(
|
||||
initData,
|
||||
lessons.getLessonNo(entry.key),
|
||||
entry.key,
|
||||
entry.value,
|
||||
active: currentLesson == entry.key,
|
||||
entry,
|
||||
active: currentLesson == entry,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -202,7 +201,7 @@ class _LessonSliderState extends State<LessonSlider> {
|
||||
: appStyle.colors.accent.withAlpha(128),
|
||||
size: centeredPageIndex == 0 ? 16 : 12,
|
||||
),
|
||||
...widget.lessons.keys.indexed.map(
|
||||
...widget.lessons.indexed.map(
|
||||
(i) => FilledCircle(
|
||||
diameter: centeredPageIndex == i.$1 + 1 ? 10 : 8,
|
||||
color: centeredPageIndex == i.$1 + 1
|
||||
@@ -214,12 +213,10 @@ class _LessonSliderState extends State<LessonSlider> {
|
||||
FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.moonSolid,
|
||||
color: centeredPageIndex == widget.lessons.keys.length + 1
|
||||
color: centeredPageIndex == widget.lessons.length + 1
|
||||
? appStyle.colors.accent
|
||||
: appStyle.colors.accent.withAlpha(128),
|
||||
size: centeredPageIndex == widget.lessons.keys.length + 1
|
||||
? 16
|
||||
: 12,
|
||||
size: centeredPageIndex == widget.lessons.length + 1 ? 16 : 12,
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -230,10 +227,16 @@ class _LessonSliderState extends State<LessonSlider> {
|
||||
}
|
||||
|
||||
class LessonSlider extends StatefulWidget {
|
||||
final LinkedHashMap<Lesson, Test?> lessons;
|
||||
final List<LessonCacheModel> lessons;
|
||||
final int tomorrowTestAmount;
|
||||
|
||||
const LessonSlider(this.lessons, this.tomorrowTestAmount, {super.key});
|
||||
LessonSlider(
|
||||
Iterable<LessonCacheModel> lessons,
|
||||
this.tomorrowTestAmount, {
|
||||
super.key,
|
||||
}) : lessons = lessons
|
||||
.where(((l) => l.type != TimetableConsts.event))
|
||||
.toList();
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _LessonSliderState();
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/shared/class_icon.dart';
|
||||
|
||||
class LessonSmallWidget extends StatelessWidget {
|
||||
final AppLocalizations l10n;
|
||||
final Lesson lesson;
|
||||
final bool lessonActive;
|
||||
|
||||
const LessonSmallWidget(
|
||||
this.l10n,
|
||||
this.lesson,
|
||||
this.lessonActive, {
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var subjectName = lesson.subject?.name ?? 'N/A';
|
||||
if (subjectName.length >= 25) {
|
||||
subjectName = "${subjectName.substring(0, 25 - 3)}...";
|
||||
}
|
||||
subjectName = subjectName.firstUpper();
|
||||
|
||||
var roomName = lesson.roomName ?? '?';
|
||||
if (roomName.length >= 8) {
|
||||
roomName = "${roomName.substring(0, 8 - 3)}...";
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
FirkaCard(
|
||||
attached: lessonActive ? Attach.none : Attach.top,
|
||||
left: [
|
||||
ClassIconWidget(
|
||||
color: wearStyle.colors.accent,
|
||||
size: 20,
|
||||
uid: lesson.uid,
|
||||
className: lesson.name,
|
||||
category: lesson.subject?.name.firstUpper() ?? '',
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
subjectName,
|
||||
style: appStyle.fonts.B_16SB.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
right: [
|
||||
Card(
|
||||
shadowColor: Colors.transparent,
|
||||
color: appStyle.colors.a15p,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(4),
|
||||
child: Text(
|
||||
roomName,
|
||||
style: appStyle.fonts.B_12R.apply(
|
||||
color: appStyle.colors.secondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${lesson.start.toLocal().format(l10n, FormatMode.hmm)} - ${lesson.end.toLocal().format(l10n, FormatMode.hmm)}",
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firka/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/app/initialization.dart';
|
||||
@@ -14,9 +15,8 @@ import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
import 'package:firka/services/watch_sync_helper.dart';
|
||||
import 'package:firka/api/consts.dart';
|
||||
import 'package:firka/api/token_grant.dart';
|
||||
import 'package:firka/data/models/token_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/core/state/firka_state.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
@@ -119,22 +119,12 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
|
||||
)["e_kreta_account_picker"]
|
||||
as SettingsKretenAccountPicker);
|
||||
|
||||
var tokenId = 0;
|
||||
var om = 0;
|
||||
await isar.writeTxn(() async {
|
||||
om = await isar.tokenModels.put(tokenModel);
|
||||
await isar.tokenModels.put(tokenModel);
|
||||
});
|
||||
|
||||
widget.data.tokens = await isar.tokenModels.where().findAll();
|
||||
for (var i = 0; i < widget.data.tokens.length; i++) {
|
||||
if (widget.data.tokens[i].studentIdNorm == om) {
|
||||
tokenId = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await isar.writeTxn(() async {
|
||||
accountPicker.accountIndex = tokenId;
|
||||
accountPicker.accountKey = tokenModel.key;
|
||||
await accountPicker.save(widget.data.isar.appSettingsModels);
|
||||
});
|
||||
|
||||
@@ -158,15 +148,6 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
|
||||
|
||||
if (!mounted) return NavigationDecision.prevent;
|
||||
|
||||
widget.data.reauthCubit?.clear();
|
||||
if (Platform.isIOS) {
|
||||
LiveActivityService.clearTokenExpiration();
|
||||
}
|
||||
|
||||
await initializeApp();
|
||||
|
||||
if (!mounted) return NavigationDecision.prevent;
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop();
|
||||
appRouter?.go('/home');
|
||||
@@ -286,8 +267,8 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
|
||||
opacity: _isLoading
|
||||
? 1.0
|
||||
: _fadeAnimationController!.isAnimating
|
||||
? _fadeAnimation!.value
|
||||
: 0.0,
|
||||
? _fadeAnimation!.value
|
||||
: 0.0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
child: Container(
|
||||
color: appStyle.colors.background,
|
||||
@@ -332,7 +313,8 @@ class _LoginWebviewWidgetState extends FirkaState<LoginWebviewWidget>
|
||||
text: _displayPath,
|
||||
style: appStyle.fonts.B_14R.copyWith(
|
||||
fontSize: 16,
|
||||
color: appStyle.colors.textTeritary ??
|
||||
color:
|
||||
appStyle.colors.textTeritary ??
|
||||
appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/core/debug_helper.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/ui/components/grade.dart';
|
||||
import 'package:firka/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/components/grade.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka/ui/shared/firka_icon.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
@@ -13,42 +19,52 @@ import 'package:firka/l10n/app_localizations.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
|
||||
class OmissionBar extends StatelessWidget {
|
||||
final List<Omission> omissions;
|
||||
const OmissionBar({super.key});
|
||||
|
||||
const OmissionBar({super.key, required this.omissions});
|
||||
static Color stateToColor(OmissionCacheModel? o) {
|
||||
if (o == null) {
|
||||
return appStyle.colors.a15p;
|
||||
}
|
||||
switch (o.state) {
|
||||
case OmissionState.excused:
|
||||
return appStyle.colors.accent;
|
||||
case OmissionState.unexcused:
|
||||
return appStyle.colors.errorAccent;
|
||||
default:
|
||||
return appStyle.colors.warningAccent;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
DateTime now = DateTime.now();
|
||||
DateTime start = now.copyWith(month: 9, day: 1);
|
||||
DateTime startOfTheYear = now.isBefore(start)
|
||||
? start.subtract(Duration(days: 365))
|
||||
: start;
|
||||
DateTime now = timeNow();
|
||||
DateTime startOfTheYear = now.getFirstSchoolDay();
|
||||
|
||||
Map<int, Color> dayToColor = omissions.fold(
|
||||
Map.identity(),
|
||||
(map, o) => map
|
||||
..putIfAbsent(
|
||||
o.date.difference(startOfTheYear).inDays,
|
||||
() => o.state == OmissionState.excused
|
||||
? appStyle.colors.accent
|
||||
: o.state == OmissionState.unexcused
|
||||
? appStyle.colors.errorAccent
|
||||
: appStyle.colors.warningAccent,
|
||||
),
|
||||
);
|
||||
final dates = initData.client!.cache
|
||||
.getTimeTable()
|
||||
.between(startOfTheYear, now)
|
||||
.findAllSync()
|
||||
.map((l) => l.start.getMidnight())
|
||||
.toSet();
|
||||
|
||||
final omittedDates = initData.client!.cache
|
||||
.getOmissions()
|
||||
.findAllSync()
|
||||
.groupList((o) => o.lesson.loadAndGet()!.start);
|
||||
|
||||
final bar = ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Row(
|
||||
children: List.generate(now.difference(startOfTheYear).inDays, (i) {
|
||||
return Expanded(
|
||||
child: Container(
|
||||
height: 12,
|
||||
color: dayToColor[i] ?? appStyle.colors.a15p,
|
||||
),
|
||||
);
|
||||
}),
|
||||
children: dates
|
||||
.map(
|
||||
(i) => Expanded(
|
||||
child: Container(
|
||||
height: 12,
|
||||
color: stateToColor(omittedDates[i]?.firstOrNull),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka_common/firka_common.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka/ui/components/firka_card.dart';
|
||||
import 'package:firka/core/settings.dart';
|
||||
import 'package:firka_common/core/debug_helper.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/ui/theme/style.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -11,24 +11,48 @@ import 'package:flutter_svg/svg.dart';
|
||||
import 'lesson.dart';
|
||||
|
||||
class TimeTableDayWidget extends StatelessWidget {
|
||||
final AppInitialization data;
|
||||
final DateTime date;
|
||||
final List<Lesson> week;
|
||||
final List<Lesson> lessons;
|
||||
final List<Lesson> events;
|
||||
final List<Test> tests;
|
||||
final List<Lesson> day;
|
||||
final List<LessonCacheModel> lessons;
|
||||
final List<LessonCacheModel> events;
|
||||
|
||||
const TimeTableDayWidget(
|
||||
this.data,
|
||||
this.date,
|
||||
this.week,
|
||||
this.lessons,
|
||||
this.events,
|
||||
this.tests,
|
||||
this.day, {
|
||||
super.key,
|
||||
});
|
||||
const TimeTableDayWidget(this.lessons, this.events, {super.key});
|
||||
|
||||
static String simplifyEventName(String e) {
|
||||
return e
|
||||
.replaceAll(" (Nem órarendi nap)", "")
|
||||
.replaceAll(" (Hétfő)", "")
|
||||
.replaceAll(" (Kedd)", "")
|
||||
.replaceAll(" (Szerda)", "")
|
||||
.replaceAll(" (Csütörtök)", "")
|
||||
.replaceAll(" (Péntek)", "")
|
||||
.replaceAll(" (Szombat)", "")
|
||||
.replaceAll(" (Vasárnap)", "")
|
||||
.replaceAll(
|
||||
"Tanítás nélküli munkanap",
|
||||
initData.l10n.tt_non_instructional_day,
|
||||
)
|
||||
.replaceAll("Munkaszüneti nap", initData.l10n.tt_public_holiday)
|
||||
.replaceAll("Tavaszi szünet", initData.l10n.tt_spring_break)
|
||||
.replaceAll("Téli szünet", initData.l10n.tt_winter_break)
|
||||
.replaceAll("Őszi szünet", initData.l10n.tt_autumn_break)
|
||||
.replaceAll("Tanítási nap", initData.l10n.tt_instructional_day)
|
||||
.replaceAll("Első félév vége", initData.l10n.tt_first_semester_end)
|
||||
.replaceAll("Ünnepnap", initData.l10n.tt_holiday)
|
||||
.replaceAll("Pihenőnap", initData.l10n.tt_rest_day)
|
||||
.replaceAll(
|
||||
"Első tanítási nap",
|
||||
initData.l10n.tt_first_instructional_day,
|
||||
)
|
||||
.replaceAll(
|
||||
"Utolsó tanítási nap",
|
||||
initData.l10n.tt_last_instructional_day,
|
||||
)
|
||||
.replaceAll(
|
||||
"Utolsó tanítási nap a végzős évfolyamokon",
|
||||
initData.l10n.tt_last_instructional_day_graduates,
|
||||
)
|
||||
.replaceAll("Egész napos kirándulás", initData.l10n.tt_full_day_trip)
|
||||
.replaceAll("negyedév vége", initData.l10n.tt_quarter_end);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -44,13 +68,13 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
data.l10n.tt_no_classes_l1,
|
||||
initData.l10n.tt_no_classes_l1,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
data.l10n.tt_no_classes_l2,
|
||||
initData.l10n.tt_no_classes_l2,
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -59,29 +83,7 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
...events.map(
|
||||
(event) => Center(
|
||||
child: Text(
|
||||
event.name
|
||||
.replaceAll(" (Nem órarendi nap)", "")
|
||||
.replaceAll(" (Hétfő)", "")
|
||||
.replaceAll(" (Kedd)", "")
|
||||
.replaceAll(" (Szerda)", "")
|
||||
.replaceAll(" (Csütörtök)", "")
|
||||
.replaceAll(" (Péntek)", "")
|
||||
.replaceAll(" (Szombat)", "")
|
||||
.replaceAll(" (Vasárnap)", "")
|
||||
.replaceAll("Tanítás nélküli munkanap", data.l10n.tt_non_instructional_day)
|
||||
.replaceAll("Munkaszüneti nap", data.l10n.tt_public_holiday)
|
||||
.replaceAll("Tavaszi szünet", data.l10n.tt_spring_break)
|
||||
.replaceAll("Téli szünet", data.l10n.tt_winter_break)
|
||||
.replaceAll("Őszi szünet", data.l10n.tt_autumn_break)
|
||||
.replaceAll("Tanítási nap", data.l10n.tt_instructional_day)
|
||||
.replaceAll("Első félév vége", data.l10n.tt_first_semester_end)
|
||||
.replaceAll("Ünnepnap", data.l10n.tt_holiday)
|
||||
.replaceAll("Pihenőnap", data.l10n.tt_rest_day)
|
||||
.replaceAll("Első tanítási nap", data.l10n.tt_first_instructional_day)
|
||||
.replaceAll("Utolsó tanítási nap", data.l10n.tt_last_instructional_day)
|
||||
.replaceAll("Utolsó tanítási nap a végzős évfolyamokon", data.l10n.tt_last_instructional_day_graduates)
|
||||
.replaceAll("Egész napos kirándulás", data.l10n.tt_full_day_trip)
|
||||
.replaceAll("negyedév vége", data.l10n.tt_quarter_end),
|
||||
simplifyEventName(event.name),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textSecondary,
|
||||
),
|
||||
@@ -99,7 +101,7 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
margin: EdgeInsets.zero,
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text(
|
||||
event.name,
|
||||
simplifyEventName(event.name),
|
||||
style: appStyle.fonts.B_16R.apply(
|
||||
color: appStyle.colors.textPrimary,
|
||||
),
|
||||
@@ -112,7 +114,7 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
ttLessons.add(SizedBox());
|
||||
}
|
||||
|
||||
var showBreak = data.settings
|
||||
var showBreak = initData.settings
|
||||
.group("settings")
|
||||
.subGroup("timetable_toast")
|
||||
.boolean("breaks");
|
||||
@@ -122,11 +124,8 @@ class TimeTableDayWidget extends StatelessWidget {
|
||||
var nextLesson = lessons.length > i + 1 ? lessons[i + 1] : null;
|
||||
ttLessons.add(
|
||||
LessonWidget(
|
||||
data,
|
||||
initData,
|
||||
lesson,
|
||||
tests.firstWhereOrNull(
|
||||
(test) => test.lessonNumber == lesson.lessonNumber,
|
||||
),
|
||||
active: timeNow().isBetween(
|
||||
i > 0 ? lessons[i - 1].end : lesson.start,
|
||||
lesson.end,
|
||||
|
||||
@@ -37,7 +37,7 @@ dependencies:
|
||||
flutter_screenutil: ^5.9.3
|
||||
flutter_arc_text: ^0.6.0
|
||||
flutter_svg: ^1.1.6
|
||||
home_widget: ^0.8.0
|
||||
home_widget: 0.8.0
|
||||
crypto: ^3.0.6
|
||||
transparent_pointer: ^1.0.1
|
||||
flutter_staggered_grid_view: ^0.7.0
|
||||
|
||||
55
firka_common/.gitignore
vendored
Normal file
55
firka_common/.gitignore
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.build/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
.swiftpm/
|
||||
migrate_working_dir/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
coverage
|
||||
|
||||
# Generated files
|
||||
*.g.dart
|
||||
@@ -4,7 +4,6 @@ import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
|
||||
class Constants {
|
||||
static String get clientId {
|
||||
@@ -17,17 +16,6 @@ class Constants {
|
||||
|
||||
static const applicationId = "hu.ekreta.student";
|
||||
static const applicationVersion = "5.15.0";
|
||||
|
||||
static String get userAgent {
|
||||
if (Platform.isAndroid) {
|
||||
return "$applicationId/$applicationVersion"
|
||||
"/${initData.devInfo.model}"
|
||||
"/${initData.devInfo.versionRelease}"
|
||||
"/${initData.devInfo.versionSdkInt}";
|
||||
} else {
|
||||
return "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class OmissionConsts {
|
||||
@@ -38,6 +26,7 @@ class OmissionConsts {
|
||||
|
||||
class TimetableConsts {
|
||||
static const event = "TanevRendjeEsemeny";
|
||||
static const lastDay = "Utolsó tanítási nap";
|
||||
}
|
||||
|
||||
class KretaLoginEndpoints {
|
||||
@@ -17,3 +17,17 @@ extension IterableExtension<T> on Iterable<T> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
extension MidnightExtension on DateTime {
|
||||
DateTime getMidnight() {
|
||||
return subtract(
|
||||
Duration(
|
||||
hours: hour,
|
||||
minutes: minute,
|
||||
seconds: second,
|
||||
milliseconds: millisecond,
|
||||
microseconds: microsecond,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'dart:ui';
|
||||
@@ -48,7 +51,7 @@ Color getGradeColor(
|
||||
}
|
||||
}
|
||||
|
||||
extension GradeListExtension on Iterable<Grade> {
|
||||
extension GradeCacheModelListExtension on Iterable<GradeCacheModel> {
|
||||
(int total, List<int> countsByGrade) getGradeDistribution() {
|
||||
final filtered = where((g) => g.shouldIncludeInAverage());
|
||||
final counts = [0, 0, 0, 0, 0];
|
||||
@@ -58,15 +61,18 @@ extension GradeListExtension on Iterable<Grade> {
|
||||
return (filtered.length, counts);
|
||||
}
|
||||
|
||||
double? _getAverageBySubject(String uid, {bool halfYearFallback = true}) {
|
||||
double? _getAverageBySubject(int key, {bool halfYearFallback = true}) {
|
||||
return where(
|
||||
(g) => g.subject.uid == uid,
|
||||
(g) => g.subject.loadAndGet()!.cacheKey == key,
|
||||
).getAverage(halfYearFallback: halfYearFallback);
|
||||
}
|
||||
|
||||
double? getAverageBySubject(Subject subject, {bool halfYearFallback = true}) {
|
||||
double? getAverageBySubject(
|
||||
SubjectCacheModel subject, {
|
||||
bool halfYearFallback = true,
|
||||
}) {
|
||||
return _getAverageBySubject(
|
||||
subject.uid,
|
||||
subject.cacheKey,
|
||||
halfYearFallback: halfYearFallback,
|
||||
);
|
||||
}
|
||||
@@ -78,7 +84,7 @@ extension GradeListExtension on Iterable<Grade> {
|
||||
double t3 = 0.5,
|
||||
double t4 = 0.5,
|
||||
}) {
|
||||
final averages = map((g) => g.subject).toSet().map((subject) {
|
||||
final averages = map((g) => g.subject.loadAndGet()!).toSet().map((subject) {
|
||||
final average = getAverageBySubject(
|
||||
subject,
|
||||
halfYearFallback: halfYearFallback,
|
||||
@@ -98,7 +104,7 @@ extension GradeListExtension on Iterable<Grade> {
|
||||
|
||||
double? getSubjectAverage({bool halfYearFallback = true}) {
|
||||
final averages = where((g) => g.hasClassicValue())
|
||||
.map((g) => g.subject.uid)
|
||||
.map((g) => g.subject.loadAndGet()!.cacheKey)
|
||||
.toSet()
|
||||
.map(
|
||||
(uid) =>
|
||||
@@ -121,7 +127,7 @@ extension GradeListExtension on Iterable<Grade> {
|
||||
double weightTotal = 0;
|
||||
double sum = 0;
|
||||
int? fallback;
|
||||
for (Grade grade in this) {
|
||||
for (final grade in this) {
|
||||
if (grade.hasClassicValue() && halfYearFallback) {
|
||||
fallback = grade.numericValue!;
|
||||
}
|
||||
@@ -158,3 +164,18 @@ extension GradeExtension on Grade {
|
||||
return weightPercentage != null && hasClassicValue();
|
||||
}
|
||||
}
|
||||
|
||||
extension GradeCacheModelExtension on GradeCacheModel {
|
||||
bool isInPercentage() {
|
||||
return valueType == 'Szazalekos';
|
||||
}
|
||||
|
||||
bool hasClassicValue() {
|
||||
return valueType == "Osztalyzat";
|
||||
}
|
||||
|
||||
// https://tudasbazis.ekreta.hu/pages/viewpage.action?pageId=2426172
|
||||
bool shouldIncludeInAverage() {
|
||||
return weightPercentage != null && hasClassicValue();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:majesticons_flutter/majesticons_flutter.dart';
|
||||
|
||||
enum ClassIcon {
|
||||
@@ -94,31 +95,26 @@ Map<ClassIcon, Uint8List> _iconMap = {
|
||||
ClassIcon.database: Majesticon.dataSolid,
|
||||
};
|
||||
|
||||
ClassIcon? getIconType(String uid, String className, String category) {
|
||||
ClassIcon? getIconType(SubjectCacheModel subject) {
|
||||
ClassIcon? icon;
|
||||
if (category.toLowerCase() == "matematika") {
|
||||
icon = ClassIcon.mathematics;
|
||||
}
|
||||
|
||||
if (icon == null) {
|
||||
for (var desc in _descriptors.entries) {
|
||||
if (desc.value.hasMatch(
|
||||
className
|
||||
.replaceAll("ö", "o")
|
||||
.replaceAll("ü", "u")
|
||||
.replaceAll("ó", "o")
|
||||
.replaceAll("ő", "o")
|
||||
.replaceAll("ú", "u")
|
||||
.replaceAll("é", "e")
|
||||
.replaceAll("á", "a")
|
||||
.replaceAll("ű", "u")
|
||||
.replaceAll("í", "i")
|
||||
.toLowerCase(),
|
||||
)) {
|
||||
icon = desc.key;
|
||||
for (var desc in _descriptors.entries) {
|
||||
if (desc.value.hasMatch(
|
||||
subject.name
|
||||
.replaceAll("ö", "o")
|
||||
.replaceAll("ü", "u")
|
||||
.replaceAll("ó", "o")
|
||||
.replaceAll("ő", "o")
|
||||
.replaceAll("ú", "u")
|
||||
.replaceAll("é", "e")
|
||||
.replaceAll("á", "a")
|
||||
.replaceAll("ű", "u")
|
||||
.replaceAll("í", "i")
|
||||
.toLowerCase(),
|
||||
)) {
|
||||
icon = desc.key;
|
||||
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
133
firka_common/lib/data/cache_manager.dart
Normal file
133
firka_common/lib/data/cache_manager.dart
Normal file
@@ -0,0 +1,133 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/teacher_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'models/token_model.dart';
|
||||
|
||||
typedef AfterQBFilter<OBJ> = QueryBuilder<OBJ, OBJ, QAfterFilterCondition>;
|
||||
typedef QBFilter<OBJ> = QueryBuilder<OBJ, OBJ, QFilterCondition>;
|
||||
|
||||
class CacheManager {
|
||||
TokenModel token;
|
||||
|
||||
CacheManager(this.token);
|
||||
|
||||
StudentCacheModel findStudent() {
|
||||
return isarInit.studentCacheModels
|
||||
.filter()
|
||||
.group(isCurrentStudent)
|
||||
.findFirstSync()!;
|
||||
}
|
||||
|
||||
int genCacheKey(Identifiable identifiable) {
|
||||
return _genCacheKey(identifiable.id);
|
||||
}
|
||||
|
||||
int _genCacheKey(int id) {
|
||||
return id ^ token.iss.hashCode;
|
||||
}
|
||||
|
||||
AfterQBFilter<StudentCacheModel> isCurrentStudent(
|
||||
QBFilter<StudentCacheModel> q,
|
||||
) {
|
||||
return q.cacheKeyEqualTo(_genCacheKey(token.studentId));
|
||||
}
|
||||
|
||||
AfterQBFilter<ClassGroupCacheModel> isCurrentClassGroup(
|
||||
QBFilter<ClassGroupCacheModel> q,
|
||||
) {
|
||||
return q.student(isCurrentStudent);
|
||||
}
|
||||
|
||||
AfterQBFilter<LessonCacheModel> getTimeTable() {
|
||||
return isarInit.lessonCacheModels.filter().classGroup(isCurrentClassGroup);
|
||||
}
|
||||
|
||||
AfterQBFilter<LessonCacheModel> getClassLessons() {
|
||||
return getTimeTable().and().not().events();
|
||||
}
|
||||
|
||||
AfterQBFilter<LessonCacheModel> getEvents() {
|
||||
return getTimeTable().and().events();
|
||||
}
|
||||
|
||||
AfterQBFilter<GradeCacheModel> getGrades() {
|
||||
return isarInit.gradeCacheModels.filter().classGroup(isCurrentClassGroup);
|
||||
}
|
||||
|
||||
AfterQBFilter<ClassAverageCacheModel> getClassAverages() {
|
||||
return isarInit.classAverageCacheModels.filter().student(isCurrentStudent);
|
||||
}
|
||||
|
||||
AfterQBFilter<TestCacheModel> getTests() {
|
||||
return isarInit.testCacheModels.filter().lesson(
|
||||
(l) => l.classGroup(isCurrentClassGroup),
|
||||
);
|
||||
}
|
||||
|
||||
AfterQBFilter<HomeworkCacheModel> getHomeworks() {
|
||||
return isarInit.homeworkCacheModels.filter().classGroup(
|
||||
isCurrentClassGroup,
|
||||
);
|
||||
}
|
||||
|
||||
AfterQBFilter<MessageCacheModel> getMessages() {
|
||||
return isarInit.messageCacheModels.filter().student(isCurrentStudent);
|
||||
}
|
||||
|
||||
AfterQBFilter<SubjectCacheModel> getSubjects() {
|
||||
return isarInit.subjectCacheModels.filter().teachers(
|
||||
(t) => t.classGroup(isCurrentClassGroup),
|
||||
);
|
||||
}
|
||||
|
||||
AfterQBFilter<OmissionCacheModel> getOmissions() {
|
||||
return isarInit.omissionCacheModels.filter().lesson(
|
||||
(l) => l.classGroup(isCurrentClassGroup),
|
||||
);
|
||||
}
|
||||
|
||||
void resolveTeachers() {
|
||||
Set<TeacherModel> teachers = HashSet<TeacherModel>(
|
||||
equals: (t, t2) =>
|
||||
t.name == t2.name &&
|
||||
t.subject.value!.cacheKey == t2.subject.value!.cacheKey &&
|
||||
t.classGroup.value!.cacheKey == t2.classGroup.value!.cacheKey,
|
||||
hashCode: (t) =>
|
||||
t.name.hashCode ^
|
||||
t.subject.value!.cacheKey ^
|
||||
t.classGroup.value!.cacheKey,
|
||||
);
|
||||
List<LessonCacheModel> lessons = getClassLessons()
|
||||
.sortByStart()
|
||||
.findAllSync();
|
||||
teachers.addAll(
|
||||
lessons.map(
|
||||
(l) => TeacherModel()
|
||||
..name = l.teacher!
|
||||
..since = l.start
|
||||
..subject.value = l.subject.loadAndGet()!
|
||||
..classGroup.value = l.classGroup.loadAndGet()!,
|
||||
),
|
||||
);
|
||||
|
||||
isarInit.writeTxnSync(() {
|
||||
isarInit.teacherModels.clearSync();
|
||||
isarInit.teacherModels.putAllSync(teachers.toList());
|
||||
});
|
||||
}
|
||||
}
|
||||
43
firka_common/lib/data/database.dart
Normal file
43
firka_common/lib/data/database.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'package:firka_common/data/models/app_settings_model.dart';
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/message_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/teacher_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
late Isar isarInit;
|
||||
|
||||
Future<Isar> initDB() async {
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
|
||||
isarInit = await Isar.open(
|
||||
[
|
||||
TokenModelSchema,
|
||||
TeacherModelSchema,
|
||||
ClassAverageCacheModelSchema,
|
||||
ClassGroupCacheModelSchema,
|
||||
GradeCacheModelSchema,
|
||||
LessonCacheModelSchema,
|
||||
MessageCacheModelSchema,
|
||||
OmissionCacheModelSchema,
|
||||
TestCacheModelSchema,
|
||||
HomeworkCacheModelSchema,
|
||||
AppSettingsModelSchema,
|
||||
SubjectCacheModelSchema,
|
||||
StudentCacheModelSchema,
|
||||
],
|
||||
inspector: true,
|
||||
directory: dir.path,
|
||||
);
|
||||
|
||||
return isarInit;
|
||||
}
|
||||
27
firka_common/lib/data/models/class_average_cache_model.dart
Normal file
27
firka_common/lib/data/models/class_average_cache_model.dart
Normal file
@@ -0,0 +1,27 @@
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'class_average_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class ClassAverageCacheModel
|
||||
extends GenericCacheModel<ClassGroupSubjectAverage> {
|
||||
late float classAverage;
|
||||
late float studentAverage;
|
||||
|
||||
final subject = IsarLink<SubjectCacheModel>();
|
||||
final student = IsarLink<StudentCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<ClassGroupSubjectAverage> ctx) {
|
||||
this
|
||||
..classAverage = ctx.data.classGroupAverage as float
|
||||
..studentAverage = ctx.data.studentAverage as float
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject)
|
||||
..student.value = ctx.cacheManager.findStudent();
|
||||
}
|
||||
}
|
||||
31
firka_common/lib/data/models/class_group_cache_model.dart
Normal file
31
firka_common/lib/data/models/class_group_cache_model.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'class_group_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class ClassGroupCacheModel extends GenericCacheModel<ClassGroup> {
|
||||
late String name;
|
||||
late bool isActive;
|
||||
late String type;
|
||||
late String educationalOrderUid;
|
||||
late String educationalOrderName;
|
||||
late String educationalOrderDescription;
|
||||
|
||||
final student = IsarLink<StudentCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<ClassGroup> ctx) {
|
||||
this
|
||||
..name = ctx.data.name
|
||||
..isActive = ctx.data.isActive
|
||||
..type = ctx.data.type
|
||||
..educationalOrderUid = ctx.data.studyTask!.uid
|
||||
..educationalOrderName = ctx.data.studyTask!.name
|
||||
..educationalOrderDescription = ctx.data.studyTask!.description
|
||||
..student.value = ctx.cacheManager.findStudent();
|
||||
}
|
||||
}
|
||||
10
firka_common/lib/data/models/generic_cache_model.dart
Normal file
10
firka_common/lib/data/models/generic_cache_model.dart
Normal file
@@ -0,0 +1,10 @@
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
class GenericCacheModel<T extends Identifiable> {
|
||||
late Id cacheKey;
|
||||
late DateTime createdAt;
|
||||
|
||||
void apply(CacheContext<T> data) {}
|
||||
}
|
||||
52
firka_common/lib/data/models/grade_cache_model.dart
Normal file
52
firka_common/lib/data/models/grade_cache_model.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'grade_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class GradeCacheModel extends GenericCacheModel<Grade> {
|
||||
String? mode;
|
||||
String? topic;
|
||||
late String type;
|
||||
late String valueType;
|
||||
late DateTime writtenAt;
|
||||
int? numericValue;
|
||||
int? weightPercentage;
|
||||
late String textValue;
|
||||
late String teacherName;
|
||||
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>();
|
||||
final subject = IsarLink<SubjectCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Grade> ctx) {
|
||||
this
|
||||
..mode = ctx.data.mode?.description
|
||||
..topic = ctx.data.topic
|
||||
..type = ctx.data.type.description
|
||||
..valueType = ctx.data.valueType.name
|
||||
..writtenAt = ctx.data.recordDate
|
||||
..numericValue = ctx.data.numericValue
|
||||
..weightPercentage = ctx.data.weightPercentage
|
||||
..textValue = ctx.data.strValue
|
||||
..teacherName = ctx.data.teacher
|
||||
..createdAt = ctx.data.creationDate
|
||||
..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup)
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject);
|
||||
|
||||
if (subject.value == null) {
|
||||
isarInit.writeTxnSync(() {
|
||||
subject.value = SubjectCacheModel()
|
||||
..cacheKey = ctx.cacheManager.genCacheKey(ctx.data.subject)
|
||||
..name = ctx.data.subject.name
|
||||
..createdAt = DateTime.now();
|
||||
isarInit.subjectCacheModels.putSync(subject.value!);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
45
firka_common/lib/data/models/homework_cache_model.dart
Normal file
45
firka_common/lib/data/models/homework_cache_model.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'homework_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class HomeworkCacheModel extends GenericCacheModel<Homework> {
|
||||
late String teacherName;
|
||||
late DateTime dueDate;
|
||||
late DateTime startDate;
|
||||
late String description;
|
||||
bool isDone = false;
|
||||
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>();
|
||||
final subject = IsarLink<SubjectCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Homework> ctx) {
|
||||
this
|
||||
..teacherName = ctx.data.teacherName
|
||||
..dueDate = ctx.data.dueDate
|
||||
..startDate = ctx.data.startDate
|
||||
..description = ctx.data.description
|
||||
..createdAt = ctx.data.creationDate
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject)
|
||||
..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup);
|
||||
|
||||
if (subject.value == null) {
|
||||
isarInit.writeTxnSync(() {
|
||||
subject.value = SubjectCacheModel()
|
||||
..cacheKey = ctx.cacheManager.genCacheKey(ctx.data.subject)
|
||||
..name = ctx.data.subject.name
|
||||
..createdAt = DateTime.now();
|
||||
isarInit.subjectCacheModels.putSync(subject.value!);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
108
firka_common/lib/data/models/lesson_cache_model.dart
Normal file
108
firka_common/lib/data/models/lesson_cache_model.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
import 'package:firka_common/core/consts.dart';
|
||||
import 'package:firka_common/core/extensions.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/homework_cache_model.dart';
|
||||
import 'package:firka_common/data/models/omission_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/models/test_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'lesson_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class LessonCacheModel extends GenericCacheModel<Lesson> {
|
||||
@Index()
|
||||
late DateTime start;
|
||||
late DateTime end;
|
||||
int? dailyNth; // null = event
|
||||
int? yearlyNth; // null = event
|
||||
late String name;
|
||||
String? topic;
|
||||
String? roomName; // null = event
|
||||
late String state;
|
||||
late String type;
|
||||
String? teacher;
|
||||
String? substituteTeacher;
|
||||
|
||||
final homework = IsarLink<HomeworkCacheModel>();
|
||||
final subject = IsarLink<SubjectCacheModel>(); // null = event
|
||||
final test = IsarLink<TestCacheModel>();
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>(); // null = whole class
|
||||
|
||||
@Backlink(to: "lesson")
|
||||
final omission = IsarLink<OmissionCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Lesson> ctx) {
|
||||
this
|
||||
..start = ctx.data.start
|
||||
..end = ctx.data.end
|
||||
..dailyNth = ctx.data.lessonNumber
|
||||
..yearlyNth = ctx.data.lessonSeqNumber
|
||||
..state = ctx.data.state.name
|
||||
..teacher = ctx.data.teacher
|
||||
..substituteTeacher = ctx.data.substituteTeacher
|
||||
..name = ctx.data.name
|
||||
..topic = ctx.data.theme
|
||||
..roomName = ctx.data.roomName
|
||||
..type = ctx.data.type.name
|
||||
..classGroup.init(ctx.cacheManager, ctx.data.classGroup)
|
||||
..subject.init(ctx.cacheManager, ctx.data.subject);
|
||||
|
||||
if (subject.value == null && ctx.data.subject != null) {
|
||||
isarInit.writeTxnSync(() {
|
||||
subject.value = SubjectCacheModel()
|
||||
..cacheKey = ctx.cacheManager.genCacheKey(ctx.data.subject!)
|
||||
..name = ctx.data.subject!.name
|
||||
..createdAt = DateTime.now();
|
||||
isarInit.subjectCacheModels.putSync(subject.value!);
|
||||
});
|
||||
}
|
||||
|
||||
if (ctx.data.assessmentUid != null) {
|
||||
test.init(ctx.cacheManager, UidObj(uid: ctx.data.assessmentUid!));
|
||||
}
|
||||
|
||||
if (ctx.data.homeworkUid != null) {
|
||||
homework.init(ctx.cacheManager, UidObj(uid: ctx.data.homeworkUid!));
|
||||
}
|
||||
|
||||
if (classGroup.value == null) {
|
||||
classGroup.value = isarInit.classGroupCacheModels
|
||||
.filter()
|
||||
.group(ctx.cacheManager.isCurrentClassGroup)
|
||||
.and()
|
||||
.typeEqualTo("Osztaly")
|
||||
.findFirstSync()!;
|
||||
}
|
||||
}
|
||||
|
||||
bool isEvent() {
|
||||
return type == TimetableConsts.event;
|
||||
}
|
||||
}
|
||||
|
||||
typedef AfterQBFilter<OBJ> = QueryBuilder<OBJ, OBJ, QAfterFilterCondition>;
|
||||
typedef QBFilter<OBJ> = QueryBuilder<OBJ, OBJ, QFilterCondition>;
|
||||
|
||||
extension LessonFilterExtension on QBFilter<LessonCacheModel> {
|
||||
AfterQBFilter<LessonCacheModel> events() {
|
||||
return typeEqualTo(TimetableConsts.event);
|
||||
}
|
||||
|
||||
AfterQBFilter<LessonCacheModel> between(DateTime fromDate, DateTime toDate) {
|
||||
return startBetween(
|
||||
fromDate.getMidnight(),
|
||||
toDate.getMidnight().add(Duration(days: 1)),
|
||||
includeUpper: false,
|
||||
);
|
||||
}
|
||||
|
||||
AfterQBFilter<LessonCacheModel> on(DateTime date) {
|
||||
return between(date, date);
|
||||
}
|
||||
}
|
||||
26
firka_common/lib/data/models/message_cache_model.dart
Normal file
26
firka_common/lib/data/models/message_cache_model.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'message_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class MessageCacheModel extends GenericCacheModel<MessageItem> {
|
||||
late String author;
|
||||
late String title;
|
||||
late String contentHtml;
|
||||
|
||||
final student = IsarLink<StudentCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<MessageItem> ctx) {
|
||||
this
|
||||
..author = ctx.data.author
|
||||
..title = ctx.data.title
|
||||
..createdAt = ctx.data.date
|
||||
..contentHtml = ctx.data.contentHTML
|
||||
..student.value = ctx.cacheManager.findStudent();
|
||||
}
|
||||
}
|
||||
35
firka_common/lib/data/models/omission_cache_model.dart
Normal file
35
firka_common/lib/data/models/omission_cache_model.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'omission_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class OmissionCacheModel extends GenericCacheModel<Omission> {
|
||||
int? lateMins;
|
||||
@Enumerated(EnumType.name)
|
||||
late OmissionState state;
|
||||
late String teacherName;
|
||||
String? proofType;
|
||||
|
||||
final lesson = IsarLink<LessonCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Omission> ctx) {
|
||||
this
|
||||
..lateMins = ctx.data.lateForMin
|
||||
..state = ctx.data.state
|
||||
..teacherName = ctx.data.teacher
|
||||
..proofType = ctx.data.proofType?.description
|
||||
..createdAt = ctx.data.createdAt;
|
||||
lesson.value = ctx.cacheManager
|
||||
.getTimeTable()
|
||||
.startEqualTo(ctx.data.lesson!.start)
|
||||
.and()
|
||||
.endEqualTo(ctx.data.lesson!.end)
|
||||
.findFirstSync();
|
||||
}
|
||||
}
|
||||
19
firka_common/lib/data/models/student_cache_model.dart
Normal file
19
firka_common/lib/data/models/student_cache_model.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'student_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class StudentCacheModel extends GenericCacheModel<Student> {
|
||||
late String name;
|
||||
late DateTime birthday;
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Student> ctx) {
|
||||
this
|
||||
..name = ctx.data.name
|
||||
..birthday = ctx.data.birthdate;
|
||||
}
|
||||
}
|
||||
24
firka_common/lib/data/models/subject_cache_model.dart
Normal file
24
firka_common/lib/data/models/subject_cache_model.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import 'package:firka_common/data/models/class_average_cache_model.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/teacher_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'subject_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class SubjectCacheModel extends GenericCacheModel<DktSubject> {
|
||||
late String name;
|
||||
|
||||
@Backlink(to: "subject")
|
||||
final classAverage = IsarLink<ClassAverageCacheModel>();
|
||||
|
||||
@Backlink(to: "subject")
|
||||
final teachers = IsarLinks<TeacherModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<DktSubject> ctx) {
|
||||
this..name = ctx.data.name;
|
||||
}
|
||||
}
|
||||
16
firka_common/lib/data/models/teacher_model.dart
Normal file
16
firka_common/lib/data/models/teacher_model.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:firka_common/data/models/class_group_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'teacher_model.g.dart';
|
||||
|
||||
@collection
|
||||
class TeacherModel {
|
||||
Id? id;
|
||||
late String name;
|
||||
late DateTime since;
|
||||
|
||||
final classGroup = IsarLink<ClassGroupCacheModel>();
|
||||
final subject = IsarLink<SubjectCacheModel>();
|
||||
}
|
||||
27
firka_common/lib/data/models/test_cache_model.dart
Normal file
27
firka_common/lib/data/models/test_cache_model.dart
Normal file
@@ -0,0 +1,27 @@
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/lesson_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:firka_common/data/util.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
part 'test_cache_model.g.dart';
|
||||
|
||||
@collection
|
||||
class TestCacheModel extends GenericCacheModel<Test> {
|
||||
late String? topic;
|
||||
late String method;
|
||||
late String teacherName;
|
||||
|
||||
@Backlink(to: "test")
|
||||
final lesson = IsarLink<LessonCacheModel>();
|
||||
|
||||
@override
|
||||
void apply(CacheContext<Test> ctx) {
|
||||
this
|
||||
..topic = ctx.data.theme
|
||||
..method = ctx.data.method.description
|
||||
..teacherName = ctx.data.teacherName
|
||||
..createdAt = ctx.data.reportDate;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/student_cache_model.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
import 'package:firka/core/extensions.dart';
|
||||
import 'package:firka_common/core/debug_helper.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
part 'token_model.g.dart';
|
||||
|
||||
@collection
|
||||
class TokenModel {
|
||||
Id? studentIdNorm; // Custom unique student identifier with "G0" removed
|
||||
String? studentId; // Custom unique student identifier
|
||||
String? iss; // Institution id for student
|
||||
String? idToken; // Unique identifier for the token if needed
|
||||
String? accessToken; // The main auth token
|
||||
String? refreshToken; // Token used to refresh the access token
|
||||
DateTime? expiryDate;
|
||||
late Id key; // Custom unique student identifier with "G0" removed
|
||||
late int studentId;
|
||||
late String username; // Custom unique student identifier
|
||||
late String iss; // Institution id for student
|
||||
late String idToken; // Unique identifier for the token if needed
|
||||
late String accessToken; // The main auth token
|
||||
late String refreshToken; // Token used to refresh the access token
|
||||
late DateTime expiryDate;
|
||||
int? tokenVersion;
|
||||
int? updatedAtMs;
|
||||
|
||||
@@ -25,7 +23,7 @@ class TokenModel {
|
||||
|
||||
factory TokenModel.fromValues(
|
||||
Id studentIdNorm,
|
||||
studentId,
|
||||
String studentId,
|
||||
String iss,
|
||||
String idToken,
|
||||
String accessToken,
|
||||
@@ -36,8 +34,8 @@ class TokenModel {
|
||||
}) {
|
||||
var m = TokenModel();
|
||||
|
||||
m.studentIdNorm = studentIdNorm;
|
||||
m.studentId = studentId;
|
||||
m.key = studentIdNorm;
|
||||
m.username = studentId;
|
||||
m.iss = iss;
|
||||
m.idToken = idToken;
|
||||
m.accessToken = accessToken;
|
||||
@@ -54,30 +52,18 @@ class TokenModel {
|
||||
final jwt = JWT.decode(resp.idToken);
|
||||
|
||||
final payload = jwt.payload as Map<String, dynamic>;
|
||||
final username = payload["kreta:user_name"].toString();
|
||||
if (username.isNumeric() ||
|
||||
(username.contains("G0") &&
|
||||
username.substring(0, username.length - 3).isNumeric())) {
|
||||
m.studentIdNorm = int.parse(username.toString().replaceAll("G0", ""));
|
||||
} else {
|
||||
// you would expect all usernames to be numeric
|
||||
// and for them be the student's student id, but NO
|
||||
final hash = sha256.convert(utf8.encode(username));
|
||||
final value =
|
||||
((hash.bytes[0] << 24) |
|
||||
(hash.bytes[1] << 16) |
|
||||
(hash.bytes[2] << 8) |
|
||||
(hash.bytes[3])) >>>
|
||||
0;
|
||||
|
||||
m.studentIdNorm = value & 0x3FFFFFFF;
|
||||
}
|
||||
m.studentId = payload["kreta:user_name"];
|
||||
m.key = int.tryParse(
|
||||
"${payload["kreta:institute_code"].hashCode}${payload["kreta:institute_user_id"]}",
|
||||
)!;
|
||||
m.studentId =
|
||||
int.tryParse(payload["kreta:student_id"] ?? "") ?? // parent only field
|
||||
int.tryParse(payload["kreta:institute_user_id"])!;
|
||||
m.username = payload["kreta:user_name"];
|
||||
m.iss = payload["kreta:institute_code"];
|
||||
m.idToken = resp.idToken;
|
||||
m.accessToken = resp.accessToken;
|
||||
m.refreshToken = resp.refreshToken;
|
||||
m.expiryDate = timeNow()
|
||||
m.expiryDate = DateTime.now()
|
||||
.add(Duration(seconds: resp.expiresIn))
|
||||
.subtract(Duration(minutes: 1)); // just to be safe
|
||||
final iat = payload["iat"];
|
||||
80
firka_common/lib/data/util.dart
Normal file
80
firka_common/lib/data/util.dart
Normal file
@@ -0,0 +1,80 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:firka_common/data/cache_manager.dart';
|
||||
import 'package:firka_common/data/database.dart';
|
||||
import 'package:firka_common/data/models/generic_cache_model.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:isar_community/isar.dart';
|
||||
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
int genCacheKey(DateTime date, int studentId) {
|
||||
var md = date.month * pow(10, 2) + date.day;
|
||||
|
||||
return (md * pow(10, 11) + studentId) as int;
|
||||
}
|
||||
|
||||
DateTime getDate(int key) {
|
||||
var md = key ~/ pow(10, 11);
|
||||
var month = md ~/ pow(10, 2);
|
||||
var day = (md - month * pow(10, 2)) as int;
|
||||
|
||||
return DateTime(DateTime.now().year, month, day);
|
||||
}
|
||||
|
||||
class CacheContext<T extends Identifiable> {
|
||||
final CacheManager cacheManager;
|
||||
final T data;
|
||||
|
||||
CacheContext(this.cacheManager, this.data);
|
||||
}
|
||||
|
||||
extension LinksExtension<M> on IsarLinks<M> {
|
||||
Set<M> loadAndGet() {
|
||||
if (!isAttached) {
|
||||
print("${this}: Isar link got before attached");
|
||||
}
|
||||
if (!isLoaded) {
|
||||
loadSync();
|
||||
}
|
||||
// can be useful for debugging
|
||||
/*if (value == null) {
|
||||
print("${M} link: null value detected");
|
||||
}*/
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
extension LinkExtension<T extends Identifiable, M extends GenericCacheModel<T>>
|
||||
on IsarLink<M> {
|
||||
M? loadAndGet() {
|
||||
if (!isAttached) {
|
||||
print("${this}: Isar link got before attached");
|
||||
}
|
||||
if (!isLoaded) {
|
||||
loadSync();
|
||||
}
|
||||
// can be useful for debugging
|
||||
/*if (value == null) {
|
||||
print("${M} link: null value detected");
|
||||
}*/
|
||||
return value;
|
||||
}
|
||||
|
||||
/// Attaches by id and if the object is absent makes one
|
||||
void init(CacheManager manager, T? t) {
|
||||
if (t == null) {
|
||||
return;
|
||||
}
|
||||
value = isarInit.collection<M>().getSync(manager.genCacheKey(t));
|
||||
}
|
||||
|
||||
/// Does not creates an object, only attempts to attach by id
|
||||
/// if you want to create with it, use `init` instead
|
||||
void unsafeInit(CacheManager manager, Identifiable? identifiable) {
|
||||
if (identifiable == null) {
|
||||
return;
|
||||
}
|
||||
value = isarInit.collection<M>().getSync(manager.genCacheKey(identifiable));
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
library firka_common;
|
||||
|
||||
/*
|
||||
export 'core/consts.dart';
|
||||
export 'core/debug_helper.dart';
|
||||
export 'core/extensions.dart';
|
||||
export 'core/icon_helper.dart';
|
||||
export 'core/json_helper.dart';
|
||||
export 'core/grade_helper.dart';
|
||||
export 'ui/components/firka_card.dart';
|
||||
export 'ui/components/firka_shadow.dart';
|
||||
export 'ui/components/grade.dart';
|
||||
export 'ui/components/grade_helpers.dart';
|
||||
export 'ui/shared/class_icon.dart';
|
||||
export 'ui/shared/counter_digit.dart';
|
||||
export 'ui/shared/delayed_spinner.dart';
|
||||
export 'ui/shared/firka_icon.dart';
|
||||
export 'ui/shared/grade_small_card.dart';
|
||||
export 'ui/theme/style.dart';
|
||||
*/
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
|
||||
class FilledCircle extends StatelessWidget {
|
||||
final double diameter;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:firka_common/ui/components/firka_shadow.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
|
||||
enum Attach { none, bottom, top }
|
||||
@@ -84,11 +83,12 @@ class FirkaCard extends StatelessWidget {
|
||||
padding: padding,
|
||||
margin: margin,
|
||||
decoration: ShapeDecoration(
|
||||
shadows: shadow && !isLight
|
||||
shadows: shadow
|
||||
? [
|
||||
BoxShadow(
|
||||
color: appStyle.colors.shadowColor,
|
||||
offset: const Offset(0, 1),
|
||||
blurRadius: isLight ? 2.0 : 0,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
|
||||
import 'filled_circle.dart';
|
||||
@@ -18,7 +19,7 @@ class GradeWidget extends StatelessWidget {
|
||||
super.key,
|
||||
}) : grade = null;
|
||||
|
||||
final Grade? grade;
|
||||
final GradeCacheModel? grade;
|
||||
final double size;
|
||||
final int? gradeValue;
|
||||
final int? gradeWeight;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:firka_common/core/icon_helper.dart';
|
||||
@@ -6,35 +7,20 @@ import 'package:firka_common/ui/shared/firka_icon.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
class ClassIconWidget extends StatelessWidget {
|
||||
final String _uid;
|
||||
final String _className;
|
||||
final String _category;
|
||||
final SubjectCacheModel subject;
|
||||
final Color color;
|
||||
final double? size;
|
||||
|
||||
ClassIconWidget.subject({
|
||||
super.key,
|
||||
required Subject subject,
|
||||
this.color = Colors.white,
|
||||
this.size,
|
||||
}) : _className = subject.name,
|
||||
_uid = subject.uid,
|
||||
_category = subject.category.name;
|
||||
|
||||
const ClassIconWidget({
|
||||
super.key,
|
||||
required String uid,
|
||||
required String className,
|
||||
required String category,
|
||||
required SubjectCacheModel this.subject,
|
||||
this.color = Colors.white,
|
||||
this.size,
|
||||
}) : _className = className,
|
||||
_uid = uid,
|
||||
_category = category;
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var iconCategory = getIconType(_uid, _className, _category);
|
||||
var iconCategory = getIconType(subject);
|
||||
|
||||
return FirkaIconWidget(
|
||||
FirkaIconType.majesticons,
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
import 'package:firka_common/data/models/grade_cache_model.dart';
|
||||
import 'package:firka_common/data/models/subject_cache_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:kreta_api/kreta_api.dart';
|
||||
|
||||
import 'package:firka_common/ui/components/firka_card.dart';
|
||||
import 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
import 'package:firka_common/core/grade_helper.dart';
|
||||
import 'package:firka_common/ui/shared/class_icon.dart';
|
||||
import 'package:firka_common/ui/theme/style.dart';
|
||||
|
||||
class GradeSmallCard extends StatelessWidget {
|
||||
final double? studentAverage;
|
||||
final double? classAverage;
|
||||
final Subject subject;
|
||||
final SubjectCacheModel subject;
|
||||
|
||||
GradeSmallCard(
|
||||
List<Grade> grades,
|
||||
this.studentAverage,
|
||||
this.classAverage,
|
||||
this.subject, {
|
||||
super.key,
|
||||
}) : studentAverage = grades.getAverageBySubject(subject);
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -28,9 +30,7 @@ class GradeSmallCard extends StatelessWidget {
|
||||
spacing: 8,
|
||||
children: [
|
||||
ClassIconWidget(
|
||||
uid: subject.uid,
|
||||
className: subject.name,
|
||||
category: subject.category.name!,
|
||||
subject: subject,
|
||||
color: appStyle.colors.accent,
|
||||
size: 20,
|
||||
),
|
||||
|
||||
@@ -14,8 +14,14 @@ dependencies:
|
||||
majesticons_flutter: ^0.0.1
|
||||
flutter_svg: ^1.1.6
|
||||
intl: any
|
||||
path_provider: ^2.1.0
|
||||
dart_jsonwebtoken: ^3.2.0
|
||||
isar_community: 3.3.0
|
||||
isar_community_flutter_libs: 3.3.0
|
||||
build_runner: any
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^6.0.0
|
||||
isar_community_generator: 3.3.0
|
||||
|
||||
@@ -1 +1 @@
|
||||
export 'package:firka_common/ui/components/grade_helpers.dart';
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ library kreta_api;
|
||||
export 'src/api_response.dart';
|
||||
export 'src/endpoints.dart';
|
||||
export 'src/exceptions/token.dart';
|
||||
export 'src/model/all_lessons.dart';
|
||||
export 'src/model/class_group.dart';
|
||||
export 'src/model/generic.dart';
|
||||
export 'src/model/grade.dart';
|
||||
@@ -17,3 +16,4 @@ export 'src/model/subject.dart';
|
||||
export 'src/model/test.dart';
|
||||
export 'src/model/timetable.dart';
|
||||
export 'src/resp/token_grant.dart';
|
||||
export 'src/model/dkt_subject.dart';
|
||||
|
||||
@@ -34,7 +34,7 @@ class KretaEndpoints {
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
static String getStudentUrl(String iss) =>
|
||||
static String getStudent(String iss) =>
|
||||
"${kreta(iss)}/ellenorzo/v3/sajat/TanuloAdatlap";
|
||||
|
||||
static String getClassGroups(String iss) =>
|
||||
@@ -49,9 +49,6 @@ class KretaEndpoints {
|
||||
static String getGrades(String iss, [DateTime? from, DateTime? to]) =>
|
||||
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek${dateQuery(from, to)}";
|
||||
|
||||
static String getSubjectAvg(String iss, String studyGroupId) =>
|
||||
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek/Atlagok/TantargyiAtlagok?oktatasiNevelesiFeladatUid=$studyGroupId&oktatasiNevelesiFeladatUid=$studyGroupId";
|
||||
|
||||
static String getClassGroupAvg(String iss, String studyGroupId) =>
|
||||
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek/Atlagok/OsztalyAtlagok?oktatasiNevelesiFeladatUid=$studyGroupId&oktatasiNevelesiFeladatUid=$studyGroupId";
|
||||
|
||||
@@ -67,6 +64,6 @@ class KretaEndpoints {
|
||||
static String getTests(String iss, [DateTime? from, DateTime? to]) =>
|
||||
"${kreta(iss)}/ellenorzo/v3/sajat/BejelentettSzamonkeresek${dateQuery(from, to)}";
|
||||
|
||||
static String getLessons(String iss) =>
|
||||
static String getDktSubjects(String iss) =>
|
||||
"${kreta(iss)}/dktapi/intezmenyek/munkaterek/tanulok";
|
||||
}
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class AllLessons {
|
||||
final String schoolId;
|
||||
final String yearId;
|
||||
final dynamic classId;
|
||||
final String? className;
|
||||
final bool classWorkspace;
|
||||
final dynamic groupId;
|
||||
final String? groupName;
|
||||
final bool groupWorkspace;
|
||||
final String groupWorkspaceName;
|
||||
final dynamic subjectId;
|
||||
final String subjectName;
|
||||
final dynamic teacherId;
|
||||
final String teacherGuid;
|
||||
final String teacherName;
|
||||
final dynamic teacherAnnoId;
|
||||
final dynamic annoId;
|
||||
final String? languageId;
|
||||
final dynamic subjectCategoryId;
|
||||
final String subjectCategoryName;
|
||||
final dynamic typeId;
|
||||
final String typeName;
|
||||
final dynamic gradeTypeId;
|
||||
final String gradeTypeName;
|
||||
final dynamic taskPlaceId;
|
||||
final String taskPlaceName;
|
||||
final dynamic teacherAvatarTypeId;
|
||||
final String teacherAvatarTypePath;
|
||||
final dynamic taskGroupId;
|
||||
|
||||
const AllLessons({
|
||||
required this.schoolId,
|
||||
required this.yearId,
|
||||
this.classId,
|
||||
this.className,
|
||||
required this.classWorkspace,
|
||||
this.groupId,
|
||||
this.groupName,
|
||||
required this.groupWorkspace,
|
||||
required this.groupWorkspaceName,
|
||||
required this.subjectId,
|
||||
required this.subjectName,
|
||||
required this.teacherId,
|
||||
required this.teacherGuid,
|
||||
required this.teacherName,
|
||||
this.teacherAnnoId,
|
||||
this.annoId,
|
||||
this.languageId,
|
||||
required this.subjectCategoryId,
|
||||
required this.subjectCategoryName,
|
||||
required this.typeId,
|
||||
required this.typeName,
|
||||
required this.gradeTypeId,
|
||||
required this.gradeTypeName,
|
||||
required this.taskPlaceId,
|
||||
required this.taskPlaceName,
|
||||
required this.teacherAvatarTypeId,
|
||||
required this.teacherAvatarTypePath,
|
||||
this.taskGroupId,
|
||||
});
|
||||
|
||||
factory AllLessons.fromJson(Map<String, dynamic> json) => AllLessons(
|
||||
schoolId: json['intezmenyId']?.toString() ?? '',
|
||||
yearId: json['tanevId']?.toString() ?? '',
|
||||
classId: json['osztalyId'],
|
||||
className: json['osztalyNev']?.toString(),
|
||||
classWorkspace: json['osztalyMunkaTer'] == true,
|
||||
groupId: json['csoportId'],
|
||||
groupName: json['csoportNev']?.toString(),
|
||||
groupWorkspace: json['csoportMunkaTer'] == true,
|
||||
groupWorkspaceName: json['osztalyCsoportNev']?.toString() ?? '',
|
||||
subjectId: json['tantargyId'],
|
||||
subjectName: json['tantargyNev']?.toString() ?? '',
|
||||
teacherId: json['alkalmazottId'],
|
||||
teacherGuid: json['alkalmazottGuid']?.toString() ?? '',
|
||||
teacherName: json['alkalmazottNev']?.toString() ?? '',
|
||||
teacherAnnoId: json['alkalmazottUzenoFalId'],
|
||||
annoId: json['uzenoFalId'],
|
||||
languageId: json['nyelvId']?.toString(),
|
||||
subjectCategoryId: json['tantargyKategoriaId'],
|
||||
subjectCategoryName: json['tantargyKategoriaNev']?.toString() ?? '',
|
||||
typeId: json['tipusId'],
|
||||
typeName: json['tipusNev']?.toString() ?? '',
|
||||
gradeTypeId: json['evfolyamTipusId'],
|
||||
gradeTypeName: json['evfolyamTipusNev']?.toString() ?? '',
|
||||
taskPlaceId: json['feladatEllatasiHelyId'],
|
||||
taskPlaceName: json['feladatEllatasiHelyNev']?.toString() ?? '',
|
||||
teacherAvatarTypeId: json['alkalmazottAvatarTipusId'],
|
||||
teacherAvatarTypePath: json['alkalmazottAvatarEleres']?.toString() ?? '',
|
||||
taskGroupId: json['oraiFeladatGroupId'],
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'intezmenyId': schoolId,
|
||||
'tanevId': yearId,
|
||||
'osztalyId': classId,
|
||||
'osztalyNev': className,
|
||||
'osztalyMunkaTer': classWorkspace,
|
||||
'csoportId': groupId,
|
||||
'csoportNev': groupName,
|
||||
'csoportMunkaTer': groupWorkspace,
|
||||
'osztalyCsoportNev': groupWorkspaceName,
|
||||
'tantargyId': subjectId,
|
||||
'tantargyNev': subjectName,
|
||||
'alkalmazottId': teacherId,
|
||||
'alkalmazottGuid': teacherGuid,
|
||||
'alkalmazottNev': teacherName,
|
||||
'alkalmazottUzenoFalId': teacherAnnoId,
|
||||
'uzenoFalId': annoId,
|
||||
'nyelvId': languageId,
|
||||
'tantargyKategoriaId': subjectCategoryId,
|
||||
'tantargyKategoriaNev': subjectCategoryName,
|
||||
'tipusId': typeId,
|
||||
'tipusNev': typeName,
|
||||
'evfolyamTipusId': gradeTypeId,
|
||||
'evfolyamTipusNev': gradeTypeName,
|
||||
'feladatEllatasiHelyId': taskPlaceId,
|
||||
'feladatEllatasiHelyNev': taskPlaceName,
|
||||
'alkalmazottAvatarTipusId': teacherAvatarTypeId,
|
||||
'alkalmazottAvatarEleres': teacherAvatarTypePath,
|
||||
'oraiFeladatGroupId': taskGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
List<AllLessons> lessonsFromJson(String str) =>
|
||||
List<AllLessons>.from(json.decode(str).map((x) => AllLessons.fromJson(x)));
|
||||
|
||||
String lessonsToJson(List<AllLessons> data) =>
|
||||
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
|
||||
@@ -11,7 +11,7 @@ class ClassGroup extends NameUid {
|
||||
final bool isActive;
|
||||
final String type;
|
||||
|
||||
const ClassGroup({
|
||||
ClassGroup({
|
||||
required super.uid,
|
||||
required super.name,
|
||||
required this.headTeacher,
|
||||
@@ -59,7 +59,7 @@ class SubjectAverage extends UidObj {
|
||||
final double? weightedSum;
|
||||
final double? weightedCount;
|
||||
|
||||
const SubjectAverage({
|
||||
SubjectAverage({
|
||||
required super.uid,
|
||||
required this.subject,
|
||||
this.average,
|
||||
@@ -88,7 +88,7 @@ class ClassGroupSubjectAverage extends UidObj {
|
||||
final double? studentAverage;
|
||||
final double? classGroupAverage;
|
||||
|
||||
const ClassGroupSubjectAverage({
|
||||
ClassGroupSubjectAverage({
|
||||
required super.uid,
|
||||
required this.subject,
|
||||
this.classGroupAverage,
|
||||
|
||||
33
kreta_api/lib/src/model/dkt_subject.dart
Normal file
33
kreta_api/lib/src/model/dkt_subject.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
import 'generic.dart';
|
||||
|
||||
class DktSubject extends Identifiable {
|
||||
final int id;
|
||||
final String name;
|
||||
final String teacherName;
|
||||
final int? classGroupId; // null = whole class
|
||||
final String groupName; // if group null then class name
|
||||
final String? languageCode; // ISO 639-1:2002; null = non-language subject
|
||||
final int typeId; // 0 = not removed
|
||||
|
||||
DktSubject({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.teacherName,
|
||||
required this.typeId,
|
||||
this.languageCode,
|
||||
this.classGroupId,
|
||||
required this.groupName,
|
||||
});
|
||||
|
||||
factory DktSubject.fromJson(Map<String, dynamic> json) {
|
||||
return DktSubject(
|
||||
id: json["tantargyId"],
|
||||
name: json["tantargyNev"],
|
||||
teacherName: json["alkalmazottNev"],
|
||||
classGroupId: json["csoportId"],
|
||||
groupName: json["osztalyCsoportNev"],
|
||||
typeId: json["tipusId"],
|
||||
languageCode: json["nyelvId"],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ class NameUidDesc extends NameUid {
|
||||
static final EMPTY = NameUidDesc(name: "", uid: "", description: "");
|
||||
final String description;
|
||||
|
||||
const NameUidDesc({
|
||||
NameUidDesc({
|
||||
required super.uid,
|
||||
required super.name,
|
||||
required this.description,
|
||||
@@ -33,7 +33,7 @@ class NameUidDesc extends NameUid {
|
||||
class NameUid extends UidObj {
|
||||
final String name;
|
||||
|
||||
const NameUid({required super.uid, required this.name});
|
||||
NameUid({required super.uid, required this.name});
|
||||
|
||||
factory NameUid.fromJson(Map<String, dynamic> json) {
|
||||
return NameUid(uid: json['Uid'], name: json['Nev']);
|
||||
@@ -44,15 +44,21 @@ class NameUid extends UidObj {
|
||||
}
|
||||
}
|
||||
|
||||
class UidObj {
|
||||
class UidObj extends Identifiable {
|
||||
final String uid;
|
||||
|
||||
const UidObj({required this.uid});
|
||||
UidObj({required this.uid});
|
||||
|
||||
factory UidObj.fromJson(Map<String, dynamic> json) {
|
||||
return UidObj(uid: json['Uid']);
|
||||
}
|
||||
|
||||
/// Extracts numeric id from composite key
|
||||
/// but sometimes (i.e. "Uid" : "Magatartás" in Grade.subject)
|
||||
/// not, then it uses it's hashcode, be careful!
|
||||
@override
|
||||
int get id => int.tryParse(uid.split(",").first) ?? uid.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'UidObj('
|
||||
@@ -61,6 +67,10 @@ class UidObj {
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Identifiable {
|
||||
int get id;
|
||||
}
|
||||
|
||||
extension ToUidObj on Map<String, dynamic> {
|
||||
UidObj? uid(String key) {
|
||||
final value = this[key];
|
||||
|
||||
@@ -16,10 +16,10 @@ class Grade extends UidObj {
|
||||
final String strValue;
|
||||
final int? weightPercentage;
|
||||
final String? shortStrValue;
|
||||
final UidObj? classGroup;
|
||||
final UidObj classGroup;
|
||||
final int sortIndex;
|
||||
|
||||
const Grade({
|
||||
Grade({
|
||||
required super.uid,
|
||||
required this.recordDate,
|
||||
required this.creationDate,
|
||||
@@ -35,7 +35,7 @@ class Grade extends UidObj {
|
||||
required this.strValue,
|
||||
this.weightPercentage,
|
||||
this.shortStrValue,
|
||||
this.classGroup,
|
||||
required this.classGroup,
|
||||
required this.sortIndex,
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ class Grade extends UidObj {
|
||||
strValue: json['SzovegesErtek'],
|
||||
weightPercentage: json['SulySzazalekErteke'],
|
||||
shortStrValue: json['SzovegesErtekelesRovidNev'],
|
||||
classGroup: json.uid('OsztalyCsoport'),
|
||||
classGroup: json.uid('OsztalyCsoport')!,
|
||||
sortIndex: json['SortIndex'],
|
||||
);
|
||||
}
|
||||
@@ -80,7 +80,7 @@ class Grade extends UidObj {
|
||||
'SzovegesErtek': strValue,
|
||||
'SulySzazalekErteke': weightPercentage,
|
||||
'SzovegesErtekelesRovidNev': shortStrValue,
|
||||
'OsztalyCsoport': classGroup != null ? {'Uid': classGroup!.uid} : null,
|
||||
'OsztalyCsoport': classGroup,
|
||||
'SortIndex': sortIndex,
|
||||
};
|
||||
}
|
||||
@@ -103,7 +103,7 @@ class Grade extends UidObj {
|
||||
'strValue: "$strValue", '
|
||||
'weightPercentage: ${weightPercentage ?? 'null'}, '
|
||||
'shortStrValue: "${shortStrValue ?? 'null'}", '
|
||||
'classGroup: ${classGroup ?? 'null'}, '
|
||||
'classGroup: ${classGroup}, '
|
||||
'sortIndex: $sortIndex'
|
||||
')';
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ class Guardian extends NameUid {
|
||||
final bool isLegalRepresentative;
|
||||
final String? phoneNumber;
|
||||
|
||||
const Guardian({
|
||||
Guardian({
|
||||
required this.email,
|
||||
required this.isLegalRepresentative,
|
||||
required super.name,
|
||||
|
||||
@@ -16,7 +16,7 @@ class Homework extends UidObj {
|
||||
final UidObj classGroup;
|
||||
final bool canAttach;
|
||||
|
||||
const Homework({
|
||||
Homework({
|
||||
required super.uid,
|
||||
required this.subject,
|
||||
required this.subjectName,
|
||||
|
||||
@@ -5,7 +5,7 @@ class Institution extends UidObj {
|
||||
final String shortName;
|
||||
final List<SystemModule> systemModuleList;
|
||||
|
||||
const Institution({
|
||||
Institution({
|
||||
required this.customizationSettings,
|
||||
required this.shortName,
|
||||
required this.systemModuleList,
|
||||
|
||||
@@ -7,7 +7,7 @@ abstract class MessageItem extends UidObj {
|
||||
final String contentHTML;
|
||||
final String contentText;
|
||||
|
||||
const MessageItem({
|
||||
MessageItem({
|
||||
required super.uid,
|
||||
required this.title,
|
||||
required this.author,
|
||||
@@ -25,7 +25,7 @@ class NoticeBoardItem extends MessageItem {
|
||||
@override
|
||||
DateTime get date => validFrom;
|
||||
|
||||
const NoticeBoardItem({
|
||||
NoticeBoardItem({
|
||||
required super.uid,
|
||||
required super.title,
|
||||
required super.author,
|
||||
@@ -66,7 +66,7 @@ class InfoBoardItem extends MessageItem {
|
||||
final DateTime createdAt;
|
||||
final NameUidDesc type;
|
||||
|
||||
const InfoBoardItem({
|
||||
InfoBoardItem({
|
||||
required super.uid,
|
||||
required super.title,
|
||||
required super.author,
|
||||
|
||||
@@ -15,7 +15,7 @@ class Omission extends UidObj {
|
||||
final NameUidDesc? proofType;
|
||||
final UidObj? classGroup;
|
||||
|
||||
const Omission({
|
||||
Omission({
|
||||
required super.uid,
|
||||
required this.subject,
|
||||
required this.lesson,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user