Compare commits

..

9 Commits

Author SHA1 Message Date
d9b6062767 Custom JSON Deserializer for concrete classes of abstract class TrangaTask 2023-05-31 21:43:07 +02:00
d477cd1ccd corrected check for tasktype on due 2023-05-31 21:42:23 +02:00
f892db7dda Switch Execution State to Running when executing 2023-05-31 21:40:00 +02:00
16c1b5c506 Create imageCacheFolder 2023-05-31 21:39:18 +02:00
d5ecc1c37d Spelling, redundant calls 2023-05-31 21:18:41 +02:00
1b9ebd096b Removed TaskExecutor
TrangaTask is now abstract
TrangaTask implements Execute Method, that is now called instead of TaskExecutor
Created inheriting classes of TrangaTask: UpdateKomgaLibraryTask, DownloadNewChaptersTask
2023-05-31 21:15:32 +02:00
8619630269 Renamed ExportData to ExportDataAndSettings 2023-05-31 21:14:11 +02:00
2bc92556e3 Method description and Name CopyCoverFromCacheToDownloadLocation 2023-05-31 20:39:57 +02:00
f1ab823e7f Method description 2023-05-31 20:39:23 +02:00
7 changed files with 166 additions and 201 deletions

View File

@ -28,11 +28,7 @@ public static class Tranga_Cli
Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, null, logFilePath);
logger.WriteLine("Tranga_CLI", "Loading Taskmanager.");
TrangaSettings settings;
if (File.Exists(settingsFilePath))
settings = TrangaSettings.LoadSettings(settingsFilePath);
else
settings = new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, null);
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, null);
logger.WriteLine("Tranga_CLI", "User Input");
@ -85,7 +81,7 @@ public static class Tranga_Cli
{
TaskManager taskManager = new (settings, logger);
ConsoleKey selection = ConsoleKey.EraseEndOfFile;
PrintMenu(taskManager, taskManager.settings.downloadLocation, logger);
PrintMenu(taskManager, taskManager.settings.downloadLocation);
while (selection != ConsoleKey.Q)
{
int taskCount = taskManager.GetAllTasks().Length;
@ -106,7 +102,7 @@ public static class Tranga_Cli
Console.ReadKey();
break;
case ConsoleKey.C:
CreateTask(taskManager, taskManager.settings, logger);
CreateTask(taskManager, logger);
Console.WriteLine("Press any key.");
Console.ReadKey();
break;
@ -159,7 +155,7 @@ public static class Tranga_Cli
Console.ReadKey();
break;
}
PrintMenu(taskManager, taskManager.settings.downloadLocation, logger);
PrintMenu(taskManager, taskManager.settings.downloadLocation);
}
Thread.Sleep(200);
}
@ -179,7 +175,7 @@ public static class Tranga_Cli
taskManager.Shutdown(false);
}
private static void PrintMenu(TaskManager taskManager, string folderPath, Logger logger)
private static void PrintMenu(TaskManager taskManager, string folderPath)
{
int taskCount = taskManager.GetAllTasks().Length;
int taskRunningCount = taskManager.GetAllTasks().Count(task => task.state == TrangaTask.ExecutionState.Running);
@ -264,17 +260,17 @@ public static class Tranga_Cli
Console.Clear();
logger.WriteLine("Tranga_CLI", "Menu: Add Manga Download to queue");
Connector? connector = SelectConnector(taskManager.settings.downloadLocation, taskManager.GetAvailableConnectors().Values.ToArray(), logger);
Connector? connector = SelectConnector(taskManager.GetAvailableConnectors().Values.ToArray(), logger);
if (connector is null)
return;
Publication? publication = SelectPublication(taskManager, connector!, logger);
Publication? publication = SelectPublication(taskManager, connector, logger);
if (publication is null)
return;
TimeSpan reoccurrence = SelectReoccurrence(logger);
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
TrangaTask newTask = taskManager.AddTask(TrangaTask.Task.DownloadNewChapters, connector?.name, publication, reoccurrence, "en");
TrangaTask newTask = taskManager.AddTask(TrangaTask.Task.DownloadNewChapters, connector.name, publication, reoccurrence, "en");
Console.WriteLine(newTask);
}
@ -327,24 +323,24 @@ public static class Tranga_Cli
}
}
private static void CreateTask(TaskManager taskManager, TrangaSettings settings, Logger logger)
private static void CreateTask(TaskManager taskManager, Logger logger)
{
logger.WriteLine("Tranga_CLI", "Menu: Creating Task");
TrangaTask.Task? tmpTask = SelectTaskType(logger);
if (tmpTask is null)
return;
TrangaTask.Task task = (TrangaTask.Task)tmpTask!;
TrangaTask.Task task = (TrangaTask.Task)tmpTask;
Connector? connector = null;
if (task != TrangaTask.Task.UpdateKomgaLibrary)
{
connector = SelectConnector(settings.downloadLocation, taskManager.GetAvailableConnectors().Values.ToArray(), logger);
connector = SelectConnector(taskManager.GetAvailableConnectors().Values.ToArray(), logger);
if (connector is null)
return;
}
Publication? publication = null;
if (task != TrangaTask.Task.UpdatePublications && task != TrangaTask.Task.UpdateKomgaLibrary)
if (task != TrangaTask.Task.UpdateKomgaLibrary)
{
publication = SelectPublication(taskManager, connector!, logger);
if (publication is null)
@ -431,7 +427,7 @@ public static class Tranga_Cli
return TimeSpan.Parse(Console.ReadLine()!, new CultureInfo("en-US"));
}
private static Connector? SelectConnector(string folderPath, Connector[] connectors, Logger logger)
private static Connector? SelectConnector(Connector[] connectors, Logger logger)
{
logger.WriteLine("Tranga_CLI", "Menu: Select Connector");
Console.Clear();

View File

@ -27,6 +27,8 @@ public abstract class Connector
//RequestTypes for RateLimits
}, logger);
this.imageCachePath = imageCachePath;
if (!Directory.Exists(imageCachePath))
Directory.CreateDirectory(this.imageCachePath);
}
public abstract string name { get; } //Name of the Connector (e.g. Website)
@ -50,23 +52,22 @@ public abstract class Connector
/// <summary>
/// Retrieves the Chapter (+Images) from the website.
/// Should later call DownloadChapterImages to retrieve the individual Images of the Chapter.
/// Should later call DownloadChapterImages to retrieve the individual Images of the Chapter and create .cbz archive.
/// </summary>
/// <param name="publication">Publication that contains Chapter</param>
/// <param name="chapter">Chapter with Images to retrieve</param>
public abstract void DownloadChapter(Publication publication, Chapter chapter);
/// <summary>
/// Retrieves the Cover from the Website
/// Copies the already downloaded cover from cache to downloadLocation
/// </summary>
/// <param name="publication">Publication to retrieve Cover for</param>
/// <param name="settings">TrangaSettings</param>
public void CloneCoverFromCache(Publication publication, TrangaSettings settings)
public void CopyCoverFromCacheToDownloadLocation(Publication publication, TrangaSettings settings)
{
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName}");
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} {publication.internalId}");
//Check if Publication already has a Folder and cover
string publicationFolder = Path.Join(downloadLocation, publication.folderName);
if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder);
DirectoryInfo dirInfo = new (publicationFolder);
@ -124,7 +125,7 @@ public abstract class Connector
/// </summary>
/// <param name="imageUrl"></param>
/// <param name="fullPath"></param>
/// <param name="requestType">Requesttype for ratelimit</param>
/// <param name="requestType">RequestType for Rate-Limit</param>
private void DownloadImage(string imageUrl, string fullPath, byte requestType)
{
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType);
@ -184,8 +185,8 @@ public abstract class Connector
/// <summary>
/// Creates a httpClient
/// </summary>
/// <param name="delay">minimum delay between requests (to avoid spam)</param>
/// <param name="rateLimitRequestsPerMinute">Rate limits for requests. byte is RequestType, int maximum requests per minute for RequestType</param>
/// <param name="logger"></param>
public DownloadClient(Dictionary<byte, int> rateLimitRequestsPerMinute, Logger? logger)
{
this.logger = logger;

View File

@ -1,127 +0,0 @@
using Logging;
namespace Tranga;
/// <summary>
/// Executes TrangaTasks
/// Based on the TrangaTask.Task a method is called.
/// The chapterCollection is updated with new Publications/Chapters.
/// </summary>
public static class TaskExecutor
{
/// <summary>
/// Executes TrangaTask.
/// </summary>
/// <param name="taskManager">Parent</param>
/// <param name="trangaTask">Task to execute</param>
/// <param name="chapterCollection">Current chapterCollection to update</param>
/// <param name="logger"></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, 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", $"Starting Task {trangaTask}");
//Connector is not needed for all tasks
Connector? connector = null;
if (trangaTask.task != TrangaTask.Task.UpdateKomgaLibrary)
connector = taskManager.GetConnector(trangaTask.connectorName!);
//Call appropriate Method based on TrangaTask.Task
switch (trangaTask.task)
{
case TrangaTask.Task.DownloadNewChapters:
DownloadNewChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, ref taskManager._chapterCollection, taskManager.settings);
break;
case TrangaTask.Task.UpdateChapters:
UpdateChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, ref taskManager._chapterCollection);
break;
case TrangaTask.Task.UpdatePublications:
UpdatePublications(connector!, ref taskManager._chapterCollection);
break;
case TrangaTask.Task.UpdateKomgaLibrary:
UpdateKomgaLibrary(taskManager);
break;
}
logger?.WriteLine("TaskExecutor", $"Task finished! {trangaTask}");
trangaTask.lastExecuted = DateTime.Now;
trangaTask.state = TrangaTask.ExecutionState.Waiting;
}
/// <summary>
/// Updates all Komga-Libraries
/// </summary>
/// <param name="taskManager">Parent</param>
private static void UpdateKomgaLibrary(TaskManager taskManager)
{
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);
}
/// <summary>
/// Updates the available Publications from a Connector (all of them)
/// </summary>
/// <param name="connector">Connector to receive Publications from</param>
/// <param name="chapterCollection"></param>
private static void UpdatePublications(Connector connector, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{
Publication[] publications = connector.GetPublications();
foreach (Publication publication in publications)
chapterCollection.TryAdd(publication, new List<Chapter>());
}
/// <summary>
/// Checks for new Chapters and Downloads new ones.
/// If no Chapters had been downloaded previously, download also cover and create series.json
/// </summary>
/// <param name="connector">Connector to use</param>
/// <param name="publication">Publication to check</param>
/// <param name="language">Language to receive chapters for</param>
/// <param name="chapterCollection"></param>
private static void DownloadNewChapters(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection, TrangaSettings settings)
{
//Check if Publication already has a Folder
string publicationFolder = Path.Join(connector.downloadLocation, publication.folderName);
if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder);
List<Chapter> newChapters = UpdateChapters(connector, publication, language, ref chapterCollection);
connector.CloneCoverFromCache(publication, settings);
publication.SaveSeriesInfoJson(connector.downloadLocation);
foreach(Chapter newChapter in newChapters)
connector.DownloadChapter(publication, newChapter);
}
/// <summary>
/// Updates the available Chapters of a Publication
/// </summary>
/// <param name="connector">Connector to use</param>
/// <param name="publication">Publication to check</param>
/// <param name="language">Language to receive chapters for</param>
/// <param name="chapterCollection"></param>
/// <returns>List of Chapters that were previously not in collection</returns>
private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{
List<Chapter> newChaptersList = new();
chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection
Chapter[] newChapters = connector.GetChapters(publication, language);
newChaptersList = newChapters.Where(nChapter => !connector.CheckChapterIsDownloaded(publication, nChapter)).ToList();
return newChaptersList;
}
}

