Skip to content

Commit

Permalink
Changed tuples to records (#1395)
Browse files Browse the repository at this point in the history
  • Loading branch information
DGoiana authored Dec 4, 2024
2 parents a5c5366 + 91b145c commit 97fe376
Show file tree
Hide file tree
Showing 14 changed files with 76 additions and 87 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import 'package:logger/logger.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/controller/background_workers/notifications.dart';
import 'package:workmanager/workmanager.dart';

/// This map contains the functions that a certain task type will run.
/// the bool is all functions that are ran by backgroundfetch in iOS
/// (they must not take any arguments, not checked)
const taskMap = {
'pt.up.fe.ni.uni.notificationworker':
Tuple2(NotificationManager.updateAndTriggerNotifications, true),
'pt.up.fe.ni.uni.notificationworker': (
NotificationManager.updateAndTriggerNotifications,
true
),
};

@pragma('vm:entry-point')
Expand All @@ -25,16 +26,16 @@ Future<void> workerStartCallback() async {
// by the iOS scheduler.
if (taskName == Workmanager.iOSBackgroundTask) {
taskMap.forEach((key, value) async {
if (value.item2) {
if (value.$2) {
Logger().d('''[$key]: Start executing job...''');
await value.item1();
await value.$1();
}
});
return true;
}
// try to keep the usage of this function BELOW +-30 seconds
// to not be punished by the scheduler in future runs.
await taskMap[taskName]!.item1();
await taskMap[taskName]!.$1();
} catch (err, st) {
Logger().e(
'Error while running $taskName job:',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/controller/background_workers/notifications/tuition_notification.dart';
import 'package:uni/controller/local_storage/notification_timeout_storage.dart';
import 'package:uni/controller/local_storage/preferences_controller.dart';
Expand All @@ -28,12 +27,12 @@ abstract class Notification {
String uniqueID;
Duration timeout;

Future<Tuple2<String, String>> buildNotificationContent(Session session);
Future<(String, String)> buildNotificationContent(Session session);

Future<bool> shouldDisplay(Session session);

void displayNotification(
Tuple2<String, String> content,
(String, String) content,
FlutterLocalNotificationsPlugin localNotificationsPlugin,
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/controller/background_workers/notifications.dart';
import 'package:uni/controller/fetchers/fees_fetcher.dart';
import 'package:uni/controller/local_storage/preferences_controller.dart';
Expand All @@ -13,20 +12,20 @@ class TuitionNotification extends Notification {
late DateTime _dueDate;

@override
Future<Tuple2<String, String>> buildNotificationContent(
Future<(String, String)> buildNotificationContent(
Session session,
) async {
// We must add one day because the time limit is actually at 23:59 and
// not at 00:00 of the same day
if (_dueDate.add(const Duration(days: 1)).isBefore(DateTime.now())) {
final duration = DateTime.now().difference(_dueDate);
if (duration.inDays == 0) {
return const Tuple2(
return const (
'⚠️ Ainda não pagaste as propinas ⚠️',
'O prazo para pagar as propinas acabou ontem',
);
}
return Tuple2(
return (
'⚠️ Ainda não pagaste as propinas ⚠️',
duration.toFormattedString(
'Já passou {} desde a data limite',
Expand All @@ -36,12 +35,12 @@ class TuitionNotification extends Notification {
}
final duration = _dueDate.difference(DateTime.now());
if (duration.inDays == 0) {
return const Tuple2(
return const (
'O prazo limite para as propinas está a acabar',
'Hoje acaba o prazo para pagamento das propinas!',
);
}
return Tuple2(
return (
'O prazo limite para as propinas está a acabar',
duration.toFormattedString(
'Falta {} para a data limite',
Expand Down Expand Up @@ -72,7 +71,7 @@ class TuitionNotification extends Notification {

@override
void displayNotification(
Tuple2<String, String> content,
(String, String) content,
FlutterLocalNotificationsPlugin localNotificationsPlugin,
) {
const androidNotificationDetails = AndroidNotificationDetails(
Expand All @@ -95,8 +94,8 @@ class TuitionNotification extends Notification {

localNotificationsPlugin.show(
2,
content.item1,
content.item2,
content.$1,
content.$2,
notificationDetails,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@ import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/model/entities/library_occupation.dart';

/// Fetch the library occupation from Google Sheets
class LibraryOccupationFetcher {
String baseUrl = 'https://webapi.affluences.com/api/fillRate?';

static const List<Tuple2<String, int>> floorMaxSeats = [
Tuple2('BruV6IlujdwAe1', 72),
Tuple2('cEhyzJZvC5nHSr', 114),
Tuple2('iceVfgwZWaZRhV', 114),
Tuple2('1yLPz9X0CNsg27', 114),
Tuple2('keu1j5zERlQn90', 40),
Tuple2('bY7K1v43HiAq55', 90),
static const List<(String, int)> floorMaxSeats = [
('BruV6IlujdwAe1', 72),
('cEhyzJZvC5nHSr', 114),
('iceVfgwZWaZRhV', 114),
('1yLPz9X0CNsg27', 114),
('keu1j5zERlQn90', 40),
('bY7K1v43HiAq55', 90),
];

Future<LibraryOccupation> getLibraryOccupation() async {
Expand All @@ -26,14 +25,13 @@ class LibraryOccupationFetcher {
floorMaxSeats.mapIndexed((i, entry) async {
final url = Uri.parse(baseUrl).replace(
queryParameters: {
'token': entry.item1,
'token': entry.$1,
},
);

final response = await http.get(url);

final floorOccupation =
processFloorOccupation(response, entry.item2, i);
final floorOccupation = processFloorOccupation(response, entry.$2, i);

libraryOccupation.addFloor(floorOccupation);
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class AppUserDataDatabase extends AppDatabase<Profile> {
for (final keymap in data.keymapValues()) {
await insertInDatabase(
'userdata',
{'name': keymap.item1, 'value': keymap.item2},
{'name': keymap.$1, 'value': keymap.$2},
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import 'dart:convert';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/model/entities/meal.dart';
import 'package:uni/model/entities/restaurant.dart';
import 'package:uni/model/utils/day_of_week.dart';
Expand All @@ -18,15 +17,15 @@ List<Restaurant> getRestaurantsFromHtml(Response response) {
final restaurantsTuple = restaurantsHtml.map((restaurantHtml) {
final name = restaurantHtml.text;
final ref = restaurantHtml.attributes['href']?.replaceAll('#', '');
return Tuple2(ref ?? '', name);
return (ref ?? '', name);
}).toList();

// Get restaurant meals and create the Restaurant class
final restaurants = restaurantsTuple.map((restaurantTuple) {
final meals = <Meal>[];

final referenceA =
document.querySelector('a[name="${restaurantTuple.item1}"]');
document.querySelector('a[name="${restaurantTuple.$1}"]');
var next = referenceA?.nextElementSibling;

final format = DateFormat('d-M-y');
Expand Down Expand Up @@ -70,8 +69,8 @@ List<Restaurant> getRestaurantsFromHtml(Response response) {
}
return Restaurant(
null,
restaurantTuple.item2,
restaurantTuple.item1,
restaurantTuple.$2,
restaurantTuple.$1,
meals: meals,
);
}).toList();
Expand Down
11 changes: 5 additions & 6 deletions packages/uni_app/lib/model/converters/tuple_converter.dart
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:tuple/tuple.dart';

class TupleConverter extends JsonConverter<Tuple2<String, String>?, String?> {
class TupleConverter extends JsonConverter<(String, String)?, String?> {
const TupleConverter();

@override
Tuple2<String, String>? fromJson(String? json) {
(String, String)? fromJson(String? json) {
if (json == null) {
return null;
}
return Tuple2<String, String>('', json);
return ('', json);
}

@override
String? toJson(Tuple2<String, String>? object) {
String? toJson((String, String)? object) {
if (object == null) {
return null;
}
return object.item2;
return object.$2;
}
}
3 changes: 1 addition & 2 deletions packages/uni_app/lib/model/entities/bug_report.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Stores information about Bug Report
import 'package:json_annotation/json_annotation.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/model/converters/tuple_converter.dart';

part '../../generated/model/entities/bug_report.g.dart';
Expand All @@ -16,7 +15,7 @@ class BugReport {
final String title;
final String text;
final String email;
final Tuple2<String, String>? bugLabel;
final (String, String)? bugLabel;
final List<String> faculties;

Map<String, dynamic> toJson() => _$BugReportToJson(this);
Expand Down
13 changes: 6 additions & 7 deletions packages/uni_app/lib/model/entities/profile.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'dart:convert';

import 'package:http/http.dart';
import 'package:tuple/tuple.dart';
import 'package:uni/model/entities/course.dart';
import 'package:uni/model/entities/course_units/course_unit.dart';

Expand Down Expand Up @@ -43,13 +42,13 @@ class Profile {

/// Returns a list with two tuples: the first tuple contains the user's name
/// and the other one contains the user's email.
List<Tuple2<String, String>> keymapValues() {
List<(String, String)> keymapValues() {
return [
Tuple2('name', name),
Tuple2('email', email),
Tuple2('printBalance', printBalance),
Tuple2('feesBalance', feesBalance),
Tuple2(
('name', name),
('email', email),
('printBalance', printBalance),
('feesBalance', feesBalance),
(
'feesLimit',
feesLimit != null ? feesLimit!.toIso8601String() : '',
),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'dart:collection';

import 'package:tuple/tuple.dart';
import 'package:uni/controller/fetchers/course_units_fetcher/course_units_info_fetcher.dart';
import 'package:uni/model/entities/course_units/course_unit.dart';
import 'package:uni/model/entities/course_units/course_unit_class.dart';
Expand All @@ -15,24 +14,24 @@ typedef ClassesMap = Map<CourseUnit, List<CourseUnitClass>>;
typedef FilesMap = Map<CourseUnit, List<CourseUnitFileDirectory>>;

class CourseUnitsInfoProvider
extends StateProviderNotifier<Tuple3<SheetsMap, ClassesMap, FilesMap>> {
extends StateProviderNotifier<(SheetsMap, ClassesMap, FilesMap)> {
CourseUnitsInfoProvider()
: super(
cacheDuration: null,
// Const constructor is not allowed here because of the
// need for mutable maps
// ignore: prefer_const_constructors
initialState: Tuple3({}, {}, {}),
initialState: ({}, {}, {}),
);

UnmodifiableMapView<CourseUnit, Sheet> get courseUnitsSheets =>
UnmodifiableMapView(state!.item1);
UnmodifiableMapView(state!.$1);

UnmodifiableMapView<CourseUnit, List<CourseUnitClass>>
get courseUnitsClasses => UnmodifiableMapView(state!.item2);
get courseUnitsClasses => UnmodifiableMapView(state!.$2);

UnmodifiableMapView<CourseUnit, List<CourseUnitFileDirectory>>
get courseUnitsFiles => UnmodifiableMapView(state!.item3);
get courseUnitsFiles => UnmodifiableMapView(state!.$3);

Future<void> fetchCourseUnitSheet(
CourseUnit courseUnit,
Expand All @@ -43,7 +42,7 @@ class CourseUnitsInfoProvider
return;
}

state!.item1[courseUnit] =
state!.$1[courseUnit] =
await CourseUnitsInfoFetcher().fetchSheet(session, occurrId);
}

Expand All @@ -56,7 +55,7 @@ class CourseUnitsInfoProvider
return;
}

state!.item2[courseUnit] = await CourseUnitsInfoFetcher()
state!.$2[courseUnit] = await CourseUnitsInfoFetcher()
.fetchCourseUnitClasses(session, occurrId);
notifyListeners();
}
Expand All @@ -70,22 +69,30 @@ class CourseUnitsInfoProvider
return;
}

state!.item3[courseUnit] =
state!.$3[courseUnit] =
await CourseUnitsInfoFetcher().fetchCourseUnitFiles(session, occurrId);
notifyListeners();
}

@override
Future<Tuple3<SheetsMap, ClassesMap, FilesMap>> loadFromRemote(
Future<(SheetsMap, ClassesMap, FilesMap)> loadFromRemote(
StateProviders stateProviders,
) async {
return const Tuple3({}, {}, {});
return (
<CourseUnit, Sheet>{},
<CourseUnit, List<CourseUnitClass>>{},
<CourseUnit, List<CourseUnitFileDirectory>>{}
);
}

@override
Future<Tuple3<SheetsMap, ClassesMap, FilesMap>> loadFromStorage(
Future<(SheetsMap, ClassesMap, FilesMap)> loadFromStorage(
StateProviders stateProviders,
) async {
return const Tuple3({}, {}, {});
return (
<CourseUnit, Sheet>{},
<CourseUnit, List<CourseUnitClass>>{},
<CourseUnit, List<CourseUnitFileDirectory>>{}
);
}
}
Loading

0 comments on commit 97fe376

Please sign in to comment.