From 0c580933f956bed5b28a8083c32b43aeb2a7b38d Mon Sep 17 00:00:00 2001 From: glax Date: Sat, 3 Jun 2023 15:02:15 +0200 Subject: [PATCH] #33 Preparation: Abstracted class Komga into LibraryManager Fixed logger not attaching to LibraryManager --- Tranga-API/Program.cs | 2 +- Tranga-CLI/Tranga_Cli.cs | 5 +- Tranga/Komga.cs | 148 ------------------- Tranga/LibraryManager.cs | 82 ++++++++++ Tranga/LibraryManagers/Komga.cs | 75 ++++++++++ Tranga/TaskManager.cs | 3 +- Tranga/TrangaSettings.cs | 8 +- Tranga/TrangaTasks/UpdateKomgaLibraryTask.cs | 8 +- 8 files changed, 170 insertions(+), 161 deletions(-) delete mode 100644 Tranga/Komga.cs create mode 100644 Tranga/LibraryManager.cs create mode 100644 Tranga/LibraryManagers/Komga.cs diff --git a/Tranga-API/Program.cs b/Tranga-API/Program.cs index b9fd9a9..d6c9ba6 100644 --- a/Tranga-API/Program.cs +++ b/Tranga-API/Program.cs @@ -15,7 +15,7 @@ logger.WriteLine("Tranga", "Loading settings."); TrangaSettings settings; if (File.Exists(settingsFilePath)) - settings = TrangaSettings.LoadSettings(settingsFilePath); + settings = TrangaSettings.LoadSettings(settingsFilePath, logger); else settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, null); diff --git a/Tranga-CLI/Tranga_Cli.cs b/Tranga-CLI/Tranga_Cli.cs index a8509f5..d8d654d 100644 --- a/Tranga-CLI/Tranga_Cli.cs +++ b/Tranga-CLI/Tranga_Cli.cs @@ -1,6 +1,7 @@ using System.Globalization; using Logging; using Tranga; +using Tranga.LibraryManagers; namespace Tranga_CLI; @@ -25,10 +26,10 @@ public static class Tranga_Cli Console.WriteLine($"Logfile-Path: {logFilePath}"); Console.WriteLine($"Settings-File-Path: {settingsFilePath}"); - Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, null, logFilePath); + Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, Console.Out.Encoding, logFilePath); logger.WriteLine("Tranga_CLI", "Loading Taskmanager."); - TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, null); + TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, null); logger.WriteLine("Tranga_CLI", "User Input"); diff --git a/Tranga/Komga.cs b/Tranga/Komga.cs deleted file mode 100644 index 6af7d9d..0000000 --- a/Tranga/Komga.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; -using System.Text.Json.Nodes; -using Logging; -using Newtonsoft.Json; -using JsonSerializer = System.Text.Json.JsonSerializer; - -namespace Tranga; - -/// -/// Provides connectivity to Komga-API -/// Can fetch and update libraries -/// -public class Komga -{ - public string baseUrl { get; } - public string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems - - private Logger? logger; - - /// Base-URL of Komga instance, no trailing slashes(/) - /// Komga Username - /// Komga password, will be base64 encoded. yea - public Komga(string baseUrl, string username, string password, Logger? logger) - { - this.baseUrl = baseUrl; - this.auth = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")); - this.logger = logger; - } - - /// Base-URL of Komga instance, no trailing slashes(/) - /// Base64 string of username and password (username):(password) - [JsonConstructor] - public Komga(string baseUrl, string auth, Logger? logger) - { - this.baseUrl = baseUrl; - this.auth = auth; - this.logger = logger; - } - - /// - /// Fetches all libraries available to the user - /// - /// Array of KomgaLibraries - public KomgaLibrary[] GetLibraries() - { - logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries"); - Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth); - if (data == Stream.Null) - { - logger?.WriteLine(this.GetType().ToString(), $"No libraries returned"); - return Array.Empty(); - } - JsonArray? result = JsonSerializer.Deserialize(data); - if (result is null) - { - logger?.WriteLine(this.GetType().ToString(), $"No libraries returned"); - return Array.Empty(); - } - - HashSet ret = new(); - - foreach (JsonNode? jsonNode in result) - { - var jObject = (JsonObject?)jsonNode; - string libraryId = jObject!["id"]!.GetValue(); - string libraryName = jObject!["name"]!.GetValue(); - ret.Add(new KomgaLibrary(libraryId, libraryName)); - } - - return ret.ToArray(); - } - - /// - /// Updates library with given id - /// - /// Id of the Komga-Library - /// true if successful - public bool UpdateLibrary(string libraryId) - { - logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries"); - return NetClient.MakePost($"{baseUrl}/api/v1/libraries/{libraryId}/scan", auth); - } - - public struct KomgaLibrary - { - public string id { get; } - public string name { get; } - - public KomgaLibrary(string id, string name) - { - this.id = id; - this.name = name; - } - } - - private static class NetClient - { - public static Stream MakeRequest(string url, string auth) - { - HttpClientHandler clientHandler = new (); - clientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true; - HttpClient client = new(clientHandler); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth); - - HttpRequestMessage requestMessage = new () - { - Method = HttpMethod.Get, - RequestUri = new Uri(url) - }; - HttpResponseMessage response = client.Send(requestMessage); - Stream ret; - if (response.StatusCode is HttpStatusCode.Unauthorized) - { - ret = MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, auth); - }else - return response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null; - return ret; - } - - public static bool MakePost(string url, string auth) - { - HttpClientHandler clientHandler = new HttpClientHandler(); - clientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true; - HttpClient client = new(clientHandler) - { - DefaultRequestHeaders = - { - { "Accept", "application/json" }, - { "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() } - } - }; - HttpRequestMessage requestMessage = new HttpRequestMessage - { - Method = HttpMethod.Post, - RequestUri = new Uri(url) - }; - HttpResponseMessage response = client.Send(requestMessage); - bool ret; - if (response.StatusCode is HttpStatusCode.Unauthorized) - { - ret = MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, auth); - }else - return response.IsSuccessStatusCode; - return ret; - } - } -} \ No newline at end of file diff --git a/Tranga/LibraryManager.cs b/Tranga/LibraryManager.cs new file mode 100644 index 0000000..8ddef3d --- /dev/null +++ b/Tranga/LibraryManager.cs @@ -0,0 +1,82 @@ +using System.Net; +using System.Net.Http.Headers; +using Logging; + +namespace Tranga; + +public abstract class LibraryManager +{ + public string baseUrl { get; } + protected string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems + protected Logger? logger; + + /// Base-URL of Komga instance, no trailing slashes(/) + /// Base64 string of username and password (username):(password) + /// + protected LibraryManager(string baseUrl, string auth, Logger? logger) + { + this.baseUrl = baseUrl; + this.auth = auth; + this.logger = logger; + } + public abstract void UpdateLibrary(); + + public void AddLogger(Logger newLogger) + { + this.logger = newLogger; + } + + protected static class NetClient + { + public static Stream MakeRequest(string url, string auth, Logger? logger) + { + HttpClientHandler clientHandler = new (); + HttpClient client = new(clientHandler); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth); + + HttpRequestMessage requestMessage = new () + { + Method = HttpMethod.Get, + RequestUri = new Uri(url) + }; + logger?.WriteLine("LibraryManager", $"GET {url}"); + HttpResponseMessage response = client.Send(requestMessage); + logger?.WriteLine("LibraryManager", $"{(int)response.StatusCode} {response.StatusCode}: {response.ReasonPhrase}"); + + if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url) + return MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, auth, logger); + else if (response.IsSuccessStatusCode) + return response.Content.ReadAsStream(); + else + return Stream.Null; + } + + public static bool MakePost(string url, string auth, Logger? logger) + { + HttpClientHandler clientHandler = new (); + HttpClient client = new(clientHandler) + { + DefaultRequestHeaders = + { + { "Accept", "application/json" }, + { "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() } + } + }; + HttpRequestMessage requestMessage = new () + { + Method = HttpMethod.Post, + RequestUri = new Uri(url) + }; + logger?.WriteLine("LibraryManager", $"POST {url}"); + HttpResponseMessage response = client.Send(requestMessage); + logger?.WriteLine("LibraryManager", $"{(int)response.StatusCode} {response.StatusCode}: {response.ReasonPhrase}"); + + if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url) + return MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, auth, logger); + else if (response.IsSuccessStatusCode) + return true; + else + return false; + } + } +} \ No newline at end of file diff --git a/Tranga/LibraryManagers/Komga.cs b/Tranga/LibraryManagers/Komga.cs new file mode 100644 index 0000000..87b24b8 --- /dev/null +++ b/Tranga/LibraryManagers/Komga.cs @@ -0,0 +1,75 @@ +using System.Text.Json.Nodes; +using Logging; +using Newtonsoft.Json; +using JsonSerializer = System.Text.Json.JsonSerializer; + +namespace Tranga.LibraryManagers; + +/// +/// Provides connectivity to Komga-API +/// Can fetch and update libraries +/// +public class Komga : LibraryManager +{ + public Komga(string baseUrl, string username, string password, Logger? logger) + : base(baseUrl, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")), logger) + { + } + + [JsonConstructor] + public Komga(string baseUrl, string auth, Logger? logger) : base(baseUrl, auth, logger) + { + } + + public override void UpdateLibrary() + { + logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries"); + foreach (KomgaLibrary lib in GetLibraries()) + NetClient.MakePost($"{baseUrl}/api/v1/libraries/{lib.id}/scan", auth, logger); + } + + /// + /// Fetches all libraries available to the user + /// + /// Array of KomgaLibraries + private IEnumerable GetLibraries() + { + logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries"); + Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth, logger); + if (data == Stream.Null) + { + logger?.WriteLine(this.GetType().ToString(), $"No libraries returned"); + return Array.Empty(); + } + JsonArray? result = JsonSerializer.Deserialize(data); + if (result is null) + { + logger?.WriteLine(this.GetType().ToString(), $"No libraries returned"); + return Array.Empty(); + } + + HashSet ret = new(); + + foreach (JsonNode? jsonNode in result) + { + var jObject = (JsonObject?)jsonNode; + string libraryId = jObject!["id"]!.GetValue(); + string libraryName = jObject!["name"]!.GetValue(); + ret.Add(new KomgaLibrary(libraryId, libraryName)); + } + + return ret; + } + + private struct KomgaLibrary + { + public string id { get; } + public string name { get; } + + public KomgaLibrary(string id, string name) + { + this.id = id; + this.name = name; + } + } +} \ No newline at end of file diff --git a/Tranga/TaskManager.cs b/Tranga/TaskManager.cs index 705062e..ecdcec5 100644 --- a/Tranga/TaskManager.cs +++ b/Tranga/TaskManager.cs @@ -1,6 +1,7 @@ using Logging; using Newtonsoft.Json; using Tranga.Connectors; +using Tranga.LibraryManagers; using Tranga.TrangaTasks; namespace Tranga; @@ -54,7 +55,7 @@ public class TaskManager public void UpdateSettings(string? downloadLocation, string? komgaUrl, string? komgaAuth) { if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 0 && komgaAuth.Length > 0) - settings.komga = new Komga(komgaUrl, komgaAuth, null); + settings.komga = new Komga(komgaUrl, komgaAuth, logger); if (downloadLocation is not null && downloadLocation.Length > 0) settings.downloadLocation = downloadLocation; ExportDataAndSettings(); diff --git a/Tranga/TrangaSettings.cs b/Tranga/TrangaSettings.cs index ca2acd3..b916a57 100644 --- a/Tranga/TrangaSettings.cs +++ b/Tranga/TrangaSettings.cs @@ -1,4 +1,6 @@ -using Newtonsoft.Json; +using Logging; +using Newtonsoft.Json; +using Tranga.LibraryManagers; namespace Tranga; @@ -21,13 +23,15 @@ public class TrangaSettings this.komga = komga; } - public static TrangaSettings LoadSettings(string importFilePath) + public static TrangaSettings LoadSettings(string importFilePath, Logger? logger) { if (!File.Exists(importFilePath)) return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory(), null); string toRead = File.ReadAllText(importFilePath); TrangaSettings settings = JsonConvert.DeserializeObject(toRead)!; + if(settings.komga is not null && logger is not null) + settings.komga.AddLogger(logger); return settings; } diff --git a/Tranga/TrangaTasks/UpdateKomgaLibraryTask.cs b/Tranga/TrangaTasks/UpdateKomgaLibraryTask.cs index af076fb..c6acacf 100644 --- a/Tranga/TrangaTasks/UpdateKomgaLibraryTask.cs +++ b/Tranga/TrangaTasks/UpdateKomgaLibraryTask.cs @@ -10,12 +10,6 @@ public class UpdateKomgaLibraryTask : TrangaTask protected override void ExecuteTask(TaskManager taskManager, Logger? logger) { - if (taskManager.komga is null) - return; - Komga komga = taskManager.komga; - - Komga.KomgaLibrary[] allLibraries = komga.GetLibraries(); - foreach (Komga.KomgaLibrary lib in allLibraries) - komga.UpdateLibrary(lib.id); + taskManager.komga?.UpdateLibrary(); } } \ No newline at end of file