View File

@ -1,6 +1,7 @@
using Logging;
using Newtonsoft.Json;
using Tranga.Connectors;
using Tranga.TrangaTasks;
namespace Tranga;
@ -10,7 +11,7 @@ namespace Tranga;
/// </summary>
public class TaskManager
{
public Dictionary<Publication, List<Chapter>> _chapterCollection = new();
public Dictionary<Publication, List<Chapter>> chapterCollection = new();
private HashSet<TrangaTask> _allTasks;
private bool _continueRunning = true;
private readonly Connector[] _connectors;
@ -36,7 +37,7 @@ public class TaskManager
newKomga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword, logger);
this.settings = new TrangaSettings(downloadFolderPath, workingDirectory, newKomga);
ExportData();
ExportDataAndSettings();
this._connectors = new Connector[]{ new MangaDex(downloadFolderPath, imageCachePath, logger) };
foreach(Connector cConnector in this._connectors)
@ -52,7 +53,7 @@ public class TaskManager
settings.komga = new Komga(komgaUrl, komgaAuth, null);
if (downloadLocation is not null && downloadLocation.Length > 0)
settings.downloadLocation = downloadLocation;
ExportData();
ExportDataAndSettings();
}
public TaskManager(TrangaSettings settings, Logger? logger = null)
@ -65,7 +66,7 @@ public class TaskManager
this.settings = settings;
ImportData();
ExportData();
ExportDataAndSettings();
Thread taskChecker = new(TaskCheckerThread);
taskChecker.Start();
}
@ -83,7 +84,7 @@ public class TaskManager
foreach (KeyValuePair<Connector, List<TrangaTask>> connectorTaskQueue in _taskQueue)
{
if(connectorTaskQueue.Value.RemoveAll(task => task.state == TrangaTask.ExecutionState.Waiting) > 0)
ExportData();
ExportDataAndSettings();
if (connectorTaskQueue.Value.Count > 0 && connectorTaskQueue.Value.All(task => task.state is TrangaTask.ExecutionState.Enqueued))
ExecuteTaskNow(connectorTaskQueue.Value.First());
@ -94,7 +95,7 @@ public class TaskManager
foreach (TrangaTask task in _allTasks.Where(aTask => aTask.ShouldExecute()))
{
task.state = TrangaTask.ExecutionState.Enqueued;
if(task.connectorName is null)
if(task.task == TrangaTask.Task.UpdateKomgaLibrary)
ExecuteTaskNow(task);
else
{
@ -116,9 +117,9 @@ public class TaskManager
return;
logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}");
Task t = new Task(() =>
Task t = new(() =>
{
TaskExecutor.Execute(this, task, logger);
task.Execute(this);
});
t.Start();
}
@ -137,41 +138,41 @@ public class TaskManager
{
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {task} {connectorName} {publication?.sortName}");
TrangaTask newTask;
TrangaTask? newTask = null;
if (task == TrangaTask.Task.UpdateKomgaLibrary)
{
newTask = new TrangaTask(task, null, null, reoccurrence);
newTask = new UpdateKomgaLibraryTask(task, reoccurrence);
logger?.WriteLine(this.GetType().ToString(), $"Removing old {task}-Task.");
//Only one UpdateKomgaLibrary Task
_allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateKomgaLibrary);
_allTasks.Add(newTask);
}
else
logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask}");
}else if (task == TrangaTask.Task.DownloadNewChapters)
{
if(connectorName is null)
throw new ArgumentException($"connectorName can not be null for task {task}");
//Get appropriate Connector from available Connectors for TrangaTask
Connector? connector = _connectors.FirstOrDefault(c => c.name == connectorName);
if (connector is null)
throw new ArgumentException($"Connector {connectorName} is not a known connector.");
newTask = new TrangaTask(task, connector.name, publication, reoccurrence, language);
//Check if same task already exists
if (!_allTasks.Any(trangaTask => trangaTask.task == task && trangaTask.connectorName == connector.name &&
trangaTask.publication?.internalId == publication?.internalId))
if (connectorName is null)
throw new ArgumentException($"connectorName can not be null for task {task}");
if (publication is null)
throw new ArgumentException($"publication can not be null for task {task}");
Publication pub = (Publication)publication;
newTask = new DownloadNewChaptersTask(task, connector!.name, pub, reoccurrence, language);
if (!_allTasks.Any(trangaTask =>
trangaTask.task == task && trangaTask.publication?.internalId == pub.internalId &&
trangaTask.connectorName == connector.name))
{
if(task != TrangaTask.Task.UpdatePublications)
_chapterCollection.TryAdd((Publication)publication!, new List<Chapter>());
_allTasks.Add(newTask);
logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask}");
}
else
logger?.WriteLine(this.GetType().ToString(), $"Publication already exists {publication?.internalId}");
logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
}
logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask.ToString()}");
ExportData();
ExportDataAndSettings();
if (newTask is null)
throw new Exception("Invalid path");
return newTask;
}
@ -207,7 +208,7 @@ public class TaskManager
else
logger?.WriteLine(this.GetType().ToString(), $"No Task {task} {publication?.sortName} {publication?.internalId} could be found.");
}
ExportData();
ExportDataAndSettings();
}
/// <summary>
@ -251,8 +252,8 @@ public class TaskManager
Publication[] ret = connector.GetPublications(title ?? "");
foreach (Publication publication in ret)
{
if(!_chapterCollection.Any(pub => pub.Key.sortName == publication.sortName))
this._chapterCollection.TryAdd(publication, new List<Chapter>());
if(!chapterCollection.Any(pub => pub.Key.sortName == publication.sortName))
this.chapterCollection.TryAdd(publication, new List<Chapter>());
}
return ret;
}
@ -260,7 +261,7 @@ public class TaskManager
/// <returns>All added Publications</returns>
public Publication[] GetAllPublications()
{
return this._chapterCollection.Keys.ToArray();
return this.chapterCollection.Keys.ToArray();
}
/// <summary>
@ -275,7 +276,7 @@ public class TaskManager
Connector? ret = this._connectors.FirstOrDefault(connector => connector.name == connectorName);
if (ret is null)
throw new Exception($"Connector {connectorName} is not an available Connector.");
return (Connector)ret!;
return ret;
}
/// <summary>
@ -286,7 +287,7 @@ public class TaskManager
{
logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
_continueRunning = false;
ExportData();
ExportDataAndSettings();
if(force)
Environment.Exit(_allTasks.Count(task => task.state is TrangaTask.ExecutionState.Enqueued or TrangaTask.ExecutionState.Running));
@ -306,7 +307,7 @@ public class TaskManager
{
logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
buffer = File.ReadAllText(settings.tasksFilePath);
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer)!;
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
}
if (File.Exists(settings.knownPublicationsPath))
@ -315,14 +316,14 @@ public class TaskManager
buffer = File.ReadAllText(settings.knownPublicationsPath);
Publication[] publications = JsonConvert.DeserializeObject<Publication[]>(buffer)!;
foreach (Publication publication in publications)
this._chapterCollection.TryAdd(publication, new List<Chapter>());
this.chapterCollection.TryAdd(publication, new List<Chapter>());
}
}
/// <summary>
/// Exports data (settings, tasks) to file
/// </summary>
private void ExportData()
private void ExportDataAndSettings()
{
logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
File.WriteAllText(settings.settingsFilePath, JsonConvert.SerializeObject(settings));
@ -331,7 +332,7 @@ public class TaskManager
File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(this._allTasks));
logger?.WriteLine(this.GetType().ToString(), $"Exporting known publications to {settings.knownPublicationsPath}");
File.WriteAllText(settings.knownPublicationsPath, JsonConvert.SerializeObject(this._chapterCollection.Keys.ToArray()));
File.WriteAllText(settings.knownPublicationsPath, JsonConvert.SerializeObject(this.chapterCollection.Keys.ToArray()));
}

