Skip to content

Commit

Permalink
patch: arreglos
Browse files Browse the repository at this point in the history
* Se agrega método para enviar notificaciones de anuncios.
* Se repara error en notificaciones.
* Se repara error al refrescar datos en segundo plano.

Signed-off-by: Francisco Solis <30329003+Im-Fran@users.noreply.github.com>
  • Loading branch information
Im-Fran committed Jun 25, 2024
1 parent 00cf7a0 commit 5a2fcf9
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 43 deletions.
6 changes: 1 addition & 5 deletions lib/screens/credencial_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,8 @@ class _CredencialScreenState extends State<CredencialScreen> {
final authService = Get.find<AuthService>();
final carrerasService = Get.find<CarrerasService>();

if(carrerasService.selectedCarrera == null) {
await carrerasService.getCarreras();
}

final user = await authService.getUser();
final carrera = carrerasService.selectedCarrera;
final carrera = await carrerasService.getCarreras();

return Pair(user, carrera);
}(),
Expand Down
8 changes: 2 additions & 6 deletions lib/screens/onboarding/notifications_screen.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/material.dart';
import 'package:mi_utem/models/preferencia.dart';
import 'package:mi_utem/screens/main_screen.dart';
Expand Down Expand Up @@ -93,13 +92,10 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
await Preferencia.onboardingStep.set("complete");
Navigator.popUntil(context, (route) => route.isFirst);
final alias = await Preferencia.apodo.get();
AwesomeNotifications().createNotification(content: NotificationContent(
id: 1,
channelKey: NotificationService.announcementsChannelKey,
actionType: ActionType.Default,
NotificationService.showAnnouncementNotification(
title: alias != null ? "¡Hola $alias! 🎉" : "¡Hola! 🎉",
body: '¡Te damos la bienvenida a la aplicación Mi UTEM! 🚀',
));
);
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => MainScreen()));
},
style: ElevatedButton.styleFrom(
Expand Down
4 changes: 2 additions & 2 deletions lib/services/auth_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ class AuthService {
Future<bool> isLoggedIn({ bool forceRefresh = false }) async {
final credentials = await _getCredential();
if(credentials == null) {
logger.d("[AuthService#isLoggedIn]: no credential");
logger.d("[AuthService#isLoggedIn]: No se encontraron credenciales.");
return false;
}

final user = await getUser();
final userToken = user?.token;
if(user == null || userToken == null) {
logger.d("[AuthService#isLoggedIn]: Usuario o token nulo (user: ${user == null}, token: ${userToken == null})");
logger.d("[AuthService#isLoggedIn]: Usuario o token nulo (user?: ${user == null}, token?: ${userToken == null})");
return false;
}

Expand Down
82 changes: 53 additions & 29 deletions lib/services/background_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ class BackgroundController {
}

class BackgroundService {

static Future<void> initAndStart() async {
BackgroundFetch.registerHeadlessTask(BackgroundController.backgroundFetchHeadlessTask);
await BackgroundFetch.configure(_backgroundFetchConfig, (taskId) {
Sentry.metrics().timing("BackgroundFetch_$taskId",
function: _onFetch(taskId),
unit: DurationSentryMeasurementUnit.milliSecond,
);
}, _onTimeout);
await BackgroundFetch.configure(_backgroundFetchConfig, (taskId) => Sentry.metrics().timing("BackgroundFetch_$taskId",
function: () async => await _onFetch(taskId),
unit: DurationSentryMeasurementUnit.milliSecond,
), _onTimeout);

BackgroundFetch.start().then((_) {}).catchError((e, stackTrace) {
Sentry.captureException(e, stackTrace: stackTrace);
Expand All @@ -71,31 +70,38 @@ class BackgroundService {
now = DateTime.now();

// Refresca las carreras
await Get.find<CarrerasRepository>().getCarreras(forceRefresh: true);
logger.d("[BackgroundFetch]: Se refrescaron las carreras, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
now = await refrescarCarreras(now);

// Actualiza el horario
now = await refrescarHorario(now);

// Revisa si hubo un cambio en las notas
await Get.find<GradesService>().lookForGradeUpdates();
logger.d("[BackgroundFetch]: Se revisaron las notas, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
now = await notificarCambiosNotas(now);

// Actualiza los permisos de ingreso
now = await refrescarPermisos(now);

// Actualiza los datos de las asignaturas
now = await refrescarAsignaturasYEstudiantes(now);

logger.d("[BackgroundFetch]: Se terminó la tarea '$taskId', tomó ${DateTime.now().difference(init).inMilliseconds} ms");
}

static Future<DateTime> refrescarHorario(DateTime now) async {
try {
PermisoIngresoRepository permisoIngresoRepository = Get.find<PermisoIngresoRepository>();
final permisos = await permisoIngresoRepository.getPermisos(forceRefresh: true);
for(final permiso in permisos) {
final id = permiso.id;
if(id == null) continue;
await permisoIngresoRepository.getDetallesPermiso(id, forceRefresh: true);
final carreraId = (await Get.find<CarrerasService>().getCarreras())?.id;
if(carreraId != null) {
await Get.find<HorarioRepository>().getHorario(carreraId, forceRefresh: true);
}
} catch (_){}
logger.d("[BackgroundFetch]: Se refrescaron los permisos de ingreso, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
} catch(_){}
logger.d("[BackgroundFetch]: Se refrescó el horario, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
return now;
}

// Actualiza los datos de las carreras y asignaturas
static Future<DateTime> refrescarAsignaturasYEstudiantes(DateTime now) async {
try {
final carreraId = Get.find<CarrerasService>().selectedCarrera?.id;
final carreraId = (await Get.find<CarrerasService>().getCarreras())?.id;
if(carreraId != null) {
AsignaturasRepository asignaturasRepository = Get.find<AsignaturasRepository>();
final asignaturas = await asignaturasRepository.getAsignaturas(carreraId, forceRefresh: true) ?? [];
Expand All @@ -106,18 +112,36 @@ class BackgroundService {
} catch(_){}
logger.d("[BackgroundFetch]: Se refrescaron los datos de las carreras y asignaturas, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
return now;
}

// Actualiza el horario
static Future<DateTime> refrescarPermisos(DateTime now) async {
try {
final carreraId = Get.find<CarrerasService>().selectedCarrera?.id;
if(carreraId != null) {
await Get.find<HorarioRepository>().getHorario(carreraId, forceRefresh: true);
PermisoIngresoRepository permisoIngresoRepository = Get.find<PermisoIngresoRepository>();
final permisos = await permisoIngresoRepository.getPermisos(forceRefresh: true);
for(final permiso in permisos) {
final id = permiso.id;
if(id == null) continue;
await permisoIngresoRepository.getDetallesPermiso(id, forceRefresh: true);
}
} catch(_){}
logger.d("[BackgroundFetch]: Se refrescó el horario, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
} catch (_){}
logger.d("[BackgroundFetch]: Se refrescaron los permisos de ingreso, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
return now;
}

logger.d("[BackgroundFetch]: Se terminó la tarea '$taskId', tomó ${DateTime.now().difference(init).inMilliseconds} ms");
static Future<DateTime> notificarCambiosNotas(DateTime now) async {
await Get.find<GradesService>().lookForGradeUpdates();
logger.d("[BackgroundFetch]: Se revisaron las notas, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
return now;
}

static Future<DateTime> refrescarCarreras(DateTime now) async {
await Get.find<CarrerasRepository>().getCarreras(forceRefresh: true);
logger.d("[BackgroundFetch]: Se refrescaron las carreras, tomó ${DateTime.now().difference(now).inMilliseconds} ms");
now = DateTime.now();
return now;
}

static _onTimeout(String taskId) async {
Expand Down
21 changes: 21 additions & 0 deletions lib/services/notification_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,27 @@ class NotificationService {
return isAllowed;
}

static void showAnnouncementNotification({
required String title,
required String body,
Map<String, dynamic> payload = const {},
}) async {
if(!await hasAllowedNotifications()) {
return;
}

notifications.createNotification(content: NotificationContent(
id: payload.hashCode,
channelKey: announcementsChannelKey,
title: title,
body: body,
payload: {
'type': 'announcement',
...payload,
},
));
}

static void showGradeChangeNotification({
required String title,
required String body,
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: mi_utem
description: 'Plataforma académica para estudiantes de la Universidad Tecnológica Metropolitana (UTEM)'
publish_to: none

version: 3.0.0+126
version: 3.0.0+129

environment:
sdk: ">=2.17.0 <3.0.0"
Expand Down

0 comments on commit 5a2fcf9

Please sign in to comment.