Skip to content

Commit

Permalink
Merge pull request #302 from mirea-ninja/release/v1.3.2
Browse files Browse the repository at this point in the history
* fix: Add displaying coursework in grades (#298)

* Исправлено #297
* Теперь оценки отображаются только для активного профиля ЛКС

* fix: Create new interner connection checker (#300)

* fix: Change default token storage to helper store (#301)
  • Loading branch information
0niel authored Mar 10, 2023
2 parents 358a7c4 + 3848c05 commit 3f57f02
Show file tree
Hide file tree
Showing 16 changed files with 155 additions and 80 deletions.
102 changes: 73 additions & 29 deletions lib/common/utils/connection_checker.dart
Original file line number Diff line number Diff line change
@@ -1,30 +1,74 @@
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';

/// The default parameters for DNS lookups
const Map<String, String> dnsParameters = {
'name': 'ya.ru',
'type': 'A',
'dnssec': '1',
};

/// The default headers for DNS lookups
const Map<String, String> dnsHeaders = {
'Accept': 'application/dns-json',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
};

final List<AddressCheckOptions> defaultAddresses = [
AddressCheckOptions(
Uri.parse('https://yandex.cloudflare-dns.com/dns-query').replace(
queryParameters: dnsParameters,
),
headers: dnsHeaders,
),
AddressCheckOptions(
Uri.parse('https://mozilla.cloudflare-dns.com/dns-query').replace(
queryParameters: dnsParameters,
),
headers: dnsHeaders,
),
import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';

/// The default hosts to ping to check for internet connection.
final List<String> defaultHosts = [
'ya.ru',
'google.com',
];

/// A class that checks if the device is connected to the internet.
///
/// It uses the [Connectivity] plugin to check for internet connection.
/// It also uses the [InternetAddress.lookup] method to ping the default hosts.
///
/// If the device is connected to the internet, the [connectionChange] stream
/// will emit true.
class InternetConnectionChecker {
static final InternetConnectionChecker _singleton =
InternetConnectionChecker._internal();
InternetConnectionChecker._internal();

static InternetConnectionChecker getInstance() => _singleton;

bool _hasConnection = false;

/// The stream that emits whenever the connection status changes.
StreamController connectionChangeController = StreamController.broadcast();

final Connectivity _connectivity = Connectivity();

void initialize() {
_connectivity.onConnectivityChanged.listen(_connectionChange);
checkConnection();
}

Stream get connectionChange => connectionChangeController.stream;

void dispose() {
connectionChangeController.close();
}

void _connectionChange(ConnectivityResult result) {
checkConnection();
}

Future<bool> checkConnection() async {
bool previousConnection = _hasConnection;

bool currentConnectionStatus = false;

for (var host in defaultHosts) {
try {
final result = await InternetAddress.lookup(host);
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
currentConnectionStatus = true;
break;
}
} on SocketException catch (_) {}
}

if (previousConnection != currentConnectionStatus) {
_hasConnection = currentConnectionStatus;
connectionChangeController.add(_hasConnection);
}

return _hasConnection;
}

Future<bool> get hasConnection async => await checkConnection();

bool get lastKnownConnection => _hasConnection;
}
16 changes: 7 additions & 9 deletions lib/data/datasources/user_local.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import 'dart:core';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:oauth2_client/oauth2_helper.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/oauth.dart';
import 'package:shared_preferences/shared_preferences.dart';

abstract class UserLocalData {
Future<void> setTokenToCache(String token);
Future<String> getTokenFromCache();
Future<void> removeTokenFromCache();

Expand All @@ -17,27 +18,24 @@ abstract class UserLocalData {
class UserLocalDataImpl implements UserLocalData {
final SharedPreferences sharedPreferences;
final FlutterSecureStorage secureStorage;
final OAuth2Helper oauthHelper;

UserLocalDataImpl({
required this.sharedPreferences,
required this.secureStorage,
required this.oauthHelper,
});

@override
Future<void> setTokenToCache(String token) {
return secureStorage.write(key: 'lks_access_token', value: token);
}

@override
Future<String> getTokenFromCache() async {
String? token = await secureStorage.read(key: 'lks_access_token');
var token = await oauthHelper.getToken();
if (token == null) throw CacheException('Auth token are not set');
return Future.value(token);
return Future.value(token.accessToken);
}

@override
Future<void> removeTokenFromCache() {
return secureStorage.delete(key: 'lks_access_token');
return oauthHelper.removeAllTokens();
}

@override
Expand Down
34 changes: 23 additions & 11 deletions lib/data/datasources/user_remote.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ abstract class UserRemoteData {
Future<List<AnnounceModel>> getAnnounces();
Future<List<EmployeeModel>> getEmployees(String name);
Future<List<AttendanceModel>> getAttendance(String dateStart, String dateEnd);
Future<Map<String, List<ScoreModel>>> getScores();
Future<Map<String, Map<String, List<ScoreModel>>>> getScores();
Future<List<NfcPassModel>> getNfcPasses(
String code, String studentId, String deviceId);
Future<int> getNfcCode(String code, String studentId, String deviceId);
Expand Down Expand Up @@ -132,7 +132,7 @@ class UserRemoteDataImpl implements UserRemoteData {
}

@override
Future<Map<String, List<ScoreModel>>> getScores() async {
Future<Map<String, Map<String, List<ScoreModel>>>> getScores() async {
final response = await lksOauth2.oauth2Helper.get(
'$_apiUrl/?action=getData&url=https://lk.mirea.ru/learning/scores/',
);
Expand All @@ -146,18 +146,30 @@ class UserRemoteDataImpl implements UserRemoteData {
}

if (response.statusCode == 200) {
Map<String, List<ScoreModel>> scores = {};
jsonResponse["SCORES"].values.first.forEach((key, value) {
if (scores.containsKey(key) == false) {
scores[key] = [];
}
Map<String, Map<String, List<ScoreModel>>> scoresByStudentCode = {};
final scoresRes = jsonResponse["SCORES"] as Map<String, dynamic>;

for (final score in value.values) {
scores[key]!.add(ScoreModel.fromJson(score[0]));
}
scoresRes.forEach((studentId, semesters) {
Map<String, List<ScoreModel>> scoresBySemester = {};
final semestersRes = semesters as Map<String, dynamic>;

semestersRes.forEach((semester, subjects) {
List<ScoreModel> scores = [];
final subjectsRes = subjects as Map<String, dynamic>;

subjectsRes.forEach((subjectId, score) {
for (final score in score) {
scores.add(ScoreModel.fromJson(score));
}
});

scoresBySemester[semester] = scores;
});

scoresByStudentCode[studentId] = scoresBySemester;
});

return scores;
return scoresByStudentCode;
} else {
throw ServerException('Response status code is ${response.statusCode}');
}
Expand Down
4 changes: 2 additions & 2 deletions lib/data/repositories/forum_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import 'package:dartz/dartz.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/forum_local.dart';
import 'package:rtu_mirea_app/data/datasources/forum_remote.dart';
import 'package:rtu_mirea_app/domain/entities/forum_member.dart';
import 'package:rtu_mirea_app/domain/repositories/forum_repository.dart';

class ForumRepositoryImpl implements ForumRepository {
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;
final ForumRemoteData remoteDataSource;
final ForumLocalData localDataSource;

Expand Down
4 changes: 2 additions & 2 deletions lib/data/repositories/github_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:dartz/dartz.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/github_local.dart';
import 'package:rtu_mirea_app/data/datasources/github_remote.dart';
import 'package:rtu_mirea_app/domain/entities/contributor.dart';
Expand All @@ -10,7 +10,7 @@ import 'package:rtu_mirea_app/domain/repositories/github_repository.dart';
class GithubRepositoryImpl implements GithubRepository {
final GithubRemoteData remoteDataSource;
final GithubLocalData localDataSource;
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;

GithubRepositoryImpl({
required this.remoteDataSource,
Expand Down
4 changes: 2 additions & 2 deletions lib/data/repositories/news_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import 'package:dartz/dartz.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/news_remote.dart';
import 'package:rtu_mirea_app/domain/entities/news_item.dart';
import 'package:rtu_mirea_app/domain/repositories/news_repository.dart';

class NewsRepositoryImpl implements NewsRepository {
final NewsRemoteData remoteDataSource;
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;

NewsRepositoryImpl({
required this.remoteDataSource,
Expand Down
4 changes: 2 additions & 2 deletions lib/data/repositories/schedule_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:dartz/dartz.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/schedule_local.dart';
import 'package:rtu_mirea_app/data/datasources/schedule_remote.dart';
import 'package:rtu_mirea_app/data/models/schedule_model.dart';
Expand All @@ -13,7 +13,7 @@ import 'package:rtu_mirea_app/domain/repositories/schedule_repository.dart';
class ScheduleRepositoryImpl implements ScheduleRepository {
final ScheduleRemoteData remoteDataSource;
final ScheduleLocalData localDataSource;
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;

ScheduleRepositoryImpl({
required this.remoteDataSource,
Expand Down
4 changes: 2 additions & 2 deletions lib/data/repositories/strapi_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import 'package:dartz/dartz.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';

import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/strapi_remote.dart';
import 'package:rtu_mirea_app/domain/entities/story.dart';
import 'package:rtu_mirea_app/domain/entities/update_info.dart';
import 'package:rtu_mirea_app/domain/repositories/strapi_repository.dart';

class StrapiRepositoryImpl implements StrapiRepository {
final StrapiRemoteData remoteDataSource;
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;
final PackageInfo packageInfo;

StrapiRepositoryImpl({
Expand Down
8 changes: 4 additions & 4 deletions lib/data/repositories/user_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:rtu_mirea_app/common/errors/exceptions.dart';
import 'package:rtu_mirea_app/common/errors/failures.dart';
import 'package:dartz/dartz.dart';
import 'package:rtu_mirea_app/common/utils/connection_checker.dart';
import 'package:rtu_mirea_app/data/datasources/user_local.dart';
import 'package:rtu_mirea_app/data/datasources/user_remote.dart';
import 'package:rtu_mirea_app/domain/entities/announce.dart';
Expand All @@ -15,7 +15,7 @@ import 'package:rtu_mirea_app/domain/repositories/user_repository.dart';
class UserRepositoryImpl implements UserRepository {
final UserRemoteData remoteDataSource;
final UserLocalData localDataSource;
final InternetConnectionCheckerPlus connectionChecker;
final InternetConnectionChecker connectionChecker;

UserRepositoryImpl({
required this.remoteDataSource,
Expand All @@ -27,7 +27,6 @@ class UserRepositoryImpl implements UserRepository {
if (await connectionChecker.hasConnection) {
try {
final authToken = await remoteDataSource.auth();
await localDataSource.setTokenToCache(authToken);
return Right(authToken);
} catch (e) {
if (e is ServerException) {
Expand Down Expand Up @@ -91,7 +90,8 @@ class UserRepositoryImpl implements UserRepository {
}

@override
Future<Either<Failure, Map<String, List<Score>>>> getScores() async {
Future<Either<Failure, Map<String, Map<String, List<Score>>>>>
getScores() async {
try {
final scores = await remoteDataSource.getScores();
return Right(scores);
Expand Down
2 changes: 1 addition & 1 deletion lib/domain/repositories/user_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ abstract class UserRepository {
Future<Either<Failure, User>> getUserData();
Future<Either<Failure, List<Announce>>> getAnnounces();
Future<Either<Failure, List<Employee>>> getEmployees(String name);
Future<Either<Failure, Map<String, List<Score>>>> getScores();
Future<Either<Failure, Map<String, Map<String, List<Score>>>>> getScores();
Future<Either<Failure, List<Attendance>>> getAattendance(
String dateStart, String dateEnd);
Future<Either<Failure, String>> getAuthToken();
Expand Down
5 changes: 3 additions & 2 deletions lib/domain/usecases/get_scores.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import 'package:rtu_mirea_app/domain/entities/score.dart';
import 'package:rtu_mirea_app/domain/repositories/user_repository.dart';
import 'package:rtu_mirea_app/domain/usecases/usecase.dart';

class GetScores extends UseCase<Map<String, List<Score>>, void> {
class GetScores extends UseCase<Map<String, Map<String, List<Score>>>, void> {
final UserRepository userRepository;

GetScores(this.userRepository);

@override
Future<Either<Failure, Map<String, List<Score>>>> call([params]) async {
Future<Either<Failure, Map<String, Map<String, List<Score>>>>> call(
[params]) async {
return userRepository.getScores();
}
}
10 changes: 9 additions & 1 deletion lib/presentation/bloc/scores_bloc/scores_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,18 @@ class ScoresBloc extends Bloc<ScoresEvent, ScoresState> {
emit(ScoresLoading());

final scores = await getScores();
final studentCode = event.studentCode;

scores.fold((failure) => emit(ScoresLoadError()), (result) {
final scores = result[studentCode];

if (scores == null) {
emit(ScoresLoadError());
return;
}

emit(ScoresLoaded(
scores: _sortScores(result), selectedSemester: result.keys.last));
scores: _sortScores(scores), selectedSemester: scores.keys.last));
});
}
}
Expand Down
4 changes: 3 additions & 1 deletion lib/presentation/bloc/scores_bloc/scores_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ abstract class ScoresEvent extends Equatable {
}

class LoadScores extends ScoresEvent {
const LoadScores();
const LoadScores({required this.studentCode});

final String studentCode;

@override
List<Object> get props => [];
Expand Down
Loading

0 comments on commit 3f57f02

Please sign in to comment.