You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
queuing_system/lib/home/app_provider.dart

564 lines
20 KiB
Dart

2 years ago
import 'dart:async';
import 'dart:developer';
import 'dart:io';
12 months ago
import 'package:connectivity_plus/connectivity_plus.dart';
2 years ago
import 'package:flutter/cupertino.dart';
2 years ago
import 'package:flutter_tts/flutter_tts.dart';
import 'package:intl/intl.dart';
2 years ago
import 'package:just_audio/just_audio.dart';
import 'package:queuing_system/core/api.dart';
2 years ago
import 'package:queuing_system/core/response_models/call_config_model.dart';
import 'package:queuing_system/core/response_models/patient_ticket_model.dart';
2 years ago
import 'package:queuing_system/core/response_models/prayers_widget_model.dart';
import 'package:queuing_system/core/response_models/rss_feed_model.dart';
2 years ago
import 'package:queuing_system/core/response_models/weathers_widget_model.dart';
import 'package:queuing_system/core/response_models/widgets_config_model.dart';
import 'package:queuing_system/main.dart';
2 years ago
import 'package:queuing_system/utils/call_by_voice.dart';
import 'package:queuing_system/utils/call_type.dart';
import 'package:queuing_system/utils/signalR_utils.dart';
2 years ago
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signalr_core/signalr_core.dart';
2 years ago
bool isVoiceActualCompletedGlobally = false;
2 years ago
class AppProvider extends ChangeNotifier {
AppProvider() {
2 years ago
callInitializations();
}
Future<void> callInitializations() async {
await startSignalHubConnection();
await getInfoWidgetsDetailsFromServer();
await getLastTimeUpdatedFromCache();
2 years ago
listenNetworkConnectivity();
2 years ago
listenAudioPlayerEvents();
2 years ago
getTheWidgetsConfigurationsEveryMidnight();
initializeFlutterTTS();
// await callPatientsAPI();
2 years ago
}
SignalRHelper signalRHelper = SignalRHelper();
final AudioPlayer audioPlayer = AudioPlayer();
2 years ago
FlutterTts flutterTts = FlutterTts();
2 years ago
CallConfig patientCallConfigurations = CallConfig();
2 years ago
List<PatientTicketModel> patientTickets = [];
List<PatientTicketModel> isQueuePatients = [];
2 years ago
String currentDeviceIp = "";
bool isCallingInProgress = false;
bool isInternetConnectionAvailable = true;
2 years ago
bool isApiCallNeeded = false;
2 years ago
initializeFlutterTTS() async {
flutterTts.setCompletionHandler(() => onVoiceCompleted());
}
Future<void> onVoiceCompleted() async {
logger.i("My Value is in setCompletionHandler: $isVoiceActualCompletedGlobally");
logger.i("isQueuePatients.length in setCompletionHandler: ${isQueuePatients.length}");
if (!isVoiceActualCompletedGlobally) {
return;
}
if (isQueuePatients.isNotEmpty) {
await Future.delayed(Duration(seconds: patientCallConfigurations.concurrentCallDelaySec)).whenComplete(
() async {
PatientTicketModel temp = PatientTicketModel();
if (patientTickets.isNotEmpty && isQueuePatients.length > 1) {
temp = patientTickets.elementAt(0);
patientTickets.removeAt(0);
}
notifyListeners();
if (isQueuePatients.isNotEmpty) {
isQueuePatients.removeAt(0);
}
if (patientTickets.isNotEmpty && isQueuePatients.length > 1) {
patientTickets.add(temp);
}
notifyListeners();
if (isQueuePatients.isNotEmpty) {
await voiceCallPatientTicket(patientTickets.first, "setCompletionHandler");
updatePatientTicket(patientTickets.first);
}
},
);
}
logger.i("here logger.ig: ${isQueuePatients.length}");
if (isQueuePatients.isEmpty) {
isCallingInProgress = false;
}
if (isApiCallNeeded && isQueuePatients.isEmpty) {
logger.i("Setting isCallingInProgress : $isCallingInProgress");
Timer(Duration(seconds: patientCallConfigurations.concurrentCallDelaySec), () async {
await callPatientsAPI();
isApiCallNeeded = false;
});
}
}
2 years ago
updateInternetConnection(bool value) {
isInternetConnectionAvailable = value;
notifyListeners();
}
ScreenOrientationEnum currentScreenRotation = ScreenOrientationEnum.portraitUp;
updateCurrentScreenRotation(ScreenOrientationEnum value) {
currentScreenRotation = value;
notifyListeners();
}
2 years ago
Future<void> getCurrentIP() async {
final ips = await NetworkInterface.list(type: InternetAddressType.IPv4);
for (var interface in ips) {
if (interface.name == "eth0") {
for (var address in interface.addresses) {
currentDeviceIp = address.address;
notifyListeners();
}
}
if (interface.name == "wlan0") {
for (var address in interface.addresses) {
currentDeviceIp = address.address;
notifyListeners();
}
}
}
}
WidgetsConfigModel? currentWidgetsConfigModel;
2 years ago
Future<void> getInfoWidgetsConfigurationsFromServer() async {
WidgetsConfigModel? widgetsConfigModel = await API.getWidgetConfigsFromServer(currentDeviceIp, onFailure: (error) {
logger.i("Api call failed with this error: ${error.toString()}");
2 years ago
});
if (widgetsConfigModel != null) currentWidgetsConfigModel = widgetsConfigModel;
notifyListeners();
2 years ago
}
WeathersWidgetModel currentWeathersWidgetModel = WeathersWidgetModel();
Future<void> getWeatherDetailsFromServer() async {
WeathersWidgetModel? weathersWidgetModel = await API.getWeatherDetailsFromServer(
(currentWidgetsConfigModel!.cityKey ?? "").toString(),
onFailure: (error) => logger.i("Api call failed with this error: ${error.toString()}"),
2 years ago
);
if (weathersWidgetModel != null) {
currentWeathersWidgetModel = weathersWidgetModel;
notifyListeners();
}
}
String nextPrayerToShowWithTime = '';
2 years ago
void getNextPrayerToShow() {
final current = DateTime.now();
logger.i("Checking Namaz time Locally at ${current.toString()} and ${current.timeZoneName} ");
if (DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.fajr!).isAfter(current)) {
final namazTime = DateFormat('hh:mm a').format(DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.fajr!));
nextPrayerToShowWithTime = "${patientCallConfigurations.fajrText} at $namazTime";
notifyListeners();
return;
}
if (DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.dhuhr!).isAfter(current)) {
final namazTime = DateFormat('hh:mm a').format(DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.dhuhr!));
nextPrayerToShowWithTime = "${patientCallConfigurations.dhuhrText} at $namazTime";
notifyListeners();
return;
}
if (DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.asr!).isAfter(current)) {
final namazTime = DateFormat('hh:mm a').format(DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.asr!));
nextPrayerToShowWithTime = "${patientCallConfigurations.asrText} at $namazTime";
notifyListeners();
return;
}
if (DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.maghrib!).isAfter(current)) {
final namazTime = DateFormat('hh:mm a').format(DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.maghrib!));
nextPrayerToShowWithTime = "${patientCallConfigurations.maghribText} at $namazTime";
notifyListeners();
return;
}
if (DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.isha!).isAfter(current)) {
final namazTime = DateFormat('hh:mm a').format(DateTime.fromMillisecondsSinceEpoch(currentPrayersWidgetModel.isha!));
nextPrayerToShowWithTime = "${patientCallConfigurations.ishaText} at $namazTime";
notifyListeners();
return;
}
2 years ago
}
PrayersWidgetModel currentPrayersWidgetModel = PrayersWidgetModel();
2 years ago
Future<void> getPrayerDetailsFromServer() async {
PrayersWidgetModel? prayersWidgetModel = await API.getPrayerDetailsFromServer(
12 months ago
latitude: currentWidgetsConfigModel!.projectLatitude ?? 0,
longitude: currentWidgetsConfigModel!.projectLongitude ?? 0,
onFailure: (error) => logger.i("Api call failed with this error: ${error.toString()}"));
2 years ago
if (prayersWidgetModel != null) {
2 years ago
currentPrayersWidgetModel = prayersWidgetModel;
logger.i("I got this data from Prayers: ${prayersWidgetModel.toString()}");
getNextPrayerToShow();
2 years ago
notifyListeners();
}
}
RssFeedModel currentRssFeedModel = RssFeedModel();
Future<void> getRssFeedDetailsFromServer() async {
RssFeedModel? rssFeedModel = await API.getRssFeedDetailsFromServer(languageId: 0, onFailure: (error) => logger.i("Api call failed with this error: ${error.toString()}"));
if (rssFeedModel != null) {
currentRssFeedModel = rssFeedModel;
logger.i("I got this data from RssFeed: ${currentRssFeedModel.rssFeed}");
notifyListeners();
}
}
2 years ago
Future<void> getInfoWidgetsDetailsFromServer() async {
// if (currentWidgetsConfigModel == null) return;
2 years ago
await getInfoWidgetsConfigurationsFromServer().whenComplete(() async {
if (currentWidgetsConfigModel!.isWeatherReq!) {
await getWeatherDetailsFromServer();
}
if (currentWidgetsConfigModel!.isPrayerTimeReq!) {
await getPrayerDetailsFromServer();
2 years ago
}
if (currentWidgetsConfigModel!.isRssFeedReq!) {
await getRssFeedDetailsFromServer();
}
2 years ago
});
int currentDate = DateTime.now().millisecondsSinceEpoch;
await setLastTimeUpdatedInCache(lasTimeUpdated: currentDate.toString());
}
2 years ago
int counter = 0;
2 years ago
Future<void> getTheWidgetsConfigurationsEveryMidnight() async {
if (currentWidgetsConfigModel == null) return;
if (!currentWidgetsConfigModel!.isWeatherReq! && !currentWidgetsConfigModel!.isPrayerTimeReq! && !currentWidgetsConfigModel!.isRssFeedReq!) {
2 years ago
return;
}
DateTime current = DateTime.now();
Stream timer = Stream.periodic(const Duration(minutes: 1), (i) {
current = current.add(const Duration(minutes: 1));
2 years ago
return current;
});
timer.listen((data) async {
DateTime dateTime = DateTime.parse(data.toString());
2 years ago
counter++;
logger.i("counterValue: $counter");
2 years ago
if (counter == 60 && currentWidgetsConfigModel!.isRssFeedReq!) {
await getRssFeedDetailsFromServer();
}
2 years ago
if (currentWidgetsConfigModel!.isWeatherReq!) {
if (dateTime.day > currentLastTimeUpdated.day) {
await getWeatherDetailsFromServer();
}
}
if (currentWidgetsConfigModel!.isPrayerTimeReq!) {
if (dateTime.day > currentLastTimeUpdated.day) {
await getPrayerDetailsFromServer();
}
}
if (currentWidgetsConfigModel!.isRssFeedReq!) {
if (dateTime.day > currentLastTimeUpdated.day) {
await getRssFeedDetailsFromServer();
}
}
getNextPrayerToShow();
2 years ago
});
}
2 years ago
Future<void> startSignalHubConnection() async {
if (!signalRHelper.getConnectionState()) {
2 years ago
await getCurrentIP().whenComplete(() => signalRHelper.startSignalRConnection(
currentDeviceIp,
onUpdateAvailable: onPingReceived,
onConnect: onConnect,
onConnecting: onConnecting,
onDisconnect: onDisconnect,
));
2 years ago
}
}
Future<void> callPatientsAPI() async {
logger.i("calling callPatientsAPI");
2 years ago
patientTickets.clear();
2 years ago
API.getCallRequestInfoByClinicInfo(currentDeviceIp,
onSuccess: (waitingCalls, isQueuePatientsCalls, callConfigs) async {
patientCallConfigurations = callConfigs;
if (waitingCalls.length > patientCallConfigurations.screenMaxDisplayPatients) {
patientTickets = waitingCalls.sublist(0, patientCallConfigurations.screenMaxDisplayPatients);
} else {
patientTickets = waitingCalls;
}
if (isQueuePatientsCalls.length > patientCallConfigurations.screenMaxDisplayPatients) {
isQueuePatients = isQueuePatientsCalls.sublist(0, patientCallConfigurations.screenMaxDisplayPatients);
} else {
isQueuePatients = isQueuePatientsCalls;
}
2 years ago
notifyListeners();
if (patientTickets.isNotEmpty) {
updateCurrentScreenRotation(patientTickets.first.screenRotationEnum);
await voiceCallPatientTicket(patientTickets.first, "callPatientsAPI");
2 years ago
updatePatientTicket(patientTickets.first);
}
},
onFailure: (error) => logger.i("Api call failed with this error: ${error.toString()}"));
2 years ago
}
onPingReceived(data) async {
logger.i("A new Ping Received when isQueuePatients: ${isQueuePatients.length}");
logger.i("isCallingInProgress from onPingReceived: $isCallingInProgress");
logger.i("isApiCallNeeded: $isApiCallNeeded");
2 years ago
if (patientTickets.isNotEmpty) {
2 years ago
if (isCallingInProgress) {
isApiCallNeeded = true;
2 years ago
} else {
await callPatientsAPI();
}
} else {
await callPatientsAPI();
}
}
2 years ago
String getCallTypeText(PatientTicketModel ticket) {
2 years ago
final callType = ticket.getCallType();
switch (callType) {
case CallType.vitalSign:
2 years ago
return ticket.callForVitalSignText;
2 years ago
case CallType.doctor:
2 years ago
return ticket.callForDoctorText;
2 years ago
case CallType.procedure:
2 years ago
return ticket.callForProcedureText;
2 years ago
case CallType.vaccination:
2 years ago
return ticket.callForVaccinationText;
2 years ago
case CallType.nebulization:
2 years ago
return ticket.callForNebulizationText;
2 years ago
default:
2 years ago
return ticket.callForVitalSignText;
2 years ago
}
}
CallByVoice? voiceCaller;
PatientTicketModel currentPatient = PatientTicketModel();
2 years ago
// testCalling() async {
// voiceCaller = CallByVoice(
// preVoice: "رقم التذكرة",
// ticketNo: "AMG A-78",
// postVoice: "دعوة للتطعيم",
// lang: "ar",
// flutterTts: flutterTts,
// );
// await voiceCaller!.startCalling(true);
// }
2 years ago
voiceCallPatientTicket(PatientTicketModel patientTicket, String calledFrom) async {
logger.i("voiceCallPatientTicket calledFrom : $calledFrom");
currentPatient = patientTicket;
2 years ago
isCallingInProgress = true;
logger.i("Setting isCallingInProgress : $isCallingInProgress");
2 years ago
logger.i("isVoiceReq: ${patientTicket.isVoiceReq}");
logger.i("voiceCaller: ${voiceCaller == null}");
logger.i("isQueue: ${patientTicket.isQueue}");
logger.i("isToneReq: ${patientTicket.isToneReq}");
2 years ago
if (patientTicket.isToneReq && !patientTicket.isQueue) {
audioPlayer.setAsset("assets/tones/call_tone.mp3");
await audioPlayer.play();
await Future.delayed(const Duration(seconds: 2));
2 years ago
}
2 years ago
if (patientTicket.isVoiceReq && voiceCaller == null && !patientTicket.isQueue) {
logger.i("patientTicket.voiceLanguage: ${patientTicket.voiceLanguage}");
2 years ago
final postVoice = getCallTypeText(patientTicket);
voiceCaller = CallByVoice(
2 years ago
preVoice: patientTicket.ticketNoText,
ticketNo: patientTicket.queueNo.trim().toString(),
postVoice: postVoice,
2 years ago
lang: patientTicket.voiceLanguage == 1 ? "en" : "ar",
flutterTts: flutterTts,
);
await voiceCaller!.startCalling(patientTicket.queueNo.trim().toString() != patientTicket.callNoStr.trim().toString()).whenComplete(() {
voiceCaller = null;
onVoiceCompleted();
logger.i("Completed Calling!! ${isQueuePatients.length}");
});
2 years ago
} else {
2 years ago
isCallingInProgress = false;
logger.i("Setting isCallingInProgress : $isCallingInProgress");
2 years ago
if (isApiCallNeeded) {
Timer(Duration(seconds: patientCallConfigurations.concurrentCallDelaySec), () async {
await callPatientsAPI();
isApiCallNeeded = false;
});
}
2 years ago
}
}
Future<void> listenAudioPlayerEvents() async {
audioPlayer.playerStateStream.listen((playerState) async {
2 years ago
if (playerState.processingState == ProcessingState.completed) {
logger.i("Tone Completed");
if (currentPatient.isVoiceReq) {
isCallingInProgress = true;
return;
}
if (isQueuePatients.isNotEmpty) {
isCallingInProgress = true;
logger.i("isQueuePatients.length 1: ${isQueuePatients.length}");
2 years ago
// for (int i = 0; i < length; i++) {
await Future.delayed(Duration(seconds: patientCallConfigurations.concurrentCallDelaySec)).whenComplete(() async {
PatientTicketModel temp = PatientTicketModel();
if (patientTickets.isNotEmpty && isQueuePatients.length > 1) {
temp = patientTickets.elementAt(0);
patientTickets.removeAt(0);
}
notifyListeners();
if (isQueuePatients.isNotEmpty) {
isQueuePatients.removeAt(0);
2 years ago
}
if (patientTickets.isNotEmpty && isQueuePatients.length > 1) {
patientTickets.add(temp);
2 years ago
}
notifyListeners();
logger.i("isQueuePatients.length 2: ${isQueuePatients.length}");
if (isQueuePatients.isNotEmpty) {
await voiceCallPatientTicket(patientTickets.first, "listenAudioPlayerEvents");
updatePatientTicket(patientTickets.first);
}
2 years ago
});
// }
}
2 years ago
if (isQueuePatients.isEmpty) {
isCallingInProgress = false;
}
if (isApiCallNeeded && isQueuePatients.isEmpty) {
logger.i("Setting isCallingInProgress : $isCallingInProgress");
Timer(Duration(seconds: patientCallConfigurations.concurrentCallDelaySec), () async {
await callPatientsAPI();
isApiCallNeeded = false;
});
}
2 years ago
}
});
}
2 years ago
// updatePatientTickets() {
// if (patientTickets.isNotEmpty) {
// List<Tickets> _ticketsToUpdate = patientTickets.where((t) => t.callUpdated == false).toList();
// API.callUpdateNotIsQueueRecordByIDAsync(currentDeviceIp, ticket: _ticketsToUpdate.first, onSuccess: (ticketsUpdated) {
// logger.i("[${ticketsUpdated.length}] Tickets Updated: $ticketsUpdated");
2 years ago
// }, onFailure: (e) {
// logger.i(" Tickets Update Failed with : ${e.toString()}");
2 years ago
// });
// }
// }
updatePatientTicket(PatientTicketModel patientTicket) {
2 years ago
if (!patientTicket.isQueue) {
API.callUpdateNotIsQueueRecordByIDAsync(currentDeviceIp, ticket: patientTicket, onSuccess: (ticketsUpdated) {
logger.i("[${patientTicket.callNoStr}] Ticket Updated: $ticketsUpdated");
2 years ago
}, onFailure: (e) {
logger.i(" Tickets Update ${patientTicket.callNoStr} Failed with Error : ${e.toString()}");
2 years ago
});
}
}
onConnect() {
logger.i("SignalR: onConnect");
2 years ago
}
onDisconnect(exception) {
logger.i("SignalR: onDisconnect");
12 months ago
signalRHelper.startSignalRConnection(
currentDeviceIp,
onUpdateAvailable: onPingReceived,
onConnect: onConnect,
onConnecting: onConnecting,
onDisconnect: onDisconnect,
);
2 years ago
}
onConnecting() {
logger.i("SignalR: onConnecting");
2 years ago
}
listenNetworkConnectivity() async {
12 months ago
Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> event) async {
switch (event.first) {
2 years ago
case ConnectivityResult.wifi:
12 months ago
case ConnectivityResult.ethernet:
2 years ago
updateInternetConnection(true);
await getCurrentIP();
if (signalRHelper.connection != null) {
if (signalRHelper.connection!.state != HubConnectionState.connected) signalRHelper.connection!.start();
2 years ago
}
break;
case ConnectivityResult.none:
updateInternetConnection(false);
signalRHelper.closeConnection();
break;
case ConnectivityResult.mobile:
break;
12 months ago
case ConnectivityResult.bluetooth:
// TODO: Handle this case.
break;
// TODO: Handle this case.
case ConnectivityResult.vpn:
// TODO: Handle this case.
break;
case ConnectivityResult.other:
// TODO: Handle this case.
break;
2 years ago
}
});
}
2 years ago
//SHARED PREFERENCE HANDLING
DateTime currentLastTimeUpdated = DateTime.now();
Future<String?> getLastTimeUpdatedFromCache() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey("lastTimeUpdated")) {
String? lastTimeUpdated = prefs.getString("lastTimeUpdated");
currentLastTimeUpdated = DateTime.fromMillisecondsSinceEpoch(int.parse(lastTimeUpdated!));
return lastTimeUpdated;
} else {
return null;
}
}
Future<void> setLastTimeUpdatedInCache({required String lasTimeUpdated}) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString("lastTimeUpdated", lasTimeUpdated);
}
2 years ago
}