View File

@ -1,11 +1,13 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tranga.TrangaTasks;
namespace Tranga;
/// <summary>
/// Stores information on Task
/// </summary>
public class TrangaTask
public abstract class TrangaTask
{
// ReSharper disable once CommentTypo ...Tell me why!
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
@ -14,7 +16,7 @@ public class TrangaTask
public string? connectorName { get; }
public Task task { get; }
public Publication? publication { get; }
public string language { get; }
public string? language { get; }
[JsonIgnore]public ExecutionState state { get; set; }
public enum ExecutionState
@ -24,14 +26,8 @@ public class TrangaTask
Running
};
public TrangaTask(Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence, string language = "")
protected TrangaTask(Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence, string? language = null)
{
if(task != Task.UpdateKomgaLibrary && connectorName is null)
throw new ArgumentException($"connectorName can not be null for task {task}");
if (publication is null && task != Task.UpdatePublications && task != Task.UpdateKomgaLibrary)
throw new ArgumentException($"Publication can not be null for task {task}");
this.publication = publication;
this.reoccurrence = reoccurrence;
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
@ -40,6 +36,12 @@ public class TrangaTask
this.language = language;
}
/// <summary>
/// Set state to running
/// </summary>
/// <param name="taskManager"></param>
public abstract void Execute(TaskManager taskManager);
/// <returns>True if elapsed time since last execution is greater than set interval</returns>
public bool ShouldExecute()
{
@ -48,8 +50,6 @@ public class TrangaTask
public enum Task
{
UpdatePublications,
UpdateChapters,
DownloadNewChapters,
UpdateKomgaLibrary
}
@ -58,4 +58,31 @@ public class TrangaTask
{
return $"{task}, {lastExecuted}, {reoccurrence}, {state} {(connectorName is not null ? $", {connectorName}" : "" )} {(publication is not null ? $", {publication?.sortName}": "")}";
}
public class TrangaTaskJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(TrangaTask));
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadNewChapters)
return jo.ToObject<DownloadNewChaptersTask>(serializer)!;
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateKomgaLibrary)
return jo.ToObject<UpdateKomgaLibraryTask>(serializer)!;
throw new Exception();
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new Exception("Dont call this");
}
}
}

