14 Commits
0.3.1 ... 0.4

Author SHA1 Message Date
4ee47ed65c Snarky comments. Documentation 2023-05-20 15:05:41 +02:00
430ee2301f Implemented Queue, so that taskManager is not held up with other Connector-tasks.
Tasks are now executed in another Thread.
Replaced TrangaTask.isBeingExecuted bool with 3-states: Waiting, Enqueued, Running
Added Queue size to CLI output.
2023-05-20 14:50:48 +02:00
58de0115d6 Use GetConnector Method. 2023-05-20 14:21:47 +02:00
fa44de0c8d Moved _chapterCollection initialization 2023-05-20 14:18:17 +02:00
72bd1c56a8 Added Method GetConnector to TaskManager that returns Connector with given Name.
Removed Method NewKomga unused
2023-05-20 14:18:03 +02:00
538cfec619 Added UpdateKomgaTask
Fixed Komga-auth
Added Komga to data.json
2023-05-20 14:07:38 +02:00
ff01bac9d4 Changed ComicInfo.xml to use chapternumber as "Number". 2023-05-20 12:53:54 +02:00
52f357021d Added KomgaAPI base,
Rewrote settings/task storage to only produce single file
2023-05-20 12:53:19 +02:00
d9a7eeb5c3 Why is it so complicated to multiply some numbers 2023-05-20 02:42:36 +02:00
e0784b2c38 Added field sortNumber to chapter 2023-05-20 02:39:23 +02:00
0afbfb6010 Add Volume and chapter number to ComicInfo.xml 2023-05-20 02:29:54 +02:00
c2872bf177 cutoff after first decimal 2023-05-20 02:23:37 +02:00
658b93bc51 I hate floating point 2023-05-20 02:10:10 +02:00
3ff2ac1043 Changed numbering scheme, because floating point. 2023-05-20 01:56:33 +02:00
10 changed files with 424 additions and 125 deletions

View File

