Merge pull request 'api-testing' (#5) from api-testing into master

Reviewed-on: glax/Tranga#5
This commit is contained in:
glax 2023-05-21 22:04:06 +02:00
commit 8b99a98e24
10 changed files with 151 additions and 177 deletions

View File

@ -1,19 +1,21 @@
using System.Text.Json;
using Tranga;
using Logging; using Logging;
using Tranga;
string applicationFolderPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Tranga-API"); string applicationFolderPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Tranga-API");
string logsFolderPath = Path.Join(applicationFolderPath, "logs"); string logsFolderPath = Path.Join(applicationFolderPath, "logs");
string logFilePath = Path.Join(logsFolderPath, $"log-{DateTime.Now:dd-M-yyyy-HH-mm-ss}.txt"); string logFilePath = Path.Join(logsFolderPath, $"log-{DateTime.Now:dd-M-yyyy-HH-mm-ss}.txt");
string settingsFilePath = Path.Join(applicationFolderPath, "data.json"); string settingsFilePath = Path.Join(applicationFolderPath, "data.json");
Directory.CreateDirectory(applicationFolderPath);
Directory.CreateDirectory(logsFolderPath);
Console.WriteLine($"Logfile-Path: {logFilePath}"); Console.WriteLine($"Logfile-Path: {logFilePath}");
Console.WriteLine($"Settings-File-Path: {settingsFilePath}"); Console.WriteLine($"Settings-File-Path: {settingsFilePath}");
Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, null, logFilePath); Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, null, logFilePath);
logger.WriteLine("Tranga_API", "Loading Taskmanager."); logger.WriteLine("Tranga_CLI", "Loading Taskmanager.");
TaskManager.SettingsData settings; TaskManager.SettingsData settings;
if (File.Exists(settingsFilePath)) if (File.Exists(settingsFilePath))
settings = TaskManager.LoadData(settingsFilePath); settings = TaskManager.LoadData(settingsFilePath);
@ -23,162 +25,98 @@ else
TaskManager taskManager = new (settings, logger); TaskManager taskManager = new (settings, logger);
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddControllers().AddNewtonsoftJson();
var app = builder.Build(); var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwagger();
app.UseSwaggerUI();
app.MapGet("/GetConnectors", () => JsonSerializer.Serialize(taskManager.GetAvailableConnectors().Values.ToArray())); app.MapGet("/GetAvailableControllers", () => taskManager.GetAvailableConnectors());
app.MapGet("/GetPublications", (string connectorName, string? publicationName) => app.MapGet("/GetKnownPublications", () => taskManager.GetAllPublications());
app.MapGet("/GetPublicationsFromConnector", (string connectorName, string title) =>
{ {
Connector connector = taskManager.GetConnector(connectorName); Connector? connector = taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
if (connector is null)
Publication[] publications; return Array.Empty<Publication>();
if (publicationName is not null) if(title.Length < 4)
publications = connector.GetPublications(publicationName); return Array.Empty<Publication>();
else return taskManager.GetPublicationsFromConnector(connector, title);
publications = connector.GetPublications();
return JsonSerializer.Serialize(publications);
}); });
app.MapGet("/ListTasks", () => JsonSerializer.Serialize(taskManager.GetAllTasks())); app.MapGet("/Tasks/GetTaskTypes", () => Enum.GetNames(typeof(TrangaTask.Task)));
app.MapGet("/TaskTypes", () =>
app.MapPost("/Tasks/Create", (string taskType, string? connectorName, string? publicationId, string reoccurrenceTime, string? language) =>
{ {
string[] availableTasks = Enum.GetNames(typeof(TrangaTask.Task)); Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == publicationId);
return JsonSerializer.Serialize(availableTasks); TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType);
taskManager.AddTask(task, connectorName, publication, TimeSpan.Parse(reoccurrenceTime), language??"");
}); });
app.MapGet("/CreateTask", app.MapPost("/Tasks/Delete", (string taskType, string? connectorName, string? publicationId) =>
(TrangaTask.Task task, string? connectorName, string? publicationInternalId, TimeSpan reoccurrence, string? language) =>
{
switch (task)
{
case TrangaTask.Task.UpdateKomgaLibrary:
taskManager.AddTask(TrangaTask.Task.UpdateKomgaLibrary, null, null, reoccurrence);
break;
case TrangaTask.Task.DownloadNewChapters:
try
{
Publication? publication = taskManager.GetAllPublications()
.FirstOrDefault(pub => pub.internalId == publicationInternalId);
if (publication is null)
{
return JsonSerializer.Serialize($"Publication {publicationInternalId} is unknown.");
}
else
{
taskManager.AddTask(TrangaTask.Task.DownloadNewChapters, connectorName, publication, reoccurrence, language ?? "");
return JsonSerializer.Serialize("Success");
}
}
catch (Exception e)
{
return JsonSerializer.Serialize(e.Message);
}
default: return JsonSerializer.Serialize("Not Implemented");
}
return JsonSerializer.Serialize("Not Implemented");
});
app.MapGet("/RemoveTask", (TrangaTask.Task task, string? connectorName, string? publicationInternalId) =>
{ {
switch (task) Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == publicationId);
{ TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType);
case TrangaTask.Task.UpdateKomgaLibrary: taskManager.DeleteTask(task, connectorName, publication);
taskManager.DeleteTask(TrangaTask.Task.UpdateKomgaLibrary, null, null);
return JsonSerializer.Serialize("Success");
case TrangaTask.Task.DownloadNewChapters:
Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == publicationInternalId);
if (publication is null)
JsonSerializer.Serialize($"Publication with id {publicationInternalId} is unknown.");
taskManager.DeleteTask(TrangaTask.Task.DownloadNewChapters, connectorName, publication);
return JsonSerializer.Serialize("Success");
default: return JsonSerializer.Serialize("Not Implemented");
}
}); });
app.MapGet("/StartTask", (TrangaTask.Task task, string? connectorName, string? publicationInternalId) => app.MapGet("/Tasks/GetList", () => taskManager.GetAllTasks());
app.MapPost("/Tasks/Start", (string taskType, string? connectorName, string? publicationId) =>
{ {
TrangaTask[] allTasks = taskManager.GetAllTasks(); TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
TrangaTask? taskToStart = allTasks.FirstOrDefault(tTask => TrangaTask? task = taskManager.GetAllTasks().FirstOrDefault(tTask =>
tTask.task == task && tTask.connectorName == connectorName && tTask.task == pTask && tTask.publication?.internalId == publicationId && tTask.connectorName == connectorName);
tTask.publication?.internalId == publicationInternalId); if (task is null)
if(taskToStart is null) return;
JsonSerializer.Serialize($"Task with parameters {task} {connectorName} {publicationInternalId} is unknown."); taskManager.ExecuteTaskNow(task);
taskManager.ExecuteTaskNow(taskToStart!);
return JsonSerializer.Serialize("Success");
}); });
app.MapGet("/TaskQueue", () => app.MapGet("/Tasks/GetRunningTasks",
() => taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Running));
app.MapGet("/Queue/GetList",
() => taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Enqueued));
app.MapPost("/Queue/Enqueue", (string taskType, string? connectorName, string? publicationId) =>
{ {
return JsonSerializer.Serialize(taskManager.GetAllTasks() TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
.Where(task => task.state is TrangaTask.ExecutionState.Enqueued or TrangaTask.ExecutionState.Running) TrangaTask? task = taskManager.GetAllTasks().FirstOrDefault(tTask =>
.ToArray()); tTask.task == pTask && tTask.publication?.internalId == publicationId && tTask.connectorName == connectorName);
if (task is null)
return;
taskManager.AddTaskToQueue(task);
}); });
app.MapGet("/TaskEnqueue", (TrangaTask.Task task, string? connectorName, string? publicationInternalId) => app.MapPost("/Queue/Dequeue", (string taskType, string? connectorName, string? publicationId) =>
{ {
TrangaTask[] allTasks = taskManager.GetAllTasks(); TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
TrangaTask? taskToEnqueue = allTasks.FirstOrDefault(tTask => TrangaTask? task = taskManager.GetAllTasks().FirstOrDefault(tTask =>
tTask.task == task && tTask.connectorName == connectorName && tTask.task == pTask && tTask.publication?.internalId == publicationId && tTask.connectorName == connectorName);
tTask.publication?.internalId == publicationInternalId); if (task is null)
if(taskToEnqueue is null) return;
JsonSerializer.Serialize($"Task with parameters {task} {connectorName} {publicationInternalId} is unknown."); taskManager.RemoveTaskFromQueue(task);
taskManager.AddTaskToQueue(taskToEnqueue!);
return JsonSerializer.Serialize("Success");
}); });
app.MapGet("/TaskDequeue", (TrangaTask.Task task, string? connectorName, string? publicationInternalId) => app.MapGet("/Settings/Get", () => new Settings(taskManager.settings));
{
TrangaTask[] allTasks = taskManager.GetAllTasks();
TrangaTask? taskToDequeue = allTasks.FirstOrDefault(tTask =>
tTask.task == task && tTask.connectorName == connectorName &&
tTask.publication?.internalId == publicationInternalId);
if(taskToDequeue is null)
JsonSerializer.Serialize($"Task with parameters {task} {connectorName} {publicationInternalId} is unknown.");
taskManager.RemoveTaskFromQueue(taskToDequeue);
return JsonSerializer.Serialize("Success");
});
app.MapGet("/Settings", () => JsonSerializer.Serialize(new Settings(taskManager.settings))); app.MapPost("/Settings/Update", (string? downloadLocation, string? komgaUrl, string? komgaAuth) => taskManager.UpdateSettings(downloadLocation, komgaUrl, komgaAuth) );
app.MapGet("/EditSettings", (string downloadLocation, string komgaBaseUrl, string komgaAuthString) =>
{
taskManager.settings.downloadLocation = downloadLocation;
taskManager.settings.komga = new Komga(komgaBaseUrl, komgaAuthString, logger);
});
app.Run(); app.Run();
struct Settings class Settings
{ {
public Komga? komga { get; set; } public string downloadLocation { get; }
public string downloadLocation { get; set; } public Komga? komga { get; }
public string settingsFilePath { get; set; }
public Settings(TaskManager.SettingsData data)
{
this.settingsFilePath = data.settingsFilePath;
this.downloadLocation = data.downloadLocation;
this.komga = data.komga;
}
public Settings(string downloadLocation, string settingsFilePath, Komga komga) public Settings(TaskManager.SettingsData settings)
{ {
this.downloadLocation = downloadLocation; this.downloadLocation = settings.downloadLocation;
this.settingsFilePath = settingsFilePath; this.komga = settings.komga;
this.komga = komga;
}
public void Update(string? newDownloadLocation = null, string? newSettingsFilePath = null, Komga? newKomga= null)
{
this.downloadLocation = newDownloadLocation ?? this.downloadLocation;
this.settingsFilePath = newSettingsFilePath ?? this.settingsFilePath;
this.komga = newKomga ?? this.komga;
} }
} }