View File

@ -0,0 +1,47 @@
namespace Tranga.TrangaTasks;
public class DownloadNewChaptersTask : TrangaTask
{
public DownloadNewChaptersTask(Task task, string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(task, connectorName, publication, reoccurrence, language)
{
}
public override void Execute(TaskManager taskManager)
{
this.state = ExecutionState.Running;
Publication pub = (Publication)this.publication!;
Connector connector = taskManager.GetConnector(this.connectorName);
//Check if Publication already has a Folder
string publicationFolder = Path.Join(connector.downloadLocation, pub.folderName);
if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder);
List<Chapter> newChapters = UpdateChapters(connector, pub, language!, ref taskManager.chapterCollection);
connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings);
pub.SaveSeriesInfoJson(connector.downloadLocation);
foreach(Chapter newChapter in newChapters)
connector.DownloadChapter(pub, newChapter);
}
/// <summary>
/// Updates the available Chapters of a Publication
/// </summary>
/// <param name="connector">Connector to use</param>
/// <param name="publication">Publication to check</param>
/// <param name="language">Language to receive chapters for</param>
/// <param name="chapterCollection"></param>
/// <returns>List of Chapters that were previously not in collection</returns>
private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{
List<Chapter> newChaptersList = new();
chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection
Chapter[] newChapters = connector.GetChapters(publication, language);
newChaptersList = newChapters.Where(nChapter => !connector.CheckChapterIsDownloaded(publication, nChapter)).ToList();
return newChaptersList;
}
}

View File

@ -0,0 +1,20 @@
namespace Tranga.TrangaTasks;
public class UpdateKomgaLibraryTask : TrangaTask
{
public UpdateKomgaLibraryTask(Task task, TimeSpan reoccurrence) : base(task, null, null, reoccurrence)
{
}
public override void Execute(TaskManager taskManager)
{
this.state = ExecutionState.Running;
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);
}
}