-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhome.dart
756 lines (713 loc) · 25.8 KB
/
home.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:eduapge2/icanteen_setup.dart';
import 'package:eduapge2/message.dart';
import 'package:eduapge2/messages.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_session_manager/flutter_session_manager.dart';
import 'package:package_info/package_info.dart';
import 'package:restart_app/restart_app.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:shorebird_code_push/shorebird_code_push_web.dart';
import 'package:url_launcher/url_launcher.dart';
class HomePage extends StatefulWidget {
final SessionManager sessionManager;
final Function reLogin;
const HomePage(
{super.key, required this.sessionManager, required this.reLogin});
@override
State<HomePage> createState() => HomePageState();
}
class LessonStatus {
final bool hasLessonsToday;
final bool hasLesson;
final DateTime nextLessonTime;
LessonStatus({
required this.hasLessonsToday,
required this.hasLesson,
required this.nextLessonTime,
});
}
extension TimeOfDayExtension on TimeOfDay {
bool operator <(TimeOfDay other) {
if (hour < other.hour) {
return true;
} else if (hour == other.hour && minute < other.minute) {
return true;
} else {
return false;
}
}
bool operator <=(TimeOfDay other) {
if (hour < other.hour) {
return true;
} else if (hour == other.hour && minute <= other.minute) {
return true;
} else {
return false;
}
}
bool operator >(TimeOfDay other) {
if (hour > other.hour) {
return true;
} else if (hour == other.hour && minute > other.minute) {
return true;
} else {
return false;
}
}
}
extension DateTimeExtension on DateTime {
static DateTime parseTime(String timeString, {DateTime? date}) {
final time = TimeOfDay(
hour: int.parse(timeString.split(':')[0]),
minute: int.parse(timeString.split(':')[1]),
);
final dateTime = date ?? DateTime.now();
return DateTime(
dateTime.year, dateTime.month, dateTime.day, time.hour, time.minute);
}
}
LessonStatus getLessonStatus(List<dynamic> lessons, TimeOfDay currentTime) {
// Check if the user has any lessons today
final hasLessonsToday = lessons.isNotEmpty;
// Check if the user has a lesson
final hasLesson = hasLessonsToday &&
lessons.any((lesson) {
final startTime = TimeOfDay.fromDateTime(
DateTimeExtension.parseTime(lesson['period']['startTime']));
final endTime = TimeOfDay.fromDateTime(
DateTimeExtension.parseTime(lesson['period']['endTime']));
return startTime < endTime &&
startTime <= currentTime &&
endTime > currentTime;
});
// Calculate the end time of the current lesson or the start time of the next lesson
DateTime nextLessonTime;
try {
if (hasLesson) {
final currentLesson = lessons.firstWhere((lesson) {
final startTime = TimeOfDay.fromDateTime(
DateTimeExtension.parseTime(lesson['period']['startTime']));
final endTime = TimeOfDay.fromDateTime(
DateTimeExtension.parseTime(lesson['period']['endTime']));
return startTime < endTime &&
startTime <= currentTime &&
endTime > currentTime;
});
nextLessonTime =
DateTimeExtension.parseTime(currentLesson['period']['endTime']);
} else if (hasLessonsToday) {
final nextLesson = lessons.firstWhere((lesson) {
final startTime = TimeOfDay.fromDateTime(
DateTimeExtension.parseTime(lesson['period']['startTime']));
return startTime > currentTime;
});
nextLessonTime =
DateTimeExtension.parseTime(nextLesson['period']['startTime']);
} else {
nextLessonTime = DateTime.now();
}
return LessonStatus(
hasLessonsToday: hasLessonsToday,
hasLesson: hasLesson,
nextLessonTime: nextLessonTime,
);
} catch (e) {
return LessonStatus(
hasLessonsToday: false,
hasLesson: false,
nextLessonTime: DateTime.now());
}
}
final _shorebirdCodePush = ShorebirdCodePush();
class HomePageState extends State<HomePage> {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
late SharedPreferences sharedPreferences;
String baseUrl = "https://lobster-app-z6jfk.ondigitalocean.app/api";
late Response response;
Dio dio = Dio();
bool error = false; //for error status
bool loading = true; //for data featching status
String errmsg = ""; //to assing any error message from API/runtime
dynamic apidata; //for decoded JSON data
bool refresh = false;
bool updateAvailable = false;
bool quickstart = false;
bool _isCheckingForUpdate = false;
late Map<String, dynamic> apidataTT;
List<dynamic> apidataMsg = [];
late String username;
late LessonStatus _lessonStatus;
Timer? _timer;
@override
void initState() {
super.initState();
dio.interceptors
.add(DioCacheManager(CacheConfig(baseUrl: baseUrl)).interceptor);
fetchAndCompareBuildName();
getData(); //fetching data
if (!_isCheckingForUpdate) _checkForUpdate(); // ik that it's not necessary
}
Future<void> _checkForUpdate() async {
setState(() {
_isCheckingForUpdate = true;
});
// Ask the Shorebird servers if there is a new patch available.
final isUpdateAvailable =
await _shorebirdCodePush.isNewPatchAvailableForDownload();
if (!mounted) return;
setState(() {
_isCheckingForUpdate = false;
});
if (isUpdateAvailable) {
_showUpdateAvailableBanner();
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No update available'),
),
);
}
}
void _showDownloadingBanner() {
ScaffoldMessenger.of(context).showMaterialBanner(
const MaterialBanner(
content: Text('Downloading...'),
actions: [
SizedBox(
height: 14,
width: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
],
),
);
}
void _showUpdateAvailableBanner() {
ScaffoldMessenger.of(context).showMaterialBanner(
MaterialBanner(
content: const Text('Update available'),
actions: [
TextButton(
onPressed: () async {
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
await _downloadUpdate();
if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
},
child: const Text('Download'),
),
],
),
);
}
void _showRestartBanner() {
ScaffoldMessenger.of(context).showMaterialBanner(
const MaterialBanner(
content: Text('A new patch is ready!'),
actions: [
TextButton(
// Restart the app for the new patch to take effect.
onPressed: Restart.restartApp,
child: Text('Restart app'),
),
],
),
);
}
Future<void> _downloadUpdate() async {
_showDownloadingBanner();
await _shorebirdCodePush.downloadUpdateIfAvailable();
if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
_showRestartBanner();
}
@override
void setState(VoidCallback fn) {
if (!mounted) return;
super.setState(fn);
}
DateTime getWeekDay() {
DateTime now = DateTime.now();
if (now.weekday > 5) {
now.add(Duration(days: 8 - now.weekday));
}
return DateTime(now.year, now.month, now.day);
}
getData() async {
setState(() {
loading = true;
});
sharedPreferences = await SharedPreferences.getInstance();
quickstart = sharedPreferences.getBool('quickstart') ?? false;
var msgs = await widget.sessionManager.get('messages');
if (msgs != Null && msgs != null) {
setState(() {
apidataMsg = msgs;
});
}
Map<String, dynamic> user = await widget.sessionManager.get('user');
username = user["firstname"] + " " + user["lastname"];
String token = sharedPreferences.getString("token")!;
Response response = await dio.get(
"$baseUrl/timetable/${getWeekDay().toString()}",
options: buildCacheOptions(
Duration.zero,
maxStale: const Duration(days: 7),
options: Options(
headers: {
"Authorization": "Bearer $token",
},
),
),
);
apidataTT = jsonDecode(response.data);
_lessonStatus = getLessonStatus(apidataTT["lessons"], TimeOfDay.now());
if (_lessonStatus.hasLessonsToday) {
_startTimer();
}
setState(() {
loading = false;
}); //refresh UI
}
void _startTimer() {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
setState(() {
_lessonStatus = getLessonStatus(apidataTT["lessons"], TimeOfDay.now());
if (!_lessonStatus.hasLessonsToday) {
_timer?.cancel();
}
});
});
}
void fetchAndCompareBuildName() async {
final dio = Dio();
// Retrieve the package info
final packageInfo = await PackageInfo.fromPlatform();
final buildName = packageInfo.version;
try {
final response = await dio.get(
'https://api.github.com/repos/DislikesSchool/EduPage2/releases/latest');
final responseData = response.data;
// Extract the tag_name from the response JSON and remove the "v" prefix if present
final tag = responseData['tag_name'];
final formattedTag = tag.startsWith('v') ? tag.substring(1) : tag;
// Compare the tag_name to the app's build name
if (formattedTag != buildName) {
setState(() {
updateAvailable = true;
});
}
} catch (error) {
// Handle any errors that occur during the request
if (kDebugMode) {
print('Error: $error');
}
}
}
@override
Widget build(BuildContext context) {
AppLocalizations? local = AppLocalizations.of(context);
ThemeData theme = Theme.of(context);
if (loading) {
return Center(
child: Text(local!.loading),
);
}
int lunch = -1;
DateTime orderLunchesFor = DateTime(1998, 4, 10);
String? l = sharedPreferences.getString("lunches");
if (l != null) {
var lunches = jsonDecode(l) as List<dynamic>;
if (lunches.isNotEmpty) {
var lunchToday = lunches[0] as Map<String, dynamic>;
lunch = 0;
var todayLunches = lunchToday["lunches"];
for (int i = 0; i < todayLunches.length; i++) {
if (todayLunches[i]["ordered"]) lunch = i + 1;
}
for (Map<String, dynamic> li in lunches) {
bool canOrder = false;
bool hasOrdered = false;
for (Map<String, dynamic> l in li["lunches"]) {
if (l["can_order"]) {
canOrder = true;
}
if (l["ordered"]) {
hasOrdered = true;
}
}
if (canOrder && !hasOrdered) {
orderLunchesFor = DateTime.parse(li["day"]);
break;
}
}
}
}
List<dynamic> msgs =
apidataMsg.where((msg) => msg["type"] == "sprava").toList();
List<dynamic> msgsWOR = List.from(msgs);
List<Map<String, int>> bump = [];
for (Map<String, dynamic> msg in msgs) {
if (msg["replyOf"] != null) {
if (!bump.any((element) =>
element["id"]!.compareTo(int.parse(msg["replyOf"])) == 0)) {
bump.add(
{"id": int.parse(msg["replyOf"]), "index": msgsWOR.indexOf(msg)});
msgsWOR.remove(msg);
} else {
msgsWOR.remove(msg);
}
}
}
for (Map<String, int> b in bump) {
msgsWOR.move(
msgsWOR.indexOf(msgsWOR
.firstWhere((element) => int.parse(element["id"]) == b["id"])),
b["index"]!);
}
final remainingTime =
_lessonStatus.nextLessonTime.difference(DateTime.now());
final minutes =
remainingTime.inMinutes.remainder(60).toString().padLeft(2, '0');
final seconds =
remainingTime.inSeconds.remainder(60).toString().padLeft(2, '0');
final remainingTimeString = '$minutes:$seconds';
return Scaffold(
key: scaffoldKey,
body: Stack(
children: [
Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
height: 50,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceVariant,
border: Border.all(
color: theme.colorScheme.background,
),
borderRadius: BorderRadiusDirectional.circular(25),
),
child: Stack(
children: <Widget>[
Center(
child: Text(
username,
style: const TextStyle(
fontSize: 24,
),
),
),
if (_lessonStatus.hasLessonsToday)
Positioned(
right: 15,
top: 10,
child: Row(
children: [
Icon(
Icons.circle,
color: Color.fromARGB(
255,
_lessonStatus.hasLesson ? 0 : 255,
_lessonStatus.hasLesson ? 255 : 0,
0),
size: 8,
),
const SizedBox(width: 5),
Text(
remainingTimeString,
style: const TextStyle(fontSize: 20),
),
],
),
),
IconButton(
icon: const Icon(Icons.menu),
onPressed: () => {
scaffoldKey.currentState?.openDrawer(),
},
),
],
),
),
if (apidataTT["lessons"].length > 0)
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Card(
elevation: 5,
child: SizedBox(
height: 100,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (Map<String, dynamic> lesson
in apidataTT["lessons"])
Card(
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
Text(
lesson["period"]["name"] + ".",
style:
const TextStyle(fontSize: 10),
),
Text(
lesson["subject"]["short"],
style:
const TextStyle(fontSize: 20),
),
Text(
lesson["classrooms"][0]["short"],
style:
const TextStyle(fontSize: 14),
),
],
),
),
),
],
),
),
),
],
),
),
),
if (updateAvailable)
GestureDetector(
onTap: () async {
final url = Uri.parse(
'https://github.com/DislikesSchool/EduPage2/releases/latest');
if (await canLaunchUrl(url)) {
await launchUrl(url);
} else {
throw 'Could not launch $url';
}
},
child: Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
child: Stack(
children: [
Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.only(
top: 10, bottom: 10, left: 10, right: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(local!.homeUpdateTitle,
style: const TextStyle(fontSize: 20)),
Text(local.homeUpdateDescription,
style: const TextStyle(fontSize: 12)),
],
),
),
),
Positioned(
top: 0,
right: 0,
child: IconButton(
icon: const Icon(Icons.close),
onPressed: () {
setState(() {
updateAvailable = false;
});
},
),
),
],
),
),
),
if (lunch != -1 && apidataTT["lessons"].length > 0)
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
child: Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
lunch == -1
? Text(
local!.homeLunchesNotLoaded,
style: const TextStyle(fontSize: 20),
textAlign: TextAlign.center,
)
: lunch == 0
? Text(
local!.homeNoLunchToday,
style: const TextStyle(fontSize: 20),
textAlign: TextAlign.center,
)
: Text(
local!.homeLunchToday(lunch),
style: const TextStyle(fontSize: 20),
textAlign: TextAlign.center,
),
if (orderLunchesFor != DateTime(1998, 4, 10))
Text(local.homeLunchDontForget(orderLunchesFor)),
],
),
),
),
),
if (msgsWOR != [])
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
child: Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (Map<String, dynamic> m in msgsWOR.length < 5
? msgsWOR
: msgsWOR.getRange(0, 4))
InkWell(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
child: Row(
children: [
Expanded(
child: Card(
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${m["owner"]["firstname"]?.trim()} ${m["owner"]["lastname"]?.trim()}: ${m["text"]}'
.replaceAll(RegExp(r'\s+'), ' '),
softWrap: false,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MessagePage(
sessionManager:
widget.sessionManager,
id: int.parse(m["id"]))));
},
),
],
),
),
),
),
],
),
],
),
backgroundColor: theme.colorScheme.background,
drawer: Drawer(
child: ListView(
children: [
const Padding(
padding: EdgeInsets.only(top: 15),
),
InkWell(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
child: ListTile(
leading: const Icon(Icons.lunch_dining_rounded),
title: Text(local!.homeSetupICanteen),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ICanteenSetupScreen(
sessionManager: widget.sessionManager,
loadedCallback: () {
widget.reLogin();
},
),
),
);
},
),
),
InkWell(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
child: Badge(
label: Text(local.homePreview),
alignment: AlignmentDirectional.topEnd,
child: ListTile(
leading: const Icon(Icons.bolt_rounded),
title: Text(local.homeQuickstart),
trailing: Transform.scale(
scale: 0.75,
child: Switch(
value: quickstart,
onChanged: (bool value) {
sharedPreferences.setBool('quickstart', value);
setState(() {
quickstart = value;
});
},
),
),
onTap: () {
sharedPreferences.setBool('quickstart', !quickstart);
setState(() {
quickstart = !quickstart;
});
},
),
),
),
const Divider(),
InkWell(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
child: ListTile(
leading: const Icon(Icons.logout),
title: Text(local.homeLogout),
onTap: () {
sharedPreferences.remove('email');
sharedPreferences.remove('password');
sharedPreferences.remove('token');
widget.reLogin();
},
),
),
const AboutListTile(
icon: Icon(Icons.info_outline),
applicationName: 'EduPage2',
applicationVersion: String.fromEnvironment('BVS'),
applicationLegalese: '©2023 Jakub Palacký',
dense: true,
),
],
),
),
);
}
}