Changed Logger to accept string as caller

Added Logger to all relevant methods
This commit is contained in:
2023-05-20 22:10:24 +02:00
parent a367ebb230
commit d62b0bdf34
8 changed files with 100 additions and 62 deletions

View File

@ -1,6 +1,7 @@
using System.IO.Compression;
using System.Net;
using System.Xml.Linq;
using Logging;
namespace Tranga;
@ -13,10 +14,13 @@ public abstract class Connector
internal string downloadLocation { get; } //Location of local files
protected DownloadClient downloadClient { get; }
protected Connector(string downloadLocation, uint downloadDelay)
protected Logger? logger;
protected Connector(string downloadLocation, uint downloadDelay, Logger? logger)
{
this.downloadLocation = downloadLocation;
this.downloadClient = new DownloadClient(downloadDelay);
this.logger = logger;
}
public abstract string name { get; } //Name of the Connector (e.g. Website)
@ -58,6 +62,7 @@ public abstract class Connector
/// <param name="publication">Publication to save series.json for</param>
public void SaveSeriesInfo(Publication publication)
{
logger?.WriteLine(this.GetType().ToString(), $"Saving series.json for {publication.sortName}");
//Check if Publication already has a Folder and a series.json
string publicationFolder = Path.Join(downloadLocation, publication.folderName);
if(!Directory.Exists(publicationFolder))
@ -73,8 +78,9 @@ public abstract class Connector
/// See ComicInfo.xml
/// </summary>
/// <returns>XML-string</returns>
protected static string CreateComicInfo(Publication publication, Chapter chapter)
protected static string CreateComicInfo(Publication publication, Chapter chapter, Logger? logger)
{
logger?.WriteLine("Connector", $"Creating ComicInfo.Xml for {publication.sortName} Chapter {chapter.sortNumber}");
XElement comicInfo = new XElement("ComicInfo",
new XElement("Tags", string.Join(',',publication.tags)),
new XElement("LanguageISO", publication.originalLanguage),
@ -124,8 +130,9 @@ public abstract class Connector
/// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param>
/// <param name="downloadClient">DownloadClient of the connector</param>
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
protected static void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, DownloadClient downloadClient, string? comicInfoPath = null)
protected static void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, DownloadClient downloadClient, Logger? logger, string? comicInfoPath = null)
{
logger?.WriteLine("Connector", "Downloading Images");
//Check if Publication Directory already exists
string[] splitPath = saveArchiveFilePath.Split(Path.DirectorySeparatorChar);
string directoryPath = Path.Combine(splitPath.Take(splitPath.Length - 1).ToArray());
@ -151,6 +158,7 @@ public abstract class Connector
if(comicInfoPath is not null)
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
logger?.WriteLine("Connector", "Creating archive");
//ZIP-it and ship-it
ZipFile.CreateFromDirectory(tempFolder, fullPath);
Directory.Delete(tempFolder, true); //Cleanup

View File

@ -2,24 +2,26 @@
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using Logging;
namespace Tranga.Connectors;
public class MangaDex : Connector
{
public override string name { get; }
public MangaDex(string downloadLocation, uint downloadDelay) : base(downloadLocation, downloadDelay)
public MangaDex(string downloadLocation, uint downloadDelay, Logger? logger) : base(downloadLocation, downloadDelay, logger)
{
name = "MangaDex";
}
public MangaDex(string downloadLocation) : base(downloadLocation, 750)
public MangaDex(string downloadLocation, Logger? logger) : base(downloadLocation, 750, logger)
{
name = "MangaDex";
}
public override Publication[] GetPublications(string publicationTitle = "")
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications");
const int limit = 100; //How many values we want returned at once
int offset = 0; //"Page"
int total = int.MaxValue; //How many total results are there, is updated on first request
@ -126,6 +128,7 @@ public class MangaDex : Connector
public override Chapter[] GetChapters(Publication publication, string language = "")
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters");
const int limit = 100; //How many values we want returned at once
int offset = 0; //"Page"
int total = int.MaxValue; //How many total results are there, is updated on first request
@ -180,6 +183,7 @@ public class MangaDex : Connector
public override void DownloadChapter(Publication publication, Chapter chapter)
{
logger?.WriteLine(this.GetType().ToString(), $"Download Chapter {publication.sortName} {chapter.sortNumber}");
//Request URLs for Chapter-Images
DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'");
@ -198,14 +202,15 @@ public class MangaDex : Connector
imageUrls.Add($"{baseUrl}/data/{hash}/{image!.GetValue<string>()}");
string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, CreateComicInfo(publication, chapter));
File.WriteAllText(comicInfoPath, CreateComicInfo(publication, chapter, logger));
//Download Chapter-Images
DownloadChapterImages(imageUrls.ToArray(), CreateFullFilepath(publication, chapter), downloadClient, comicInfoPath);
DownloadChapterImages(imageUrls.ToArray(), CreateFullFilepath(publication, chapter), downloadClient, logger, comicInfoPath);
}
public override void DownloadCover(Publication publication)
{
logger?.WriteLine(this.GetType().ToString(), $"Download cover {publication.sortName}");
//Check if Publication already has a Folder and cover
string publicationFolder = Path.Join(downloadLocation, publication.folderName);
if(!Directory.Exists(publicationFolder))

View File

@ -1,5 +1,6 @@
using System.Net.Http.Headers;
using System.Text.Json.Nodes;
using Logging;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
@ -13,23 +14,27 @@ 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;
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
/// <param name="username">Komga Username</param>
/// <param name="password">Komga password, will be base64 encoded. yea</param>
public Komga(string baseUrl, string username, string password)
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;
}
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
/// <param name="auth">Base64 string of username and password (username):(password)</param>
[JsonConstructor]
public Komga(string baseUrl, string auth)
public Komga(string baseUrl, string auth, Logger? logger)
{
this.baseUrl = baseUrl;
this.auth = auth;
this.logger = logger;
}
/// <summary>
@ -38,6 +43,7 @@ public class Komga
/// <returns>Array of KomgaLibraries</returns>
public KomgaLibrary[] GetLibraries()
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries");
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth);
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
if (result is null)
@ -63,6 +69,7 @@ public class Komga
/// <returns>true if successful</returns>
public bool UpdateLibrary(string libraryId)
{
logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries");
return NetClient.MakePost($"{baseUrl}/api/v1/libraries/{libraryId}/scan", auth);
}

View File

@ -1,4 +1,6 @@
namespace Tranga;
using Logging;
namespace Tranga;
/// <summary>
/// Executes TrangaTasks
@ -14,12 +16,16 @@ public static class TaskExecutor
/// <param name="trangaTask">Task to execute</param>
/// <param name="chapterCollection">Current chapterCollection to update</param>
/// <exception cref="ArgumentException">Is thrown when there is no Connector available with the name of the TrangaTask.connectorName</exception>
public static void Execute(TaskManager taskManager, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection)
public static void Execute(TaskManager taskManager, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection, Logger? logger)
{
//Only execute task if it is not already being executed.
if (trangaTask.state == TrangaTask.ExecutionState.Running)
{
logger?.WriteLine("TaskExecutor", $"Task already running {trangaTask}");
return;
}
trangaTask.state = TrangaTask.ExecutionState.Running;
logger?.WriteLine("TaskExecutor", $"Executing Task {trangaTask}");
//Connector is not needed for all tasks
Connector? connector = null;
@ -42,7 +48,8 @@ public static class TaskExecutor
UpdateKomgaLibrary(taskManager);
break;
}
logger?.WriteLine("TaskExecutor", $"Task executed! {trangaTask}");
trangaTask.state = TrangaTask.ExecutionState.Waiting;
trangaTask.lastExecuted = DateTime.Now;
}

