Skip to content

Commit

Permalink
Timetable implementation in load.dart
Browse files Browse the repository at this point in the history
  • Loading branch information
vyPal committed Oct 1, 2023
1 parent 13c2b6b commit c780b2b
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 272 deletions.
2 changes: 1 addition & 1 deletion lib/home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ class HomePageState extends State<HomePage> {
),
),
),
if (lunch != -1 && apidataTT["lessons"].length > 0)
if (lunch != -1 && apidataTT["Days"].values.first.length > 0)
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
Expand Down
226 changes: 4 additions & 222 deletions lib/load.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:eduapge2/login.dart';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_session_manager/flutter_session_manager.dart';
Expand Down Expand Up @@ -35,7 +34,7 @@ class LoadingScreenState extends State<LoadingScreen> {
double progress = 0.0;
String loaderText = "Loading...";

String baseUrl = FirebaseRemoteConfig.instance.getString("baseUrl");
String baseUrl = FirebaseRemoteConfig.instance.getString("testUrl");

late AppLocalizations? local;

Expand Down Expand Up @@ -187,174 +186,6 @@ class LoadingScreenState extends State<LoadingScreen> {
.then((value) => init());
}

/*
Future<void> loadUser() async {
if (sharedPreferences.getBool("ice") == true) {
sessionManager.set("iCanteenEnabled", true);
}
String? failedToken;
if (sharedPreferences.getString("token") != null) {
String? token = sharedPreferences.getString("token");
progress = 0.2;
loaderText = local!.loadLoggingIn;
setState(() {});
Response response = await dio
.get(
"$baseUrl/login",
options: buildCacheOptions(
const Duration(days: 5),
maxStale: const Duration(days: 14),
forceRefresh: !quickstart,
options: Options(
headers: {
"Authorization": "Bearer $token",
},
),
),
)
.catchError((obj) {
sharedPreferences.remove("token");
failedToken = token;
return Response(
requestOptions: RequestOptions(path: "$baseUrl/login"),
statusCode: 500,
);
});
if (response.statusCode == 200) {
if (response.data.runtimeType == String) {
if (jsonDecode(response.data)["icanteen"] == true) {
await sessionManager.set('iCanteenEnabled', true);
}
} else {
if (response.data["icanteen"] == true) {
await sessionManager.set('iCanteenEnabled', true);
}
}
OneSignal.shared.setExternalUserId(token!);
progress = 0.5;
loaderText = local!.loadLoggedIn;
setState(() {});
if (response.data.runtimeType == Map) {
sessionManager.set('user', jsonEncode(response.data));
} else {
sessionManager.set('user', response.data);
}
return loadTimetable();
} else {
failedToken = token;
}
} else if (sharedPreferences.getString("email") != null &&
sharedPreferences.getString("password") != null) {
String? email = sharedPreferences.getString("email");
String? password = sharedPreferences.getString("password");
progress = 0.3;
loaderText = local!.loadAccessToken;
setState(() {});
Response response = await dio
.post(
"$baseUrl/token",
data: {
"email": email,
"password": password,
},
options: buildCacheOptions(
const Duration(days: 5),
forceRefresh: !quickstart,
),
)
.catchError((obj) {
return Response(
requestOptions: RequestOptions(path: "$baseUrl/token"),
statusCode: 500,
);
});
if (response.statusCode == 500) {
sharedPreferences.remove("email");
sharedPreferences.remove("password");
runningInit = false;
// ignore: use_build_context_synchronously
Navigator.push(context,
MaterialPageRoute(builder: (context) => const LoginPage()))
.then((value) => init());
} else {
if (response.data["token"] == failedToken) {
sharedPreferences.remove("email");
sharedPreferences.remove("password");
runningInit = false;
// ignore: use_build_context_synchronously
Navigator.push(context,
MaterialPageRoute(builder: (context) => const LoginPage()))
.then((value) => init());
} else {
sessionManager.set("token", response.data["token"]);
loaderText = local!.loadVerify;
setState(() {});
String token = response.data["token"];
response = await dio
.get(
"$baseUrl/login",
options: buildCacheOptions(
const Duration(days: 5),
maxStale: const Duration(days: 14),
forceRefresh: !quickstart,
options: Options(
headers: {
"Authorization": "Bearer ${response.data["token"]}",
},
),
),
)
.catchError((obj) {
sharedPreferences.remove("token");
failedToken = response.data["token"];
return Response(
requestOptions: RequestOptions(path: "$baseUrl/login"),
statusCode: 500,
);
});
if (response.statusCode == 200) {
if (response.data.runtimeType == String) {
if (jsonDecode(response.data)["icanteen"] == true) {
await sessionManager.set('iCanteenEnabled', true);
}
} else {
if (response.data["icanteen"] == true) {
await sessionManager.set('iCanteenEnabled', true);
}
}
OneSignal.shared.setExternalUserId(token);
progress = 0.6;
loaderText = local!.loadLoggedIn;
setState(() {});
if (response.data.runtimeType == Map) {
sessionManager.set('user', jsonEncode(response.data));
} else {
sessionManager.set('user', response.data);
}
return loadTimetable();
} else {
runningInit = false;
// ignore: use_build_context_synchronously
Navigator.push(context,
MaterialPageRoute(builder: (context) => const LoginPage()))
.then((value) => init());
}
}
}
} else {
runningInit = false;
Navigator.push(context,
MaterialPageRoute(builder: (context) => const LoginPage()))
.then((value) => init());
}
}
*/

DateTime getWeekDay() {
DateTime now = DateTime.now();
if (now.weekday > 5) {
Expand All @@ -367,39 +198,23 @@ class LoadingScreenState extends State<LoadingScreen> {
progress = 0.7;
loaderText = local!.loadDownloadTimetable;
setState(() {});
sessionManager.set("timetable",
jsonEncode({"date": DateTime.now().toString(), "lessons": []}));
return loadMessages();
}

/*
Future<void> loadTimetable() async {
progress = 0.7;
loaderText = local!.loadDownloadTimetable;
setState(() {});
final metric = FirebasePerformance.instance.newHttpMetric(
"$baseUrl/timetable/${getWeekDay().toString()}", HttpMethod.Get);
String token = sharedPreferences.getString("token")!;
metric.start();
Response response = await dio.get(
"$baseUrl/timetable/${getWeekDay().toString()}",
"$baseUrl/api/timetable?from=${getWeekDay().toIso8601String()}",
options: buildCacheOptions(
const Duration(days: 5),
maxStale: const Duration(days: 14),
forceRefresh: !quickstart,
forceRefresh: true,
options: Options(
headers: {
"Authorization": "Bearer $token",
},
),
),
);
metric.stop();
sessionManager.set("timetable", response.data);
sessionManager.set("timetable", jsonEncode(response.data));
return loadMessages();
}
*/

Future<void> loadMessages() async {
progress = 0.9;
Expand All @@ -426,39 +241,6 @@ class LoadingScreenState extends State<LoadingScreen> {
widget.loadedCallback();
}

/*
Future<void> loadMessages() async {
progress = 0.9;
loaderText = local!.loadDownloadMessages;
setState(() {});
final metric = FirebasePerformance.instance
.newHttpMetric("$baseUrl/messages", HttpMethod.Get);
String token = sharedPreferences.getString("token")!;
metric.start();
Response response = await dio.get(
"$baseUrl/messages",
options: buildCacheOptions(
const Duration(days: 5),
maxStale: const Duration(days: 14),
forceRefresh: !quickstart,
options: Options(
headers: {
"Authorization": "Bearer $token",
},
),
),
);
metric.stop();
sessionManager.set("messages", jsonEncode(response.data));
progress = 1.0;
loaderText = local!.loadDone;
setState(() {});
widget.loadedCallback();
}
*/

@override
Widget build(BuildContext context) {
if (!startedInit) {
Expand Down
2 changes: 1 addition & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ class PageBaseState extends State<PageBase> {
"testUrl": "https://edupage2server-1-c5607538.deta.app/"
});
await remoteConfig.fetchAndActivate();
baseUrl = remoteConfig.getString("baseUrl");
baseUrl = remoteConfig.getString("testUrl");
}

getMsgs() async {
Expand Down
67 changes: 19 additions & 48 deletions lib/timetable.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import 'dart:convert';

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
Expand Down Expand Up @@ -80,66 +78,39 @@ class TimeTablePageState extends State<TimeTablePage> {
apidataTT = await widget.sessionManager.get('timetable');

List<TimeTableClass> ttClasses = <TimeTableClass>[];
List<dynamic> lessons = apidataTT["lessons"];
for (Map<String, dynamic> ttLesson in lessons) {
Map<String, dynamic> lessons = response.data["Days"];
for (Map<String, dynamic> ttLesson
in lessons.values.isEmpty ? [] : lessons.values.first) {
ttClasses.add(
TimeTableClass(
ttLesson["period"]["name"],
ttLesson["uniperiod"],
ttLesson["subject"]["short"],
ttLesson["teachers"][0]["short"],
ttLesson["period"]["startTime"],
ttLesson["period"]["endTime"],
ttLesson["classrooms"][0]["short"],
ttLesson["teachers"].length > 0
? ttLesson["teachers"][0]["short"]
: "?",
ttLesson["starttime"],
ttLesson["endtime"],
ttLesson["classrooms"].length > 0
? ttLesson["classrooms"][0]["short"]
: "?",
0,
ttLesson,
),
);
}
tt = TimeTableData(DateTime.parse(apidataTT["date"]), ttClasses);
timetables.add(tt);
TimeTableData t = TimeTableData(
DateTime.parse(response.data["Days"].keys.isEmpty
? DateTime.now().toString()
: response.data["Days"].keys.first),
ttClasses);
timetables.add(t);

loading = false;
refresh = false;
setState(() {}); //refresh UI

if (sp.getBool('quickstart') ?? false) {
String token = sp.getString("token")!;
Dio dio = Dio();
Response response = await dio.get(
"$baseUrl/api/timetable?from=${getWeekDay().toIso8601String()}",
options: buildCacheOptions(
const Duration(days: 5),
maxStale: const Duration(days: 14),
forceRefresh: true,
options: Options(
headers: {
"Authorization": "Bearer $token",
},
),
),
);
widget.sessionManager.set("timetable", jsonEncode(response.data));

List<TimeTableClass> ttClasses = <TimeTableClass>[];
List<dynamic> lessons = jsonDecode(response.data)["lessons"];
for (Map<String, dynamic> ttLesson in lessons) {
ttClasses.add(
TimeTableClass(
ttLesson["period"]["name"],
ttLesson["subject"]["short"],
ttLesson["teachers"][0]["short"],
ttLesson["period"]["startTime"],
ttLesson["period"]["endTime"],
ttLesson["classrooms"][0]["short"],
0,
ttLesson,
),
);
}
tt = TimeTableData(DateTime.parse(apidataTT["date"]), ttClasses);
timetables.clear();
timetables.add(tt);

await loadTt(DateTime.now());
setState(() {});
}
}
Expand Down

0 comments on commit c780b2b

Please sign in to comment.