using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Diagnostics; using System.Net; using Pilz.Networking.CloudProviders.Nextcloud.OCS.APIs; namespace Pilz.Networking.CloudProviders.Nextcloud.OCS { public class OcsApi : IDisposable { public event GetOcsApiAuthCredentailsEventHandler? GetOcsApiAuthCredentails; private readonly HttpClient client = new(); public string BaseUrl { get; set; } = string.Empty; public OcsApiLoginFlowV2 LoginFlowV2 { get; init; } public OcsApiCore Core { get; init; } public OcsApiCloud Cloud { get; init; } public OcsApi() { LoginFlowV2 = new(this); Core = new(this); Cloud = new(this); } public string BuildFullUrl(OcsApiUrlPath path) { return BaseUrl + path; } public Task MakeRequestJson(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null) { return MakeRequestJson(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters); } public Task MakeRequest(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null) { return MakeRequest(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters); } public async Task MakeRequestJson(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null) { using var responseInit = await MakeRequest(httpMethod, url, useAuthentication: useAuthentication, parameters: parameters); if (responseInit != null) { var bodyInit = await responseInit.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(bodyInit); } return default; } public async Task MakeRequest(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null) { OcsApiAuthCredentials? authentication; string @params; // Get authentication if (useAuthentication) { var args = new GetOcsApiAuthCredentailsEventArgs(); GetOcsApiAuthCredentails?.Invoke(this, args); authentication = args.Credentials; } else authentication = null; // Parse params if (parameters != null) @params = "?" + string.Join(",", parameters.Select(p => $"{p.Key}={p.Value}")); else @params = string.Empty; // Send request var request = new HttpRequestMessage { Method = httpMethod ?? HttpMethod.Post, RequestUri = new Uri(url + @params), Headers = { { "Accept", "application/json" }, { "OCS-APIREQUEST", "true" }, { "Authorization", authentication.ToBasicAuth() } }, }; return await client.SendAsync(request); } public void Dispose() { client.Dispose(); GC.SuppressFinalize(this); } } }