View File

@ -1,4 +1,5 @@
using Newtonsoft.Json;
using Logging;
using Newtonsoft.Json;
using Tranga.Connectors;
namespace Tranga;
@ -15,20 +16,23 @@ public class TaskManager
private readonly Connector[] _connectors;
private Dictionary<Connector, List<TrangaTask>> tasksToExecute = new();
private string downloadLocation { get; }
private Logger? logger { get; }
public Komga? komga { get; private set; }
public Komga? komga { get; }
/// <param name="folderPath">Local path to save data (Manga) to</param>
/// <param name="komgaBaseUrl">The Url of the Komga-instance that you want to update</param>
/// <param name="komgaUsername">The Komga username</param>
/// <param name="komgaPassword">The Komga password</param>
public TaskManager(string folderPath, string? komgaBaseUrl = null, string? komgaUsername = null, string? komgaPassword = null)
/// <param name="logger"></param>
public TaskManager(string folderPath, string? komgaBaseUrl = null, string? komgaUsername = null, string? komgaPassword = null, Logger? logger = null)
{
this.logger = logger;
this.downloadLocation = folderPath;
if (komgaBaseUrl != null && komgaUsername != null && komgaPassword != null)
this.komga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword);
this._connectors = new Connector[]{ new MangaDex(folderPath) };
this.komga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword, logger);
this._connectors = new Connector[]{ new MangaDex(folderPath, logger) };
foreach(Connector cConnector in this._connectors)
tasksToExecute.Add(cConnector, new List<TrangaTask>());
_allTasks = new HashSet<TrangaTask>();
@ -37,9 +41,10 @@ public class TaskManager
taskChecker.Start();
}
public TaskManager(SettingsData settings)
public TaskManager(SettingsData settings, Logger? logger = null)
{
this._connectors = new Connector[]{ new MangaDex(settings.downloadLocation) };
this.logger = logger;
this._connectors = new Connector[]{ new MangaDex(settings.downloadLocation, logger) };
foreach(Connector cConnector in this._connectors)
tasksToExecute.Add(cConnector, new List<TrangaTask>());
this.downloadLocation = settings.downloadLocation;
@ -74,6 +79,7 @@ public class TaskManager
ExecuteTaskNow(task);
else
{
logger?.WriteLine(this.GetType().ToString(), $"Task due: {task}");
tasksToExecute[GetConnector(task.connectorName!)].Add(task);
}
}
@ -90,9 +96,10 @@ public class TaskManager
if (!this._allTasks.Contains(task))
return;
logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}");
Task t = new Task(() =>
{
TaskExecutor.Execute(this, task, this._chapterCollection);
TaskExecutor.Execute(this, task, this._chapterCollection, logger);
});
t.Start();
}
@ -109,6 +116,7 @@ public class TaskManager
public TrangaTask AddTask(TrangaTask.Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence,
string language = "")
{
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task");
if (task != TrangaTask.Task.UpdateKomgaLibrary && connectorName is null)
throw new ArgumentException($"connectorName can not be null for task {task}");
@ -142,6 +150,7 @@ public class TaskManager
_allTasks.Add(newTask);
}
}
logger?.WriteLine(this.GetType().ToString(), newTask.ToString());
ExportData(Directory.GetCurrentDirectory());
return newTask;
@ -155,6 +164,7 @@ public class TaskManager
/// <param name="publication">Publication that was used</param>
public void RemoveTask(TrangaTask.Task task, string? connectorName, Publication? publication)
{
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {task}");
if (task == TrangaTask.Task.UpdateKomgaLibrary)
_allTasks.RemoveWhere(uTask => uTask.task == TrangaTask.Task.UpdateKomgaLibrary);
else if (connectorName is null)
@ -207,6 +217,7 @@ public class TaskManager
/// <param name="force">If force is true, tasks are aborted.</param>
public void Shutdown(bool force = false)
{
logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
_continueRunning = false;
ExportData(Directory.GetCurrentDirectory());
@ -241,6 +252,7 @@ public class TaskManager
/// <param name="exportFolderPath">Folder path, filename will be data.json</param>
private void ExportData(string exportFolderPath)
{
logger?.WriteLine(this.GetType().ToString(), $"Exporting data to data.json");
SettingsData data = new SettingsData(this.downloadLocation, this.komga, this._allTasks);
string exportPath = Path.Join(exportFolderPath, "data.json");