using Jugenddienst_Stunden.Types; using Newtonsoft.Json; using System.Text; using System.Text.Json; namespace Jugenddienst_Stunden.Models; internal static class BaseFunc { internal static async Task GetApiDataWithAuthAsync(string url, string token) { if (Connectivity.Current.NetworkAccess == NetworkAccess.None) throw new Exception("Bitte überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut."); if (string.IsNullOrEmpty(token)) throw new Exception("Kein APIKEY, bitte zuerst Login durchführen"); // Erstellen eines HttpClient-Objekts using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) { client.DefaultRequestHeaders.Add("Accept", "application/json"); // Hinzufügen des Bearer-Tokens zum Authorization-Header client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); // Senden der Anfrage und Abrufen der Antwort using (HttpResponseMessage HttpResponseMessage = await client.GetAsync(url).ConfigureAwait(false)) { var byteArray = await HttpResponseMessage.Content.ReadAsByteArrayAsync(); string responseData = Encoding.UTF8.GetString(byteArray); using (HttpContent HttpContent = HttpResponseMessage.Content) { //responseData = await HttpContent.ReadAsStringAsync(); } if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK) { return responseData; } else { var options = new JsonDocumentOptions { AllowTrailingCommas = true }; using (JsonDocument doc = JsonDocument.Parse(responseData, options)) { JsonElement root = doc.RootElement; string message = root.GetProperty("message").GetString() ?? throw new Exception("Fehler: 'message' ist null."); throw new Exception(message); } } } } } internal static async Task AuthUserPass(string user, string pass, string url) { var values = new Dictionary { { "user", user }, { "pass", pass } }; var content = new FormUrlEncodedContent(values); using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) { client.DefaultRequestHeaders.Add("Accept", "application/json"); // Senden der Anfrage und Abrufen der Antwort using (HttpResponseMessage HttpResponseMessage = await client.PostAsync(url, content).ConfigureAwait(false)) { if (!HttpResponseMessage.IsSuccessStatusCode) { //throw new Exception("Fehler beim Einloggen " + HttpResponseMessage.Content); var byteArray = await HttpResponseMessage.Content.ReadAsByteArrayAsync(); string responseData = Encoding.UTF8.GetString(byteArray); var options = new JsonDocumentOptions { AllowTrailingCommas = true }; using (JsonDocument doc = JsonDocument.Parse(responseData, options)) { JsonElement root = doc.RootElement; string message = root.GetProperty("message").GetString() ?? throw new Exception("Fehler: 'message' ist null."); throw new Exception(message); } } // Überprüfen, ob die Anfrage erfolgreich war if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK) { using (HttpContent HttpContent = HttpResponseMessage.Content) { // Lesen und Rückgabe der Antwort als String string responseData = await HttpContent.ReadAsStringAsync(); BaseResponse res = JsonConvert.DeserializeObject(responseData) ?? throw new Exception("Fehler beim Deserialisieren der Daten"); //User userData = System.Text.Json.JsonSerializer.Deserialize(responseData) ?? throw new Exception("Fehler beim Deserialisieren der Daten"); return res.user; } } } } return null; } internal static Note Load(string filename) { filename = System.IO.Path.Combine(FileSystem.AppDataDirectory, filename); if (!File.Exists(filename)) throw new FileNotFoundException("Unable to find file on local storage.", filename); return new() { Date = File.GetLastWriteTime(filename) }; } /// /// Stundeneintrag speichern /// internal static async Task SaveItemAsync(string url, string token, DayTime item, bool isNewItem = false) { //Uhrzeiten sollten sinnvolle Werte haben - außer bei Freistellungen, da wäre eigentlich null if (item.TimeSpanVon == item.TimeSpanBis && item.FreistellungAktiv == null) { throw new Exception("Beginn und Ende sind gleich"); } if (item.TimeSpanBis < item.TimeSpanVon) { throw new Exception("Ende ist vor Beginn"); } TimeSpan span = TimeSpan.Zero; span += item.TimeSpanBis - item.TimeSpanVon; if (span.Hours > 10) { //Hier vielleicht eine Abfrage, ob mehr als 10 Stunden gesund sind? //Das müsste aber das ViewModel machen } //Gemeinde ist ein Pflichtfeld if (item.GemeindeAktiv == null && GlobalVar.Settings.GemeindeAktivSet) { throw new Exception("Gemeinde nicht gewählt"); } //Projekt ist ein Pflichtfeld if (item.ProjektAktiv == null && GlobalVar.Settings.ProjektAktivSet) { throw new Exception("Projekt nicht gewählt"); } //Keine Beschreibung if (string.IsNullOrEmpty(item.Description) && item.FreistellungAktiv == null) { throw new Exception("Keine Beschreibung"); } //Keine Beschreibung if (string.IsNullOrEmpty(item.Description)) { item.Description = item.FreistellungAktiv.Name; } using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) { //HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); //string json = JsonSerializer.Serialize(item); string json = JsonConvert.SerializeObject(item); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage? response = null; if (isNewItem) response = await client.PostAsync(url, content); else response = await client.PutAsync(url, content); if (!response.IsSuccessStatusCode) { throw new Exception("Fehler beim Speichern " + response.Content); } } } internal static async Task DeleteItemAsync(string url, string token) { using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) { //HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await client.DeleteAsync(url); if (!response.IsSuccessStatusCode) throw new Exception("Fehler beim Löschen " + response.Content); } } }