View File

@ -3,8 +3,8 @@
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:14826", "applicationUrl": "http://localhost:1716",
"sslPort": 44333 "sslPort": 44391
} }
}, },
"profiles": { "profiles": {
@ -12,7 +12,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "http://localhost:5119", "applicationUrl": "http://localhost:5177",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
@ -21,7 +21,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "https://localhost:7070;http://localhost:5119", "applicationUrl": "https://localhost:7036;http://localhost:5177",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

View File

@ -15,7 +15,14 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Logging\Logging.csproj" />
<ProjectReference Include="..\Tranga\Tranga.csproj" /> <ProjectReference Include="..\Tranga\Tranga.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.5" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project> </Project>

View File

@ -1 +0,0 @@
[{"reoccurrence":"00:00:00","lastExecuted":"2023-05-19T17:34:40.5349215+02:00","connectorName":"MangaDex","task":0,"publication":{"sortName":null,"description":null,"tags":null,"posterUrl":null,"year":null,"originalLanguage":null,"status":null,"folderName":null,"downloadUrl":null},"language":"en"}]

View File

@ -41,7 +41,7 @@ public static class Tranga_Cli
while(tmpPath is null) while(tmpPath is null)
tmpPath = Console.ReadLine(); tmpPath = Console.ReadLine();
if(tmpPath.Length > 0) if(tmpPath.Length > 0)
settings.downloadLocation = tmpPath; settings.UpdateSettings(pDownloadLocation: tmpPath, null);
Console.WriteLine($"Komga BaseURL [{settings.komga?.baseUrl}]:"); Console.WriteLine($"Komga BaseURL [{settings.komga?.baseUrl}]:");
string? tmpUrl = Console.ReadLine(); string? tmpUrl = Console.ReadLine();
@ -73,8 +73,8 @@ public static class Tranga_Cli
tmpPass += keyInfo.KeyChar; tmpPass += keyInfo.KeyChar;
} }
} while (key != ConsoleKey.Enter); } while (key != ConsoleKey.Enter);
settings.komga = new Komga(tmpUrl, tmpUser, tmpPass, logger); settings.UpdateSettings(null, new Komga(tmpUrl, tmpUser, tmpPass, logger));
} }
logger.WriteLine("Tranga_CLI", "Loaded."); logger.WriteLine("Tranga_CLI", "Loaded.");

