Skip to content

Commit

Permalink
Merge branch 'develop' into feature/launch_url_with_toast
Browse files Browse the repository at this point in the history
  • Loading branch information
rubuy-74 authored Sep 26, 2023
2 parents 2efdc7f + 85d7277 commit e58cdf8
Show file tree
Hide file tree
Showing 21 changed files with 140 additions and 183 deletions.
2 changes: 1 addition & 1 deletion uni/app_version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5.64+182
1.6.1+189
4 changes: 4 additions & 0 deletions uni/lib/controller/background_workers/notifications.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ class NotificationManager {
final userInfo = await AppSharedPreferences.getPersistentUserInfo();
final faculties = await AppSharedPreferences.getUserFaculties();

if (userInfo == null || faculties.isEmpty) {
return;
}

final session = await NetworkRouter.login(
userInfo.item1,
userInfo.item2,
Expand Down
38 changes: 19 additions & 19 deletions uni/lib/controller/local_storage/app_shared_preferences.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import 'package:uni/utils/favorite_widget_type.dart';
/// This database stores the user's student number, password and favorite
/// widgets.
class AppSharedPreferences {
static final iv = encrypt.IV.fromBase64('jF9jjdSEPgsKnf0jCl1GAQ==');
static final key =
encrypt.Key.fromBase64('DT3/GTNYldhwOD3ZbpVLoAwA/mncsN7U7sJxfFn3y0A=');

static const lastUpdateTimeKeySuffix = '_last_update_time';
static const String userNumber = 'user_number';
static const String userPw = 'user_password';
Expand All @@ -24,10 +28,6 @@ class AppSharedPreferences {
'tuition_notification_toogle';
static const String themeMode = 'theme_mode';
static const String locale = 'app_locale';
static const int keyLength = 32;
static const int ivLength = 16;
static final iv = encrypt.IV.fromLength(ivLength);

static const String favoriteCards = 'favorite_cards';
static final List<FavoriteWidgetType> defaultFavoriteCards = [
FavoriteWidgetType.schedule,
Expand Down Expand Up @@ -149,9 +149,12 @@ class AppSharedPreferences {
/// * the first element in the tuple is the user's student number.
/// * the second element in the tuple is the user's password, in plain text
/// format.
static Future<Tuple2<String, String>> getPersistentUserInfo() async {
static Future<Tuple2<String, String>?> getPersistentUserInfo() async {
final userNum = await getUserNumber();
final userPass = await getUserPassword();
if (userNum == null || userPass == null) {
return null;
}
return Tuple2(userNum, userPass);
}

Expand All @@ -164,22 +167,16 @@ class AppSharedPreferences {
}

/// Returns the user's student number.
static Future<String> getUserNumber() async {
static Future<String?> getUserNumber() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(userNumber) ??
''; // empty string for the case it does not exist
return prefs.getString(userNumber);
}

/// Returns the user's password, in plain text format.
static Future<String> getUserPassword() async {
static Future<String?> getUserPassword() async {
final prefs = await SharedPreferences.getInstance();
var pass = prefs.getString(userPw) ?? '';

if (pass != '') {
pass = decode(pass);
}

return pass;
final password = prefs.getString(userPw);
return password != null ? decode(password) : null;
}

/// Replaces the user's favorite widgets with [newFavorites].
Expand Down Expand Up @@ -270,15 +267,18 @@ class AppSharedPreferences {
}

/// Decrypts [base64Text].
static String decode(String base64Text) {
static String? decode(String base64Text) {
final encrypter = _createEncrypter();
return encrypter.decrypt64(base64Text, iv: iv);
try {
return encrypter.decrypt64(base64Text, iv: iv);
} catch (e) {
return null;
}
}

/// Creates an [encrypt.Encrypter] for encrypting and decrypting the user's
/// password.
static encrypt.Encrypter _createEncrypter() {
final key = encrypt.Key.fromLength(keyLength);
return encrypt.Encrypter(encrypt.AES(key));
}

Expand Down
67 changes: 32 additions & 35 deletions uni/lib/controller/networking/network_router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ class NetworkRouter {

final url =
'${NetworkRouter.getBaseUrls(faculties)[0]}mob_val_geral.autentica';

final response = await http.post(
url.toUri(),
body: {'pv_login': username, 'pv_password': password},
Expand All @@ -71,6 +70,7 @@ class NetworkRouter {
faculties,
persistentSession: persistentSession,
);

if (session == null) {
Logger().e('Login failed: user not authenticated');
return null;
Expand All @@ -90,11 +90,15 @@ class NetworkRouter {
static Future<Session?> reLoginFromSession(Session session) async {
final username = session.username;
final password = await AppSharedPreferences.getUserPassword();

if (password == null) {
Logger().e('Re-login failed: password not found');
return null;
}

final faculties = session.faculties;
final persistentSession = session.persistentSession;

Logger().d('Re-login from session: $username, $faculties');

return login(
username,
password,
Expand All @@ -110,17 +114,13 @@ class NetworkRouter {
String pass,
List<String> faculties,
) async {
return _loginLock.synchronized(() async {
final url =
'${NetworkRouter.getBaseUrls(faculties)[0]}vld_validacao.validacao';

final response = await http.post(
url.toUri(),
body: {'p_user': user, 'p_pass': pass},
).timeout(_requestTimeout);

return response.body;
});
final url =
'${NetworkRouter.getBaseUrls(faculties)[0]}vld_validacao.validacao';
final response = await http.post(
url.toUri(),
body: {'p_user': user, 'p_pass': pass},
).timeout(_requestTimeout);
return response.body;
}

/// Extracts the cookies present in [headers].
Expand Down Expand Up @@ -185,6 +185,7 @@ class NetworkRouter {
NavigationService.logoutAndPopHistory(null);
return Future.error('Login failed');
}

session
..username = newSession.username
..cookies = newSession.cookies;
Expand All @@ -211,20 +212,18 @@ class NetworkRouter {
/// Check if the user is still logged in,
/// performing a health check on the user's personal page.
static Future<bool> userLoggedIn(Session session) async {
return _loginLock.synchronized(() async {
Logger().d('Checking if user is still logged in');
Logger().d('Checking if user is still logged in');

final url = '${getBaseUrl(session.faculties[0])}'
'fest_geral.cursos_list?pv_num_unico=${session.username}';
final headers = <String, String>{};
headers['cookie'] = session.cookies;
final url = '${getBaseUrl(session.faculties[0])}'
'fest_geral.cursos_list?pv_num_unico=${session.username}';
final headers = <String, String>{};
headers['cookie'] = session.cookies;

final response = await (httpClient != null
? httpClient!.get(url.toUri(), headers: headers)
: http.get(url.toUri(), headers: headers));
final response = await (httpClient != null
? httpClient!.get(url.toUri(), headers: headers)
: http.get(url.toUri(), headers: headers));

return response.statusCode == 200;
});
return response.statusCode == 200;
}

/// Returns the base url of the user's faculties.
Expand All @@ -246,17 +245,15 @@ class NetworkRouter {
static Future<Response> killSigarraAuthentication(
List<String> faculties,
) async {
return _loginLock.synchronized(() async {
final url = '${NetworkRouter.getBaseUrl(faculties[0])}vld_validacao.sair';
final response = await http.get(url.toUri()).timeout(_requestTimeout);
final url = '${NetworkRouter.getBaseUrl(faculties[0])}vld_validacao.sair';
final response = await http.get(url.toUri()).timeout(_requestTimeout);

if (response.statusCode == 200) {
Logger().i('Logout Successful');
} else {
Logger().i('Logout Failed');
}
if (response.statusCode == 200) {
Logger().i('Logout Successful');
} else {
Logger().i('Logout Failed');
}

return response;
});
return response;
}
}
4 changes: 1 addition & 3 deletions uni/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ SentryEvent? beforeSend(SentryEvent event) {

Future<String> firstRoute() async {
final userPersistentInfo = await AppSharedPreferences.getPersistentUserInfo();
final userName = userPersistentInfo.item1;
final password = userPersistentInfo.item2;

if (userName != '' && password != '') {
if (userPersistentInfo != null) {
return '/${DrawerItem.navPersonalArea.title}';
}

Expand Down
25 changes: 11 additions & 14 deletions uni/lib/model/entities/lecture.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class Lecture {
String classNumber,
int occurrId,
) {
final endTime = startTime.add(Duration(seconds: 60 * 30 * blocks));
final endTime = startTime.add(Duration(minutes: 30 * blocks));
final lecture = Lecture(
subject,
typeClass,
Expand All @@ -44,28 +44,25 @@ class Lecture {
String subject,
String typeClass,
DateTime day,
String startTime,
String startTimeString,
int blocks,
String room,
String teacher,
String classNumber,
int occurrId,
) {
final startTimeHours = int.parse(startTime.substring(0, 2));
final startTimeMinutes = int.parse(startTime.substring(3, 5));
final endTimeHours =
(startTimeMinutes + (blocks * 30)) ~/ 60 + startTimeHours;
final endTimeMinutes = (startTimeMinutes + (blocks * 30)) % 60;
final startTime = day.add(
Duration(
hours: int.parse(startTimeString.substring(0, 2)),
minutes: int.parse(startTimeString.substring(3, 5)),
),
);
final endTime = startTime.add(Duration(minutes: 30 * blocks));
return Lecture(
subject,
typeClass,
day.add(Duration(hours: startTimeHours, minutes: startTimeMinutes)),
day.add(
Duration(
hours: startTimeMinutes + endTimeHours,
minutes: startTimeMinutes + endTimeMinutes,
),
),
startTime,
endTime,
blocks,
room,
teacher,
Expand Down
12 changes: 6 additions & 6 deletions uni/lib/model/providers/lazy/exam_provider.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:collection';

import 'package:tuple/tuple.dart';
import 'package:uni/controller/fetchers/exam_fetcher.dart';
import 'package:uni/controller/local_storage/app_exams_database.dart';
import 'package:uni/controller/local_storage/app_shared_preferences.dart';
Expand Down Expand Up @@ -42,27 +41,28 @@ class ExamProvider extends StateProviderNotifier {
Future<void> loadFromRemote(Session session, Profile profile) async {
await fetchUserExams(
ParserExams(),
await AppSharedPreferences.getPersistentUserInfo(),
profile,
session,
profile.courseUnits,
persistentSession:
(await AppSharedPreferences.getPersistentUserInfo()) != null,
);
}

Future<void> fetchUserExams(
ParserExams parserExams,
Tuple2<String, String> userPersistentInfo,
Profile profile,
Session session,
List<CourseUnit> userUcs,
) async {
List<CourseUnit> userUcs, {
required bool persistentSession,
}) async {
try {
final exams = await ExamFetcher(profile.courses, userUcs)
.extractExams(session, parserExams);

exams.sort((exam1, exam2) => exam1.begin.compareTo(exam2.begin));

if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (persistentSession) {
await AppExamsDatabase().saveNewExams(exams);
}

Expand Down
8 changes: 4 additions & 4 deletions uni/lib/model/providers/lazy/lecture_provider.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:collection';

import 'package:tuple/tuple.dart';
import 'package:uni/controller/fetchers/schedule_fetcher/schedule_fetcher.dart';
import 'package:uni/controller/fetchers/schedule_fetcher/schedule_fetcher_api.dart';
import 'package:uni/controller/fetchers/schedule_fetcher/schedule_fetcher_html.dart';
Expand Down Expand Up @@ -30,23 +29,24 @@ class LectureProvider extends StateProviderNotifier {
@override
Future<void> loadFromRemote(Session session, Profile profile) async {
await fetchUserLectures(
await AppSharedPreferences.getPersistentUserInfo(),
session,
profile,
persistentSession:
(await AppSharedPreferences.getPersistentUserInfo()) != null,
);
}

Future<void> fetchUserLectures(
Tuple2<String, String> userPersistentInfo,
Session session,
Profile profile, {
required bool persistentSession,
ScheduleFetcher? fetcher,
}) async {
try {
final lectures =
await getLecturesFromFetcherOrElse(fetcher, session, profile);

if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (persistentSession) {
final db = AppLecturesDatabase();
await db.saveNewLectures(lectures);
}
Expand Down
8 changes: 4 additions & 4 deletions uni/lib/model/providers/startup/profile_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class ProfileProvider extends StateProviderNotifier {
final userPersistentInfo =
await AppSharedPreferences.getPersistentUserInfo();

if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (userPersistentInfo != null) {
final profileDb = AppUserDataDatabase();
await profileDb.saveUserFees(feesBalance, feesLimit);
}
Expand All @@ -95,7 +95,7 @@ class ProfileProvider extends StateProviderNotifier {

final userPersistentInfo =
await AppSharedPreferences.getPersistentUserInfo();
if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (userPersistentInfo != null) {
final profileDb = AppUserDataDatabase();
await profileDb.saveUserPrintBalance(printBalance);
}
Expand All @@ -119,7 +119,7 @@ class ProfileProvider extends StateProviderNotifier {

final userPersistentInfo =
await AppSharedPreferences.getPersistentUserInfo();
if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (userPersistentInfo != null) {
// Course units are saved later, so we don't it here
final profileDb = AppUserDataDatabase();
await profileDb.insertUserData(_profile);
Expand All @@ -144,7 +144,7 @@ class ProfileProvider extends StateProviderNotifier {

final userPersistentInfo =
await AppSharedPreferences.getPersistentUserInfo();
if (userPersistentInfo.item1 != '' && userPersistentInfo.item2 != '') {
if (userPersistentInfo != null) {
final coursesDb = AppCoursesDatabase();
await coursesDb.saveNewCourses(courses);

Expand Down
Loading

0 comments on commit e58cdf8

Please sign in to comment.