@ -10,9 +10,7 @@ app.MapGet("/GetConnectors", () => JsonSerializer.Serialize(taskManager.GetAvail
app.MapGet("/GetPublications", (string connectorName, string? title) =>
{
Connector? connector = taskManager.GetAvailableConnectors().FirstOrDefault(c => c.Key == connectorName).Value;
if (connector is null)
return JsonSerializer.Serialize($"Connector {connectorName} is not a known connector.");
Connector connector = taskManager.GetConnector(connectorName);
Publication[] publications;
if (title is not null)

View File

@ -4,23 +4,67 @@ using Tranga.Connectors;
namespace Tranga_CLI;
/*
* This is written with pure hatred for readability.
* At some point do this properly.
* Read at own risk.
*/
public static class Tranga_Cli
{
public static void Main(string[] args)
{
string folderPath = Directory.GetCurrentDirectory();
string settingsPath = Path.Join(Directory.GetCurrentDirectory(), "lastPath.setting");
TaskManager.SettingsData settings;
string settingsPath = Path.Join(Directory.GetCurrentDirectory(), "data.json");
if (File.Exists(settingsPath))
folderPath = File.ReadAllText(settingsPath);
settings = TaskManager.LoadData(Directory.GetCurrentDirectory());
else
settings = new TaskManager.SettingsData(Directory.GetCurrentDirectory(), null, new HashSet<TrangaTask>());
Console.WriteLine($"Output folder path [{folderPath}]:");
Console.WriteLine($"Output folder path [{settings.downloadLocation}]:");
string? tmpPath = Console.ReadLine();
while(tmpPath is null)
tmpPath = Console.ReadLine();
if(tmpPath.Length > 0)
folderPath = tmpPath;
File.WriteAllText(settingsPath, folderPath);
settings.downloadLocation = tmpPath;
Console.WriteLine($"Komga BaseURL [{settings.komga?.baseUrl}]:");
string? tmpUrl = Console.ReadLine();
while (tmpUrl is null)
tmpUrl = Console.ReadLine();
if (tmpUrl.Length > 0)
{
Console.WriteLine("Username:");
string? tmpUser = Console.ReadLine();
while (tmpUser is null || tmpUser.Length < 1)
tmpUser = Console.ReadLine();
Console.WriteLine("Password:");
string tmpPass = string.Empty;
ConsoleKey key;
do
{
var keyInfo = Console.ReadKey(intercept: true);
key = keyInfo.Key;
if (key == ConsoleKey.Backspace && tmpPass.Length > 0)
{
Console.Write("\b \b");
tmpPass = tmpPass[0..^1];
}
else if (!char.IsControl(keyInfo.KeyChar))
{
Console.Write("*");
tmpPass += keyInfo.KeyChar;
}
} while (key != ConsoleKey.Enter);
settings.komga = new Komga(tmpUrl, tmpUser, tmpPass);
}
//For now only TaskManager mode
/*
Console.Write("Mode (D: Interactive only, T: TaskManager):");
ConsoleKeyInfo mode = Console.ReadKey();
while (mode.Key != ConsoleKey.D && mode.Key != ConsoleKey.T)
@ -28,14 +72,15 @@ public static class Tranga_Cli
Console.WriteLine();
if(mode.Key == ConsoleKey.D)
DownloadNow(folderPath);
DownloadNow(settings);
else if (mode.Key == ConsoleKey.T)
TaskMode(folderPath);
TaskMode(settings);*/
TaskMode(settings);
}
private static void TaskMode(string folderPath)
private static void TaskMode(TaskManager.SettingsData settings)
{
TaskManager taskManager = new TaskManager(folderPath);
TaskManager taskManager = new TaskManager(settings);
ConsoleKey selection = ConsoleKey.NoName;
int menu = 0;
while (selection != ConsoleKey.Escape && selection != ConsoleKey.Q)
@ -49,13 +94,18 @@ public static class Tranga_Cli
menu = 0;
break;
case 2:
Connector connector = SelectConnector(folderPath, taskManager.GetAvailableConnectors().Values.ToArray());
TrangaTask.Task task = SelectTask();
Connector? connector = null;
if(task != TrangaTask.Task.UpdateKomgaLibrary)
connector = SelectConnector(settings.downloadLocation, taskManager.GetAvailableConnectors().Values.ToArray());
Publication? publication = null;
if(task != TrangaTask.Task.UpdatePublications)
publication = SelectPublication(connector);
if(task != TrangaTask.Task.UpdatePublications && task != TrangaTask.Task.UpdateKomgaLibrary)
publication = SelectPublication(connector!);
TimeSpan reoccurrence = SelectReoccurrence();
TrangaTask newTask = taskManager.AddTask(task, connector.name, publication, reoccurrence, "en");
TrangaTask newTask = taskManager.AddTask(task, connector?.name, publication, reoccurrence, "en");
Console.WriteLine(newTask);
Console.WriteLine("Press any key.");
Console.ReadKey();
@ -79,20 +129,19 @@ public static class Tranga_Cli
while (query is null || query.Length < 1)
query = Console.ReadLine();
PrintTasks(taskManager.GetAllTasks().Where(qTask =>
((Publication)qTask.publication!).sortName.ToLower()
.Contains(query, StringComparison.OrdinalIgnoreCase)).ToArray());
qTask.ToString().ToLower().Contains(query, StringComparison.OrdinalIgnoreCase)).ToArray());
Console.WriteLine("Press any key.");
Console.ReadKey();
menu = 0;
break;
case 6:
PrintTasks(taskManager.GetAllTasks().Where(eTask => eTask.isBeingExecuted).ToArray());
PrintTasks(taskManager.GetAllTasks().Where(eTask => eTask.state == TrangaTask.ExecutionState.Running).ToArray());
Console.WriteLine("Press any key.");
Console.ReadKey();
menu = 0;
break;
default:
selection = Menu(taskManager, folderPath);
selection = Menu(taskManager, settings.downloadLocation);
switch (selection)
{
case ConsoleKey.L:
@ -124,10 +173,12 @@ public static class Tranga_Cli
}
}
if (taskManager.GetAllTasks().Any(task => task.isBeingExecuted))
if (taskManager.GetAllTasks().Any(task => task.state == TrangaTask.ExecutionState.Running))
{
Console.WriteLine("Force quit (Even with running tasks?) y/N");
selection = Console.ReadKey().Key;
while(selection != ConsoleKey.Y && selection != ConsoleKey.N)
selection = Console.ReadKey().Key;
taskManager.Shutdown(selection == ConsoleKey.Y);
}else
// ReSharper disable once RedundantArgumentDefaultValue Better readability
@ -137,9 +188,11 @@ public static class Tranga_Cli
private static ConsoleKey Menu(TaskManager taskManager, string folderPath)
{
int taskCount = taskManager.GetAllTasks().Length;
int taskRunningCount = taskManager.GetAllTasks().Count(task => task.isBeingExecuted);
int taskRunningCount = taskManager.GetAllTasks().Count(task => task.state == TrangaTask.ExecutionState.Running);
int taskEnqueuedCount =
taskManager.GetAllTasks().Count(task => task.state == TrangaTask.ExecutionState.Enqueued);
Console.Clear();
Console.WriteLine($"Download Folder: {folderPath} Tasks (Running/Total): {taskRunningCount}/{taskCount}");
Console.WriteLine($"Download Folder: {folderPath} Tasks (Running/Queue/Total): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}");
Console.WriteLine("U: Update this Screen");
Console.WriteLine("L: List tasks");
Console.WriteLine("C: Create Task");
@ -156,10 +209,11 @@ public static class Tranga_Cli
private static void PrintTasks(TrangaTask[] tasks)
{
int taskCount = tasks.Length;
int taskRunningCount = tasks.Count(task => task.isBeingExecuted);
int taskRunningCount = tasks.Count(task => task.state == TrangaTask.ExecutionState.Running);
int taskEnqueuedCount = tasks.Count(task => task.state == TrangaTask.ExecutionState.Enqueued);
Console.Clear();
int tIndex = 0;
Console.WriteLine($"Tasks (Running/Total): {taskRunningCount}/{taskCount}");
Console.WriteLine($"Tasks (Running/Queue/Total): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}");
foreach(TrangaTask trangaTask in tasks)
Console.WriteLine($"{tIndex++:000}: {trangaTask}");
}
@ -232,9 +286,9 @@ public static class Tranga_Cli
return TimeSpan.Parse(Console.ReadLine()!, new CultureInfo("en-US"));
}
private static void DownloadNow(string folderPath)
private static void DownloadNow(TaskManager.SettingsData settings)
{
Connector connector = SelectConnector(folderPath);
Connector connector = SelectConnector(settings.downloadLocation, new Connector[]{new MangaDex(settings.downloadLocation)});
Publication publication = SelectPublication(connector);
@ -253,10 +307,9 @@ public static class Tranga_Cli
}
}
private static Connector SelectConnector(string folderPath, Connector[]? availableConnectors = null)
private static Connector SelectConnector(string folderPath, Connector[] connectors)
{
Console.Clear();
Connector[] connectors = availableConnectors ?? new Connector[] { new MangaDex(folderPath) };
int cIndex = 0;
Console.WriteLine("Connectors:");

View File

@ -1,2 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Komga/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tranga/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -13,16 +13,21 @@ public struct Chapter
public string? chapterNumber { get; }
public string url { get; }
public string fileName { get; }
public string sortNumber { get; }
public Chapter(string? name, string? volumeNumber, string? chapterNumber, string url)
{
this.name = name;
this.volumeNumber = volumeNumber;
this.volumeNumber = volumeNumber is { Length: > 0 } ? volumeNumber : "1";
this.chapterNumber = chapterNumber;
this.url = url;
string chapterName = string.Concat((name ?? "").Split(Path.GetInvalidFileNameChars()));
double multiplied = Convert.ToDouble(chapterNumber, new NumberFormatInfo() { NumberDecimalSeparator = "." }) *
Convert.ToInt32(volumeNumber);
this.fileName = $"{chapterName} - V{volumeNumber}C{chapterNumber} - {multiplied.ToString(new NumberFormatInfo() { NumberDecimalSeparator = "." })}";
NumberFormatInfo nfi = new NumberFormatInfo()
{
NumberDecimalSeparator = "."
};
sortNumber = decimal.Round(Convert.ToDecimal(this.volumeNumber) * Convert.ToDecimal(this.chapterNumber, nfi), 1)
.ToString(nfi);
this.fileName = $"{chapterName} - V{volumeNumber}C{chapterNumber} - {sortNumber}";
}
}

View File

@ -68,21 +68,36 @@ public abstract class Connector
File.WriteAllText(seriesInfoPath,publication.GetSeriesInfoJson());
}
/// <summary>
/// Creates a string containing XML of publication and chapter.
/// See ComicInfo.xml
/// </summary>
/// <returns>XML-string</returns>
protected static string CreateComicInfo(Publication publication, Chapter chapter)
{
XElement comicInfo = new XElement("ComicInfo",
new XElement("Tags", string.Join(',',publication.tags)),
new XElement("LanguageISO", publication.originalLanguage),
new XElement("Title", chapter.name)
new XElement("Title", chapter.name),
new XElement("Volume", chapter.volumeNumber),
new XElement("Number", chapter.chapterNumber) //TODO check if this is correct at some point
);
return comicInfo.ToString();
}
/// <summary>
/// Checks if a chapter-archive is already present
/// </summary>
/// <returns>true if chapter is present</returns>
public bool ChapterIsDownloaded(Publication publication, Chapter chapter)
{
return File.Exists(CreateFullFilepath(publication, chapter));
}
/// <summary>
/// Creates full file path of chapter-archive
/// </summary>
/// <returns>Filepath</returns>
protected string CreateFullFilepath(Publication publication, Chapter chapter)
{
return Path.Join(downloadLocation, publication.folderName, chapter.fileName);

118
Tranga/Komga.cs Normal file
View File

@ -0,0 +1,118 @@
using System.Net.Http.Headers;
using System.Text.Json.Nodes;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Tranga;
/// <summary>
/// Provides connectivity to Komga-API
/// Can fetch and update libraries
/// </summary>
public class Komga
{
public string baseUrl { get; }
public string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems
/// <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)
{
this.baseUrl = baseUrl;
this.auth = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
}
/// <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)
{
this.baseUrl = baseUrl;
this.auth = auth;
}
/// <summary>
/// Fetches all libraries available to the user
/// </summary>
/// <returns>Array of KomgaLibraries</returns>
public KomgaLibrary[] GetLibraries()
{
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth);
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
if (result is null)
return Array.Empty<KomgaLibrary>();
HashSet<KomgaLibrary> ret = new();
foreach (JsonNode jsonNode in result)
{
var jObject = (JsonObject?)jsonNode;
string libraryId = jObject!["id"]!.GetValue<string>();
string libraryName = jObject!["name"]!.GetValue<string>();
ret.Add(new KomgaLibrary(libraryId, libraryName));
}
return ret.ToArray();
}
/// <summary>
/// Updates library with given id
/// </summary>
/// <param name="libraryId">Id of the Komga-Library</param>
/// <returns>true if successful</returns>
public bool UpdateLibrary(string libraryId)
{
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)
{
HttpClient client = new();
HttpRequestMessage requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
}
};
HttpResponseMessage response = client.Send(requestMessage);
Stream resultString = response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null;
return resultString;
}
public static bool MakePost(string url, string auth)
{
HttpClient client = new();
HttpRequestMessage requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
}
};
HttpResponseMessage response = client.Send(requestMessage);
return response.IsSuccessStatusCode;
}
}
}