View File

@ -4,10 +4,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga", ".\Tranga\Tranga.c
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-CLI", "Tranga-CLI\Tranga-CLI.csproj", "{4899E3B2-B259-479A-B43E-042D043E9501}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-CLI", "Tranga-CLI\Tranga-CLI.csproj", "{4899E3B2-B259-479A-B43E-042D043E9501}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-API", "Tranga-API\Tranga-API.csproj", "{6284C936-4E90-486B-BC46-0AFAD85AD8EE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logging", "Logging\Logging.csproj", "{415BE889-BB7D-426F-976F-8D977876A462}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logging", "Logging\Logging.csproj", "{415BE889-BB7D-426F-976F-8D977876A462}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-API", "Tranga-API\Tranga-API.csproj", "{48F4E495-75BC-4402-8E03-DEC5B79D7E83}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -22,13 +22,13 @@ Global
{4899E3B2-B259-479A-B43E-042D043E9501}.Debug|Any CPU.Build.0 = Debug|Any CPU {4899E3B2-B259-479A-B43E-042D043E9501}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.ActiveCfg = Release|Any CPU {4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.Build.0 = Release|Any CPU {4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.Build.0 = Release|Any CPU
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Release|Any CPU.Build.0 = Release|Any CPU
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.Build.0 = Debug|Any CPU {415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.Build.0 = Debug|Any CPU
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.ActiveCfg = Release|Any CPU {415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.ActiveCfg = Release|Any CPU
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.Build.0 = Release|Any CPU {415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.Build.0 = Release|Any CPU
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Debug|Any CPU.Build.0 = Debug|Any CPU
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Release|Any CPU.ActiveCfg = Release|Any CPU
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -58,14 +58,12 @@ public class MangaDex : Connector
: null; : null;
JsonArray altTitlesObject = attributes["altTitles"]!.AsArray(); JsonArray altTitlesObject = attributes["altTitles"]!.AsArray();
string[,] altTitles = new string[altTitlesObject.Count, 2]; Dictionary<string, string> altTitlesDict = new();
int titleIndex = 0;
foreach (JsonNode? altTitleNode in altTitlesObject) foreach (JsonNode? altTitleNode in altTitlesObject)
{ {
JsonObject altTitleObject = (JsonObject)altTitleNode!; JsonObject altTitleObject = (JsonObject)altTitleNode!;
string key = ((IDictionary<string, JsonNode?>)altTitleObject).Keys.ToArray()[0]; string key = ((IDictionary<string, JsonNode?>)altTitleObject).Keys.ToArray()[0];
altTitles[titleIndex, 0] = key; altTitlesDict.TryAdd(key, altTitleObject[key]!.GetValue<string>());
altTitles[titleIndex++, 1] = altTitleObject[key]!.GetValue<string>();
} }
JsonArray tagsObject = attributes["tags"]!.AsArray(); JsonArray tagsObject = attributes["tags"]!.AsArray();
@ -84,16 +82,14 @@ public class MangaDex : Connector
poster = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>(); poster = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>();
} }
Dictionary<string, string> linksDict = new();
string[,]? links = null; string[,]? links = null;
if (attributes.ContainsKey("links") && attributes["links"] is not null) if (attributes.ContainsKey("links") && attributes["links"] is not null)
{ {
JsonObject linksObject = attributes["links"]!.AsObject(); JsonObject linksObject = attributes["links"]!.AsObject();
links = new string[linksObject.Count, 2];
int linkIndex = 0;
foreach (string key in ((IDictionary<string, JsonNode?>)linksObject).Keys) foreach (string key in ((IDictionary<string, JsonNode?>)linksObject).Keys)
{ {
links[linkIndex, 0] = key; linksDict.Add(key, linksObject[key]!.GetValue<string>());
links[linkIndex++, 1] = linksObject[key]!.GetValue<string>();
} }
} }
@ -110,14 +106,13 @@ public class MangaDex : Connector
Publication pub = new Publication( Publication pub = new Publication(
title, title,
description, description,
altTitles, altTitlesDict,
tags.ToArray(), tags.ToArray(),
poster, poster,
links, linksDict,
year, year,
originalLanguage, originalLanguage,
status, status,
manga["id"]!.GetValue<string>(),
manga["id"]!.GetValue<string>() manga["id"]!.GetValue<string>()
); );
publications.Add(pub); //Add Publication (Manga) to result publications.Add(pub); //Add Publication (Manga) to result

View File

@ -9,34 +9,38 @@ public readonly struct Publication
{ {
public string sortName { get; } public string sortName { get; }
// ReSharper disable UnusedAutoPropertyAccessor.Global we need it, trust // ReSharper disable UnusedAutoPropertyAccessor.Global we need it, trust
[JsonIgnore]public string[,] altTitles { get; } [JsonIgnore]public Dictionary<string,string> altTitles { get; }
// ReSharper disable trice MemberCanBePrivate.Global, trust // ReSharper disable trice MemberCanBePrivate.Global, trust
public string? description { get; } public string? description { get; }
public string[] tags { get; } public string[] tags { get; }
public string? posterUrl { get; } public string? posterUrl { get; }
[JsonIgnore]public string[,]? links { get; } [JsonIgnore]public Dictionary<string,string> links { get; }
public int? year { get; } public int? year { get; }
public string? originalLanguage { get; } public string? originalLanguage { get; }
public string status { get; } public string status { get; }
public string folderName { get; } public string folderName { get; }
public string downloadUrl { get; } public string downloadUrl { get; }
public string internalId { get; } public string internalId { get; }
public Publication(string sortName, string? description, string[,] altTitles, string[] tags, string? posterUrl, string[,]? links, int? year, string? originalLanguage, string status, string downloadUrl, string internalId) public readonly struct ValueTuple
{
}
public Publication(string sortName, string? description, Dictionary<string,string> altTitles, string[] tags, string? posterUrl, Dictionary<string,string>? links, int? year, string? originalLanguage, string status, string downloadUrl)
{ {
this.sortName = sortName; this.sortName = sortName;
this.description = description; this.description = description;
this.altTitles = altTitles; this.altTitles = altTitles;
this.tags = tags; this.tags = tags;
this.posterUrl = posterUrl; this.posterUrl = posterUrl;
this.links = links; this.links = links ?? new Dictionary<string, string>();
this.year = year; this.year = year;
this.originalLanguage = originalLanguage; this.originalLanguage = originalLanguage;
this.status = status; this.status = status;
this.downloadUrl = downloadUrl; this.downloadUrl = downloadUrl;
this.folderName = string.Concat(sortName.Split(Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).ToArray())); this.folderName = string.Concat(sortName.Split(Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).ToArray()));
this.internalId = internalId; this.internalId = Guid.NewGuid().ToString();
} }
/// <returns>Serialized JSON String for series.json</returns> /// <returns>Serialized JSON String for series.json</returns>

View File

@ -17,7 +17,7 @@ public static class TaskExecutor
/// <param name="chapterCollection">Current chapterCollection to update</param> /// <param name="chapterCollection">Current chapterCollection to update</param>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <exception cref="ArgumentException">Is thrown when there is no Connector available with the name of the TrangaTask.connectorName</exception> /// <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, Logger? logger) public static void Execute(TaskManager taskManager, TrangaTask trangaTask, Logger? logger)
{ {
//Only execute task if it is not already being executed. //Only execute task if it is not already being executed.
if (trangaTask.state == TrangaTask.ExecutionState.Running) if (trangaTask.state == TrangaTask.ExecutionState.Running)
@ -37,13 +37,13 @@ public static class TaskExecutor
switch (trangaTask.task) switch (trangaTask.task)
{ {
case TrangaTask.Task.DownloadNewChapters: case TrangaTask.Task.DownloadNewChapters:
DownloadNewChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection); DownloadNewChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, ref taskManager._chapterCollection);
break; break;
case TrangaTask.Task.UpdateChapters: case TrangaTask.Task.UpdateChapters:
UpdateChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection); UpdateChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, ref taskManager._chapterCollection);
break; break;
case TrangaTask.Task.UpdatePublications: case TrangaTask.Task.UpdatePublications:
UpdatePublications(connector!, chapterCollection); UpdatePublications(connector!, ref taskManager._chapterCollection);
break; break;
case TrangaTask.Task.UpdateKomgaLibrary: case TrangaTask.Task.UpdateKomgaLibrary:
UpdateKomgaLibrary(taskManager); UpdateKomgaLibrary(taskManager);
@ -75,7 +75,7 @@ public static class TaskExecutor
/// </summary> /// </summary>
/// <param name="connector">Connector to receive Publications from</param> /// <param name="connector">Connector to receive Publications from</param>
/// <param name="chapterCollection"></param> /// <param name="chapterCollection"></param>
private static void UpdatePublications(Connector connector, Dictionary<Publication, List<Chapter>> chapterCollection) private static void UpdatePublications(Connector connector, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{ {
Publication[] publications = connector.GetPublications(); Publication[] publications = connector.GetPublications();
foreach (Publication publication in publications) foreach (Publication publication in publications)
@ -90,9 +90,9 @@ public static class TaskExecutor
/// <param name="publication">Publication to check</param> /// <param name="publication">Publication to check</param>
/// <param name="language">Language to receive chapters for</param> /// <param name="language">Language to receive chapters for</param>
/// <param name="chapterCollection"></param> /// <param name="chapterCollection"></param>
private static void DownloadNewChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection) private static void DownloadNewChapters(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{ {
List<Chapter> newChapters = UpdateChapters(connector, publication, language, chapterCollection); List<Chapter> newChapters = UpdateChapters(connector, publication, language, ref chapterCollection);
connector.DownloadCover(publication); connector.DownloadCover(publication);
//Check if Publication already has a Folder and a series.json //Check if Publication already has a Folder and a series.json
@ -116,7 +116,7 @@ public static class TaskExecutor
/// <param name="language">Language to receive chapters for</param> /// <param name="language">Language to receive chapters for</param>
/// <param name="chapterCollection"></param> /// <param name="chapterCollection"></param>
/// <returns>List of Chapters that were previously not in collection</returns> /// <returns>List of Chapters that were previously not in collection</returns>
private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection) private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection)
{ {
List<Chapter> newChaptersList = new(); List<Chapter> newChaptersList = new();
chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection

View File

@ -10,7 +10,7 @@ namespace Tranga;
/// </summary> /// </summary>
public class TaskManager public class TaskManager
{ {
private readonly Dictionary<Publication, List<Chapter>> _chapterCollection = new(); public Dictionary<Publication, List<Chapter>> _chapterCollection = new();
private readonly HashSet<TrangaTask> _allTasks; private readonly HashSet<TrangaTask> _allTasks;
private bool _continueRunning = true; private bool _continueRunning = true;
private readonly Connector[] _connectors; private readonly Connector[] _connectors;
@ -43,6 +43,15 @@ public class TaskManager
taskChecker.Start(); taskChecker.Start();
} }
public void UpdateSettings(string? downloadLocation, string? komgaUrl, string? komgaAuth)
{
Komga? komga = null;
if (komgaUrl is not null && komgaAuth is not null)
komga = new Komga(komgaUrl, komgaAuth, null);
settings.UpdateSettings(downloadLocation, komga);
ExportData();
}
public TaskManager(SettingsData settings, Logger? logger = null) public TaskManager(SettingsData settings, Logger? logger = null)
{ {
this.logger = logger; this.logger = logger;
@ -106,7 +115,7 @@ public class TaskManager
logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}"); logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}");
Task t = new Task(() => Task t = new Task(() =>
{ {
TaskExecutor.Execute(this, task, this._chapterCollection, logger); TaskExecutor.Execute(this, task, logger);
}); });
t.Start(); t.Start();
} }
@ -154,7 +163,7 @@ public class TaskManager
trangaTask.publication?.downloadUrl == publication?.downloadUrl)) trangaTask.publication?.downloadUrl == publication?.downloadUrl))
{ {
if(task != TrangaTask.Task.UpdatePublications) if(task != TrangaTask.Task.UpdatePublications)
_chapterCollection.Add((Publication)publication!, new List<Chapter>()); _chapterCollection.TryAdd((Publication)publication!, new List<Chapter>());
_allTasks.Add(newTask); _allTasks.Add(newTask);
} }
} }
@ -227,6 +236,17 @@ public class TaskManager
_allTasks.CopyTo(ret); _allTasks.CopyTo(ret);
return ret; return ret;
} }
public Publication[] GetPublicationsFromConnector(Connector connector, string? title = null)
{
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>());
}
return ret;
}
/// <returns>All added Publications</returns> /// <returns>All added Publications</returns>
public Publication[] GetAllPublications() public Publication[] GetAllPublications()
@ -290,16 +310,19 @@ public class TaskManager
private void ExportData() private void ExportData()
{ {
logger?.WriteLine(this.GetType().ToString(), $"Exporting data to {settings.settingsFilePath}"); logger?.WriteLine(this.GetType().ToString(), $"Exporting data to {settings.settingsFilePath}");
string serializedData = JsonConvert.SerializeObject(settings); string serializedData = JsonConvert.SerializeObject(settings);
File.WriteAllText(settings.settingsFilePath, serializedData); File.WriteAllText(settings.settingsFilePath, serializedData);
} }
public class SettingsData public class SettingsData
{ {
public string downloadLocation { get; set; } public string downloadLocation { get; private set; }
public string settingsFilePath { get; } public string settingsFilePath { get; }
public Komga? komga { get; set; } public Komga? komga { get; private set; }
public HashSet<TrangaTask> allTasks { get; } public HashSet<TrangaTask> allTasks { get; }
public SettingsData(string downloadLocation, string? settingsFilePath, Komga? komga, HashSet<TrangaTask> allTasks) public SettingsData(string downloadLocation, string? settingsFilePath, Komga? komga, HashSet<TrangaTask> allTasks)
@ -311,5 +334,13 @@ public class TaskManager
this.komga = komga; this.komga = komga;
this.allTasks = allTasks; this.allTasks = allTasks;
} }
public void UpdateSettings(string? pDownloadLocation, Komga? pKomga)
{
if(pDownloadLocation is not null)
this.downloadLocation = pDownloadLocation;
if(pKomga is not null)
this.komga = pKomga;
}
} }
} }