213 lines
7.1 KiB
C#
213 lines
7.1 KiB
C#
using Jugenddienst_Stunden.Models;
|
||
using Jugenddienst_Stunden.Types;
|
||
using Jugenddienst_Stunden.ViewModels;
|
||
using ZXing.Net.Maui;
|
||
|
||
|
||
namespace Jugenddienst_Stunden.Views;
|
||
|
||
/// <summary>
|
||
/// Die Loginseite mit dem Barcodescanner
|
||
/// </summary>
|
||
public partial class LoginPage : ContentPage {
|
||
private DateTime _lastDetectionTime;
|
||
private readonly TimeSpan _detectionInterval = TimeSpan.FromSeconds(5);
|
||
|
||
|
||
/// <summary>
|
||
/// CTOR
|
||
/// </summary>
|
||
public LoginPage() {
|
||
InitializeComponent();
|
||
|
||
// BindingContext via DI beziehen, falls nicht bereits gesetzt
|
||
try {
|
||
if (BindingContext is null) {
|
||
var sp = Application.Current?.Handler?.MauiContext?.Services
|
||
?? throw new InvalidOperationException("DI container ist nicht verfügbar.");
|
||
BindingContext = sp.GetRequiredService<LoginViewModel>();
|
||
}
|
||
} catch (Exception) {
|
||
// Ignorieren: Fallback bleibt leerer BindingContext
|
||
}
|
||
|
||
if (BindingContext is LoginViewModel vm) {
|
||
vm.AlertEvent += async (_, msg) => await DisplayAlert("Fehler:", msg, "OK");
|
||
//vm.InfoEvent += async (_, msg) => await DisplayAlert("Information:", msg, "OK");
|
||
// Neues InfoEvent: Dialog anzeigen und nach Bestätigung das Result setzen
|
||
vm.InfoEvent += async (_, infoArgs) => {
|
||
await MainThread.InvokeOnMainThreadAsync(async () => {
|
||
await DisplayAlert(infoArgs.Title, infoArgs.Message, infoArgs.ConfirmText);
|
||
infoArgs.SetResult(true);
|
||
});
|
||
};
|
||
}
|
||
|
||
barcodeScannerView.Options =
|
||
new BarcodeReaderOptions { Formats = BarcodeFormat.QrCode, AutoRotate = true, Multiple = false };
|
||
|
||
// Fallback-Verkabelung: Falls das EventToCommandBehavior in XAML nicht greift,
|
||
// leiten wir das Kamera-Event manuell an das ViewModel-Command weiter.
|
||
barcodeScannerView.BarcodesDetected += (s, e) => {
|
||
if (BindingContext is LoginViewModel vm && vm.QrDetectedCommand is not null) {
|
||
// Sicherstellen, dass die Command-Ausführung im UI-Thread erfolgt
|
||
MainThread.BeginInvokeOnMainThread(async () => {
|
||
if (vm.QrDetectedCommand.CanExecute(e)) {
|
||
await vm.QrDetectedCommand.ExecuteAsync(e);
|
||
}
|
||
});
|
||
}
|
||
};
|
||
|
||
//if (BindingContext is LoginViewModel vm) {
|
||
// vm.AlertEvent += Vm_AlertEvent;
|
||
// vm.InfoEvent += Vm_InfoEvent;
|
||
// vm.MsgEvent += Vm_MsgEvent;
|
||
//}
|
||
|
||
//Zwischen manuellem und automatischem Login (mit QR-Code) umschalten und die Schalterstellung merken
|
||
// MVVM übernimmt Umschalten über IsManualMode im ViewModel; keine Code-Behind-Umschaltung mehr
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// Nach der Erkennung des Barcodes wird der Benutzer eingeloggt
|
||
/// ZXing.Net.Maui.Controls 0.4.4
|
||
/// </summary>
|
||
private void BarcodesDetected(object sender, BarcodeDetectionEventArgs e) {
|
||
var currentTime = DateTime.Now;
|
||
if ((currentTime - _lastDetectionTime) > _detectionInterval) {
|
||
_lastDetectionTime = currentTime;
|
||
foreach (var barcode in e.Results) {
|
||
if (GlobalVar.ApiKey != barcode.Value) {
|
||
_ = MainThread.InvokeOnMainThreadAsync(async () => {
|
||
//await DisplayAlert("Barcode erkannt", $"Barcode: {barcode.Format} - {barcode.Value}", "OK");
|
||
|
||
try {
|
||
var tokendata = new TokenData(barcode.Value);
|
||
GlobalVar.ApiUrl = tokendata.Url;
|
||
User user = await HoursBase.LoadUser(barcode.Value);
|
||
|
||
GlobalVar.ApiKey = barcode.Value;
|
||
GlobalVar.Name = user.Name;
|
||
GlobalVar.Surname = user.Surname;
|
||
GlobalVar.EmployeeId = user.Id;
|
||
|
||
Title = user.Name + " " + user.Surname;
|
||
//Auf der Loginseite wird der Server als Info ohne Protokoll und ohne /appapi angezeigt
|
||
ServerLabel.Text = "Server: " + tokendata.Url.Replace("/appapi", "").Replace("https://", "")
|
||
.Replace("http://", "");
|
||
|
||
|
||
await DisplayAlert("Login erfolgreich", user.Name + " " + user.Surname, "OK");
|
||
if (Navigation.NavigationStack.Count > 1) {
|
||
//Beim ersten Start ohne Login, wird man automatisch auf die Loginseite geleitet. Danach in der History zur<75>ck
|
||
await Navigation.PopAsync();
|
||
} else {
|
||
//Beim manuellen Wechsel auf die Loginseite leiten wir nach erfolgreichem Login auf die Stunden<65>bersicht
|
||
await Shell.Current.GoToAsync($"//StundenPage");
|
||
}
|
||
} catch (Exception e) {
|
||
await DisplayAlert("Fehler", e.Message, "OK");
|
||
}
|
||
});
|
||
} else {
|
||
MainThread.InvokeOnMainThreadAsync(() => {
|
||
DisplayAlert("Bereits eingeloggt",
|
||
Preferences.Default.Get("name", "") + " " + Preferences.Default.Get("surname", ""),
|
||
"OK");
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
protected override void OnDisappearing() {
|
||
base.OnDisappearing();
|
||
|
||
barcodeScannerView.CameraLocation = CameraLocation.Front;
|
||
// IsDetecting wird via Binding vom ViewModel gesteuert
|
||
}
|
||
|
||
protected override void OnAppearing() {
|
||
base.OnAppearing();
|
||
|
||
// IsDetecting wird via Binding vom ViewModel gesteuert
|
||
barcodeScannerView.CameraLocation = CameraLocation.Rear;
|
||
}
|
||
|
||
public bool IsCameraAvailable() {
|
||
var status = Permissions.CheckStatusAsync<Permissions.Camera>().Result;
|
||
if (status != PermissionStatus.Granted) {
|
||
status = Permissions.RequestAsync<Permissions.Camera>().Result;
|
||
}
|
||
|
||
return status != PermissionStatus.Granted;
|
||
}
|
||
|
||
private async void OnLoginButtonClicked(object sender, EventArgs e) {
|
||
var username = UsernameEntry.Text;
|
||
var password = PasswordEntry.Text;
|
||
var server = ServerEntry.Text;
|
||
|
||
|
||
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(server)) {
|
||
await DisplayAlert("Fehler", "Bitte alle Felder ausf<73>llen", "OK");
|
||
return;
|
||
}
|
||
|
||
try {
|
||
Uri uri = new Uri(InputUrlWithSchema(server));
|
||
|
||
Types.User response =
|
||
await BaseFunc.AuthUserPass(username, password, uri.Scheme + "://" + uri.Authority + "/appapi");
|
||
|
||
GlobalVar.ApiKey = response.Token;
|
||
GlobalVar.Name = response.Name;
|
||
GlobalVar.Surname = response.Surname;
|
||
GlobalVar.EmployeeId = response.Id;
|
||
GlobalVar.ApiUrl = uri.Scheme + "://" + uri.Authority + "/appapi";
|
||
|
||
Title = response.Name + " " + response.Surname;
|
||
//ServerLabel.Text = "Server: " + server.Replace("/appapi", "").Replace("https://", "").Replace("http://", "");
|
||
ServerLabel.Text = "Server: " + uri.Authority;
|
||
|
||
await DisplayAlert("Login erfolgreich", response.Name + " " + response.Surname, "OK");
|
||
if (Navigation.NavigationStack.Count > 1)
|
||
await Navigation.PopAsync();
|
||
else {
|
||
await Shell.Current.GoToAsync($"//StundenPage");
|
||
}
|
||
} catch (Exception ex) {
|
||
await DisplayAlert("Fehler", ex.Message, "OK");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Aus einer URL ohne Schema eine URL mit Schema machen
|
||
/// </summary>
|
||
private static string InputUrlWithSchema(string url) {
|
||
if (!url.StartsWith("http://") && !url.StartsWith("https://")) {
|
||
url = "https://" + url;
|
||
}
|
||
|
||
if (url.StartsWith("http://")) {
|
||
url = url.Replace("http://", "https://");
|
||
}
|
||
|
||
return url;
|
||
}
|
||
|
||
//Zwischen manuellem und automatischem Login (mit QR-Code) umschalten und die Schalterstellung merken
|
||
// Umschalt-Logik erfolgt über Binding an IsManualMode im ViewModel
|
||
|
||
//private void Vm_AlertEvent(object? sender, string e) {
|
||
// DisplayAlert("Fehler:", e, "OK");
|
||
//}
|
||
//private void Vm_InfoEvent(object? sender, string e) {
|
||
// DisplayAlert("Information:", e, "OK");
|
||
//}
|
||
//private async Task Vm_MsgEvent(string title, string message) {
|
||
// await DisplayAlert(title, message, "OK");
|
||
//}
|
||
} |