View File

@ -36,9 +36,6 @@ public readonly struct Publication
this.folderName = string.Concat(sortName.Split(Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).ToArray()));
}
/// <summary>
///
/// </summary>
/// <returns>Serialized JSON String for series.json</returns>
public string GetSeriesInfoJson()
{
@ -57,13 +54,13 @@ public readonly struct Publication
//Only for series.json what an abomination, why are all the fields not-null????
private struct Metadata
{
// ReSharper disable UnusedAutoPropertyAccessor.Local we need it, trust
// ReSharper disable UnusedAutoPropertyAccessor.Local we need them all, trust me
[JsonRequired] public string type { get; }
[JsonRequired] public string publisher { get; }
// ReSharper disable twice IdentifierTypo
[JsonRequired] public int comicid { get; }
[JsonRequired] public string booktype { get; }
// ReSharper disable InconsistentNaming
// ReSharper disable InconsistentNaming This one property is capitalized. Why?
[JsonRequired] public string ComicImage { get; }
[JsonRequired] public int total_issues { get; }
[JsonRequired] public string publication_run { get; }
@ -84,7 +81,7 @@ public readonly struct Publication
this.status = status;
this.description_text = description_text;
//kill it with fire
//kill it with fire, but otherwise Komga will not parse
type = "Manga";
publisher = "";
comicid = 0;

View File

@ -7,41 +7,59 @@
/// </summary>
public static class TaskExecutor
{
/// <summary>
/// Executes TrangaTask.
/// </summary>
/// <param name="connectors">List of all available Connectors</param>
/// <param name="taskManager">Parent</param>
/// <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(Connector[] connectors, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection)
public static void Execute(TaskManager taskManager, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection)
{
//Get Connector from list of available Connectors and the required Connector of the TrangaTask
Connector? connector = connectors.FirstOrDefault(c => c.name == trangaTask.connectorName);
if (connector is null)
throw new ArgumentException($"Connector {trangaTask.connectorName} is not a known connector.");
if (trangaTask.isBeingExecuted)
//Only execute task if it is not already being executed.
if (trangaTask.state == TrangaTask.ExecutionState.Running)
return;
trangaTask.isBeingExecuted = true;
trangaTask.lastExecuted = DateTime.Now;
trangaTask.state = TrangaTask.ExecutionState.Running;
//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, chapterCollection);
DownloadNewChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
break;
case TrangaTask.Task.UpdateChapters:
UpdateChapters(connector, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
UpdateChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
break;
case TrangaTask.Task.UpdatePublications:
UpdatePublications(connector, chapterCollection);
UpdatePublications(connector!, chapterCollection);
break;
case TrangaTask.Task.UpdateKomgaLibrary:
UpdateKomgaLibrary(taskManager);
break;
}
trangaTask.isBeingExecuted = false;
trangaTask.state = TrangaTask.ExecutionState.Waiting;
trangaTask.lastExecuted = DateTime.Now;
}
/// <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>

View File

@ -9,32 +9,73 @@ namespace Tranga;
/// </summary>
public class TaskManager
{
private readonly Dictionary<Publication, List<Chapter>> _chapterCollection;
private readonly Dictionary<Publication, List<Chapter>> _chapterCollection = new();
private readonly HashSet<TrangaTask> _allTasks;
private bool _continueRunning = true;
private readonly Connector[] _connectors;
private Dictionary<Connector, List<TrangaTask>> tasksToExecute = new();
private string downloadLocation { get; }
public Komga? komga { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="folderPath">Local path to save data (Manga) to</param>
public TaskManager(string folderPath)
/// <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)
{
this.downloadLocation = folderPath;
if (komgaBaseUrl != null && komgaUsername != null && komgaPassword != null)
this.komga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword);
this._connectors = new Connector[]{ new MangaDex(folderPath) };
_chapterCollection = new();
_allTasks = ImportTasks(Directory.GetCurrentDirectory());
foreach(Connector cConnector in this._connectors)
tasksToExecute.Add(cConnector, new List<TrangaTask>());
_allTasks = new HashSet<TrangaTask>();
Thread taskChecker = new(TaskCheckerThread);
taskChecker.Start();
}
public TaskManager(SettingsData settings)
{
this._connectors = new Connector[]{ new MangaDex(settings.downloadLocation) };
foreach(Connector cConnector in this._connectors)
tasksToExecute.Add(cConnector, new List<TrangaTask>());
this.downloadLocation = settings.downloadLocation;
this.komga = settings.komga;
_allTasks = settings.allTasks;
Thread taskChecker = new(TaskCheckerThread);
taskChecker.Start();
}
/// <summary>
/// Runs continuously until shutdown.
/// Checks if tasks have to be executed (time elapsed)
/// </summary>
private void TaskCheckerThread()
{
while (_continueRunning)
{
foreach (TrangaTask task in _allTasks)
//Check if previous tasks have finished and execute new tasks
foreach (KeyValuePair<Connector, List<TrangaTask>> connectorTaskQueue in tasksToExecute)
{
if(task.ShouldExecute())
TaskExecutor.Execute(this._connectors, task, this._chapterCollection); //Might crash here, when adding new Task while another Task is running. Check later
connectorTaskQueue.Value.RemoveAll(task => task.state == TrangaTask.ExecutionState.Waiting);
if (connectorTaskQueue.Value.Count > 0 && !connectorTaskQueue.Value.All(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Waiting))
ExecuteTaskNow(connectorTaskQueue.Value.First());
}
//Check if task should be executed
//Depending on type execute immediately or enqueue
foreach (TrangaTask task in _allTasks.Where(aTask => aTask.ShouldExecute()))
{
task.state = TrangaTask.ExecutionState.Enqueued;
if(task.connectorName is null)
ExecuteTaskNow(task);
else
{
tasksToExecute[GetConnector(task.connectorName!)].Add(task);
}
}
Thread.Sleep(1000);
}
@ -51,7 +92,7 @@ public class TaskManager
Task t = new Task(() =>
{
TaskExecutor.Execute(this._connectors, task, this._chapterCollection);
TaskExecutor.Execute(this, task, this._chapterCollection);
});
t.Start();
}
@ -65,24 +106,44 @@ public class TaskManager
/// <param name="reoccurrence">Time-Interval between Executions</param>
/// <param name="language">language, should Task require parameter. Can be empty</param>
/// <exception cref="ArgumentException">Is thrown when connectorName is not a available Connector</exception>
public TrangaTask AddTask(TrangaTask.Task task, string connectorName, Publication? publication, TimeSpan reoccurrence,
public TrangaTask AddTask(TrangaTask.Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence,
string language = "")
{
if (task != TrangaTask.Task.UpdateKomgaLibrary && connectorName is null)
throw new ArgumentException($"connectorName can not be null for task {task}");
TrangaTask newTask;
if (task == TrangaTask.Task.UpdateKomgaLibrary)
{
newTask = new TrangaTask(task, null, null, reoccurrence, language);
//Check if same task already exists
// ReSharper disable once SimplifyLinqExpressionUseAll readabilty
if (!_allTasks.Any(trangaTask => trangaTask.task == task))
{
_allTasks.Add(newTask);
}
}
else
{
//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.");
TrangaTask newTask = new TrangaTask(connector.name, task, publication, reoccurrence, language);
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?.downloadUrl != publication?.downloadUrl))
if (!_allTasks.Any(trangaTask => trangaTask.task == task && trangaTask.connectorName == connector.name &&
trangaTask.publication?.downloadUrl == publication?.downloadUrl))
{
if(task != TrangaTask.Task.UpdatePublications)
_chapterCollection.Add((Publication)publication!, new List<Chapter>());
_allTasks.Add(newTask);
ExportTasks(Directory.GetCurrentDirectory());
}
}
ExportData(Directory.GetCurrentDirectory());
return newTask;
}
@ -97,21 +158,15 @@ public class TaskManager
_allTasks.RemoveWhere(trangaTask =>
trangaTask.task == task && trangaTask.connectorName == connectorName &&
trangaTask.publication?.downloadUrl == publication?.downloadUrl);
ExportTasks(Directory.GetCurrentDirectory());
ExportData(Directory.GetCurrentDirectory());
}
/// <summary>
///
/// </summary>
/// <returns>All available Connectors</returns>
public Dictionary<string, Connector> GetAvailableConnectors()
{
return this._connectors.ToDictionary(connector => connector.name, connector => connector);
}
/// <summary>
///
/// </summary>
/// <returns>All TrangaTasks in task-collection</returns>
public TrangaTask[] GetAllTasks()
{
@ -120,15 +175,25 @@ public class TaskManager
return ret;
}
/// <summary>
///
/// </summary>
/// <returns>All added Publications</returns>
public Publication[] GetAllPublications()
{
return this._chapterCollection.Keys.ToArray();
}
/// <summary>
/// Return Connector with given Name
/// </summary>
/// <param name="connectorName">Connector-name (exact)</param>
/// <exception cref="Exception">If Connector is not available</exception>
public Connector GetConnector(string connectorName)
{
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!;
}
/// <summary>
/// Shuts down the taskManager.
/// </summary>
@ -136,37 +201,57 @@ public class TaskManager
public void Shutdown(bool force = false)
{
_continueRunning = false;
ExportTasks(Directory.GetCurrentDirectory());
ExportData(Directory.GetCurrentDirectory());
if(force)
Environment.Exit(_allTasks.Count(task => task.isBeingExecuted));
Environment.Exit(_allTasks.Count(task => task.state is TrangaTask.ExecutionState.Enqueued or TrangaTask.ExecutionState.Running));
//Wait for tasks to finish
while(_allTasks.Any(task => task.isBeingExecuted))
while(_allTasks.Any(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Enqueued))
Thread.Sleep(10);
Environment.Exit(0);
}
private HashSet<TrangaTask> ImportTasks(string importFolderPath)
/// <summary>
/// Loads stored data (settings, tasks) from file
/// </summary>
/// <param name="importFolderPath">working directory, filename has to be data.json</param>
public static SettingsData LoadData(string importFolderPath)
{
string filePath = Path.Join(importFolderPath, "tasks.json");
if (!File.Exists(filePath))
return new HashSet<TrangaTask>();
string importPath = Path.Join(importFolderPath, "data.json");
if (!File.Exists(importPath))
return new SettingsData("", null, new HashSet<TrangaTask>());
string toRead = File.ReadAllText(filePath);
string toRead = File.ReadAllText(importPath);
SettingsData data = JsonConvert.DeserializeObject<SettingsData>(toRead)!;
TrangaTask[] importTasks = JsonConvert.DeserializeObject<TrangaTask[]>(toRead)!;
foreach(TrangaTask task in importTasks.Where(task => task.publication is not null))
this._chapterCollection.Add((Publication)task.publication!, new List<Chapter>());
return importTasks.ToHashSet();
return data;
}
private void ExportTasks(string exportFolderPath)
/// <summary>
/// Exports data (settings, tasks) to file
/// </summary>
/// <param name="exportFolderPath">Folder path, filename will be data.json</param>
private void ExportData(string exportFolderPath)
{
string filePath = Path.Join(exportFolderPath, "tasks.json");
string toWrite = JsonConvert.SerializeObject(_allTasks.ToArray());
File.WriteAllText(filePath,toWrite);
SettingsData data = new SettingsData(this.downloadLocation, this.komga, this._allTasks);
string exportPath = Path.Join(exportFolderPath, "data.json");
string serializedData = JsonConvert.SerializeObject(data);
File.WriteAllText(exportPath, serializedData);
}
public class SettingsData
{
public string downloadLocation { get; set; }
public Komga? komga { get; set; }
public HashSet<TrangaTask> allTasks { get; }
public SettingsData(string downloadLocation, Komga? komga, HashSet<TrangaTask> allTasks)
{
this.downloadLocation = downloadLocation;
this.komga = komga;
this.allTasks = allTasks;
}
}
}

View File

@ -7,20 +7,31 @@ namespace Tranga;
/// </summary>
public class TrangaTask
{
// ReSharper disable once CommentTypo ...tell me why!
// ReSharper disable once CommentTypo ...Tell me why!
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
public TimeSpan reoccurrence { get; }
public DateTime lastExecuted { get; set; }
public string connectorName { get; }
public string? connectorName { get; }
public Task task { get; }
public Publication? publication { get; }
public string language { get; }
[JsonIgnore]public bool isBeingExecuted { get; set; }
[JsonIgnore]public ExecutionState state { get; set; }
public TrangaTask(string connectorName, Task task, Publication? publication, TimeSpan reoccurrence, string language = "")
public enum ExecutionState
{
if (task != Task.UpdatePublications && publication is null)
throw new ArgumentException($"Publication has to be not null for task {task}");
Waiting,
Enqueued,
Running
};
public TrangaTask(Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence, string language = "")
{
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);
@ -29,24 +40,22 @@ public class TrangaTask
this.language = language;
}
/// <summary>
///
/// </summary>
/// <returns>True if elapsed time since last execution is greater than set interval</returns>
public bool ShouldExecute()
{
return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence;
return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence && state is ExecutionState.Waiting;
}
public enum Task
{
UpdatePublications,
UpdateChapters,
DownloadNewChapters
DownloadNewChapters,
UpdateKomgaLibrary
}
public override string ToString()
{
return $"{task}\t{lastExecuted}\t{reoccurrence}\t{(isBeingExecuted ? "running" : "waiting")}\t{connectorName}\t{publication?.sortName}";
return $"{task}\t{lastExecuted}\t{reoccurrence}\t{state}\t{connectorName}\t{publication?.sortName}";
}
}