2
0

Compare commits

..

19 Commits

Author SHA1 Message Date
21e56a949f Added API 2023-05-19 17:36:27 +02:00
aa2ab0e1d0 Added GetAllPublications to TaskManager. 2023-05-19 17:36:15 +02:00
f0a4bc3e99 AddTask now takes ConnectorName instead of object 2023-05-19 17:36:03 +02:00
b0f6441599 Changed MangaDex name to MangaDex 2023-05-19 17:35:29 +02:00
0df7e7ed31 Missing bracket. 2023-05-19 16:36:02 +02:00
e5d7fdf9b4 ExportTasks every time a task is added/removed 2023-05-19 16:35:53 +02:00
d358147673 Moved lastExecuted update to TaskExecutor.Execute 2023-05-19 16:35:27 +02:00
dd58efce06 Working TaskManager and Tasks 2023-05-19 16:27:56 +02:00
cfaf8064cc Check if cover already exists in publication. 2023-05-19 16:27:30 +02:00
9baa9fb8f0 Amended SaveSeriesInfo to not constantly rewrite info 2023-05-19 16:25:08 +02:00
e3aab83dfb When downloading new Chapters, download cover and series info. 2023-05-19 16:24:05 +02:00
afe36ab2ef Switch to Newtonsoft.Json for serialization 2023-05-19 16:23:37 +02:00
0afbcd9bbf Removed field Connector from Publication as it was not needed. 2023-05-19 16:21:59 +02:00
9aa822b900 Created SaveSeriesInfo in Connector 2023-05-19 16:19:10 +02:00
24c58e9e22 Added methods to Add/Remove tasks 2023-05-19 14:15:17 +02:00
f42a0a0017 Added Import/Export-tasks functionality. 2023-05-19 14:15:07 +02:00
6de6d060c4 Rewrite Task-Structure for serialization.
TrangaTask include information on what to execute where, do not execute tasks.
TaskExecutor executes Tasks on information from TrangaTask
2023-05-19 14:00:30 +02:00
3d9e3d019d Future use: Import and export task-list. 2023-05-19 13:59:26 +02:00
741cf88f7f Remove not used methods 2023-05-19 13:58:57 +02:00
16 changed files with 484 additions and 108 deletions

20
Tranga-API/Dockerfile Normal file
View File

@ -0,0 +1,20 @@
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["Tranga-API/Tranga-API.csproj", "Tranga-API/"]
RUN dotnet restore "Tranga-API/Tranga-API.csproj"
COPY . .
WORKDIR "/src/Tranga-API"
RUN dotnet build "Tranga-API.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Tranga-API.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Tranga-API.dll"]

51
Tranga-API/Program.cs Normal file
View File

@ -0,0 +1,51 @@
using System.Text.Json;
using Tranga;
using Tranga.Connectors;
TaskManager taskManager = new TaskManager(Directory.GetCurrentDirectory());
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/GetConnectors", () => JsonSerializer.Serialize(taskManager.GetAvailableConnectors().Values.ToArray()));
app.MapGet("/GetPublications", (string connectorName, string? title) =>
{
Connector? connector = taskManager.GetAvailableConnectors().FirstOrDefault(c => c.Key == connectorName).Value;
if (connector is null)
JsonSerializer.Serialize($"Connector {connectorName} is not a known connector.");
Publication[] publications;
if (title is not null)
publications = connector.GetPublications(title);
else
publications = connector.GetPublications();
return JsonSerializer.Serialize(publications);
});
app.MapGet("/ListTasks", () => JsonSerializer.Serialize(taskManager.GetAllTasks()));
app.MapGet("/CreateTask",
(TrangaTask.Task task, string connectorName, string? publicationName, TimeSpan reoccurrence, string language) =>
{
Publication? publication =
taskManager.GetAllPublications().FirstOrDefault(pub => pub.downloadUrl == publicationName);
if (publication is null)
JsonSerializer.Serialize($"Publication {publicationName} is unknown.");
taskManager.AddTask(task, connectorName, publication, reoccurrence, language);
JsonSerializer.Serialize("Success");
});
app.MapGet("/RemoveTask", (TrangaTask.Task task, string connector, string? publicationName) =>
{
Publication? publication =
taskManager.GetAllPublications().FirstOrDefault(pub => pub.downloadUrl == publicationName);
if (publication is null)
JsonSerializer.Serialize($"Publication {publicationName} is unknown.");
taskManager.RemoveTask(task, connector, publication);
JsonSerializer.Serialize("Success");
});
app.Run();

View File

@ -0,0 +1,37 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:14826",
"sslPort": 44333
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5119",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7070;http://localhost:5119",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Tranga_API</RootNamespace>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Tranga\Tranga.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

1
Tranga-API/tasks.json Normal file
View File

@ -0,0 +1 @@
[{"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

@ -7,70 +7,198 @@ public static class Tranga_Cli
{
public static void Main(string[] args)
{
Console.WriteLine("Output folder path (D:):");
Console.WriteLine("Output folder path [standard D:]:");
string? folderPath = Console.ReadLine();
while(folderPath is null )
folderPath = Console.ReadLine();
if (folderPath.Length < 1)
folderPath = "D:";
DownloadNow(folderPath);
Console.Write("Mode (D: downloadNow, T: tasks):");
ConsoleKeyInfo mode = Console.ReadKey();
while (mode.Key != ConsoleKey.D && mode.Key != ConsoleKey.T)
mode = Console.ReadKey();
Console.WriteLine();
if(mode.Key == ConsoleKey.D)
DownloadNow(folderPath);
else if (mode.Key == ConsoleKey.T)
TaskMode(folderPath);
}
private static void TaskMode(string folderPath)
{
TaskManager taskManager = new TaskManager(folderPath);
ConsoleKey selection = ConsoleKey.NoName;
int menu = 0;
while (selection != ConsoleKey.Escape && selection != ConsoleKey.Q)
{
switch (menu)
{
case 1:
PrintTasks(taskManager);
Console.WriteLine("Press any key.");
Console.ReadKey();
menu = 0;
break;
case 2:
Connector connector = SelectConnector(folderPath, taskManager.GetAvailableConnectors().Values.ToArray());
TrangaTask.Task task = SelectTask();
Publication? publication = null;
if(task != TrangaTask.Task.UpdatePublications)
publication = SelectPublication(connector);
TimeSpan reoccurrence = SelectReoccurence();
taskManager.AddTask(task, connector.name, publication, reoccurrence, "en");
Console.WriteLine($"{task} - {connector.name} - {publication?.sortName}");
Console.WriteLine("Press any key.");
Console.ReadKey();
menu = 0;
break;
case 3:
RemoveTask(taskManager);
Console.WriteLine("Press any key.");
Console.ReadKey();
menu = 0;
break;
default:
selection = Menu(folderPath);
switch (selection)
{
case ConsoleKey.L:
menu = 1;
break;
case ConsoleKey.C:
menu = 2;
break;
case ConsoleKey.D:
menu = 3;
break;
default:
menu = 0;
break;
}
break;
}
}
taskManager.Shutdown();
}
private static ConsoleKey Menu(string folderPath)
{
Console.Clear();
Console.WriteLine($"Download Folder: {folderPath}");
Console.WriteLine("Select Option:");
Console.WriteLine("L: List tasks");
Console.WriteLine("C: Create Task");
Console.WriteLine("D: Delete Task");
Console.WriteLine("Q: Exit with saving");
ConsoleKey selection = Console.ReadKey().Key;
Console.WriteLine();
return selection;
}
private static int PrintTasks(TaskManager taskManager)
{
Console.Clear();
TrangaTask[] tasks = taskManager.GetAllTasks();
int tIndex = 0;
Console.WriteLine("Tasks:");
foreach(TrangaTask trangaTask in tasks)
Console.WriteLine($"{tIndex++}: {trangaTask.task} - {trangaTask.publication?.sortName} - {trangaTask.connectorName}");
return tasks.Length;
}
private static void RemoveTask(TaskManager taskManager)
{
int length = PrintTasks(taskManager);
TrangaTask[] tasks = taskManager.GetAllTasks();
Console.WriteLine($"Select Task (0-{length - 1}):");
string? selectedTask = Console.ReadLine();
while(selectedTask is null || selectedTask.Length < 1)
selectedTask = Console.ReadLine();
int selectedTaskIndex = Convert.ToInt32(selectedTask);
taskManager.RemoveTask(tasks[selectedTaskIndex].task, tasks[selectedTaskIndex].connectorName, tasks[selectedTaskIndex].publication);
}
private static TrangaTask.Task SelectTask()
{
Console.Clear();
string[] taskNames = Enum.GetNames<TrangaTask.Task>();
int tIndex = 0;
Console.WriteLine("Available Tasks:");
foreach (string taskName in taskNames)
Console.WriteLine($"{tIndex++}: {taskName}");
Console.WriteLine($"Select Task (0-{taskNames.Length - 1}):");
string? selectedTask = Console.ReadLine();
while(selectedTask is null || selectedTask.Length < 1)
selectedTask = Console.ReadLine();
int selectedTaskIndex = Convert.ToInt32(selectedTask);
string selectedTaskName = taskNames[selectedTaskIndex];
return Enum.Parse<TrangaTask.Task>(selectedTaskName);
}
private static TimeSpan SelectReoccurence()
{
return TimeSpan.FromSeconds(30); //TODO
}
private static void DownloadNow(string folderPath)
{
Connector connector = SelectConnector(folderPath);
Console.WriteLine("Search query (leave empty for all):");
string? query = Console.ReadLine();
Publication publication = SelectPublication(connector);
Publication[] publications = connector.GetPublications(query ?? "");
Publication selectedPub = SelectPublication(publications);
Chapter[] allChapteres = connector.GetChapters(selectedPub, "en");
Chapter[] downloadChapters = SelectChapters(allChapteres);
Chapter[] downloadChapters = SelectChapters(connector, publication);
if (downloadChapters.Length > 0)
{
connector.DownloadCover(selectedPub);
File.WriteAllText(Path.Join(folderPath, selectedPub.folderName, "series.json"),selectedPub.GetSeriesInfo());
connector.DownloadCover(publication);
connector.SaveSeriesInfo(publication);
}
foreach (Chapter chapter in downloadChapters)
{
Console.WriteLine($"Downloading {selectedPub.sortName} V{chapter.volumeNumber}C{chapter.chapterNumber}");
connector.DownloadChapter(selectedPub, chapter);
Console.WriteLine($"Downloading {publication.sortName} V{chapter.volumeNumber}C{chapter.chapterNumber}");
connector.DownloadChapter(publication, chapter);
}
}
private static Connector SelectConnector(string folderPath)
private static Connector SelectConnector(string folderPath, Connector[]? availableConnectors = null)
{
Console.WriteLine("Select Connector:");
Console.WriteLine("0: MangaDex");
Console.Clear();
Connector[] connectors = availableConnectors ?? new Connector[] { new MangaDex(folderPath) };
int cIndex = 0;
Console.WriteLine("Connectors:");
foreach (Connector connector in connectors)
Console.WriteLine($"{cIndex++}: {connector.name}");
Console.WriteLine($"Select Connector (0-{connectors.Length - 1}):");
string? selectedConnector = Console.ReadLine();
while(selectedConnector is null || selectedConnector.Length < 1)
selectedConnector = Console.ReadLine();
int selectedConnectorIndex = Convert.ToInt32(selectedConnector);
Connector connector;
switch (selectedConnectorIndex)
{
case 0:
connector = new MangaDex(folderPath);
break;
default:
connector = new MangaDex(folderPath);
break;
}
return connector;
return connectors[selectedConnectorIndex];
}
private static Publication SelectPublication(Publication[] publications)
private static Publication SelectPublication(Connector connector)
{
Console.Clear();
Console.WriteLine($"Connector: {connector.name}");
Console.WriteLine("Publication search query (leave empty for all):");
string? query = Console.ReadLine();
Publication[] publications = connector.GetPublications(query ?? "");
int pIndex = 0;
Console.WriteLine("Publications:");
foreach(Publication publication in publications)
Console.WriteLine($"{pIndex++}: {publication.sortName}");
Console.WriteLine($"Select publication to Download (0-{publications.Length - 1}):");
@ -81,9 +209,14 @@ public static class Tranga_Cli
return publications[Convert.ToInt32(selected)];
}
private static Chapter[] SelectChapters(Chapter[] chapters)
private static Chapter[] SelectChapters(Connector connector, Publication publication)
{
Console.Clear();
Console.WriteLine($"Connector: {connector.name} Publication: {publication.sortName}");
Chapter[] chapters = connector.GetChapters(publication, "en");
int cIndex = 0;
Console.WriteLine("Chapters:");
foreach (Chapter ch in chapters)
{
string name = cIndex.ToString();

View File

@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga", ".\Tranga\Tranga.c
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-CLI", "Tranga-CLI\Tranga-CLI.csproj", "{4899E3B2-B259-479A-B43E-042D043E9501}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-API", "Tranga-API\Tranga-API.csproj", "{6284C936-4E90-486B-BC46-0AFAD85AD8EE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -18,5 +20,9 @@ Global
{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.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
EndGlobalSection
EndGlobal

View File

@ -42,6 +42,13 @@ public abstract class Connector
ZipFile.CreateFromDirectory(tempFolder, fullPath);
}
public void SaveSeriesInfo(Publication publication)
{
string seriesInfoPath = Path.Join(downloadLocation, publication.folderName, "series.json");
if(!File.Exists(seriesInfoPath))
File.WriteAllText(seriesInfoPath,publication.GetSeriesInfo());
}
internal class DownloadClient
{
private readonly TimeSpan _requestSpeed;

View File

@ -10,7 +10,7 @@ public class MangaDex : Connector
public MangaDex(string downloadLocation) : base(downloadLocation)
{
name = "MangaDex.org";
name = "MangaDex";
}
public override Publication[] GetPublications(string publicationTitle = "")
@ -102,7 +102,6 @@ public class MangaDex : Connector
year,
originalLanguage,
status,
this,
manga["id"]!.GetValue<string>()
);
publications.Add(pub);
@ -188,6 +187,12 @@ public class MangaDex : Connector
public override void DownloadCover(Publication publication)
{
string publicationPath = Path.Join(downloadLocation, publication.folderName);
DirectoryInfo dirInfo = new DirectoryInfo(publicationPath);
foreach(FileInfo fileInfo in dirInfo.EnumerateFiles())
if (fileInfo.Name.Contains("cover."))
return;
DownloadClient.RequestResult requestResult = _downloadClient.MakeRequest($"https://api.mangadex.org/cover/{publication.posterUrl}");
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
if (result is null)

View File

@ -1,24 +1,22 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
namespace Tranga;
public struct Publication
{
public string sortName { get; }
public string[,] altTitles { get; }
[JsonIgnore]public string[,] altTitles { get; }
public string? description { get; }
public string[] tags { get; }
public string? posterUrl { get; }
public string[,]? links { get; }
[JsonIgnore]public string[,]? links { get; }
public int? year { get; }
public string? originalLanguage { get; }
public string status { get; }
public string folderName { get; }
public Connector connector { get; }
public string downloadUrl { get; }
public Publication(string sortName, string? description, string[,] altTitles, string[] tags, string? posterUrl, string[,]? links, int? year, string? originalLanguage, string status, Connector connector, string downloadUrl)
public Publication(string sortName, string? description, string[,] altTitles, string[] tags, string? posterUrl, string[,]? links, int? year, string? originalLanguage, string status, string downloadUrl)
{
this.sortName = sortName;
this.description = description;
@ -29,7 +27,6 @@ public struct Publication
this.year = year;
this.originalLanguage = originalLanguage;
this.status = status;
this.connector = connector;
this.downloadUrl = downloadUrl;
this.folderName = string.Concat(sortName.Split(Path.GetInvalidPathChars()));
}
@ -37,7 +34,7 @@ public struct Publication
public string GetSeriesInfo()
{
SeriesInfo si = new (new Metadata(this.sortName, this.year.ToString() ?? string.Empty, this.status, this.description ?? ""));
return JsonSerializer.Serialize(si, JsonSerializerOptions.Default);
return System.Text.Json.JsonSerializer.Serialize(si);
}
internal struct SeriesInfo

55
Tranga/TaskExecutor.cs Normal file
View File

@ -0,0 +1,55 @@
namespace Tranga;
public static class TaskExecutor
{
public static void Execute(Connector[] connectors, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection)
{
Connector? connector = connectors.FirstOrDefault(c => c.name == trangaTask.connectorName);
if (connector is null)
throw new ArgumentException($"Connector {trangaTask.connectorName} is not a known connector.");
trangaTask.lastExecuted = DateTime.Now;
switch (trangaTask.task)
{
case TrangaTask.Task.DownloadNewChapters:
DownloadNewChapters(connector, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
break;
case TrangaTask.Task.UpdateChapters:
UpdateChapters(connector, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
break;
case TrangaTask.Task.UpdatePublications:
UpdatePublications(connector, chapterCollection);
break;
}
}
private static void UpdatePublications(Connector connector, Dictionary<Publication, List<Chapter>> chapterCollection)
{
Publication[] publications = connector.GetPublications();
foreach (Publication publication in publications)
chapterCollection.TryAdd(publication, new List<Chapter>());
}
private static void DownloadNewChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection)
{
List<Chapter> newChapters = UpdateChapters(connector, publication, language, chapterCollection);
foreach(Chapter newChapter in newChapters)
connector.DownloadChapter(publication, newChapter);
connector.DownloadCover(publication);
connector.SaveSeriesInfo(publication);
}
private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection)
{
List<Chapter> newChaptersList = new();
if (!chapterCollection.ContainsKey(publication))
return newChaptersList;
List<Chapter> currentChapters = chapterCollection[publication];
Chapter[] newChapters = connector.GetChapters(publication, language);
newChaptersList = newChapters.ToList()
.ExceptBy(currentChapters.Select(cChapter => cChapter.url), nChapter => nChapter.url).ToList();
return newChaptersList;
}
}

View File

@ -1,15 +1,22 @@
namespace Tranga;
using Newtonsoft.Json;
using Tranga.Connectors;
namespace Tranga;
public class TaskManager
{
private readonly Dictionary<Publication, Chapter[]> _chapterCollection;
private readonly Dictionary<Publication, List<Chapter>> _chapterCollection;
private readonly HashSet<TrangaTask> _allTasks;
private bool _continueRunning = true;
private readonly Connector[] connectors;
private readonly string folderPath;
public TaskManager()
public TaskManager(string folderPath)
{
this.folderPath = folderPath;
this.connectors = new Connector[]{ new MangaDex(folderPath) };
_chapterCollection = new();
_allTasks = new ();
_allTasks = ImportTasks(Directory.GetCurrentDirectory());
Thread taskChecker = new(TaskCheckerThread);
taskChecker.Start();
}
@ -18,37 +25,81 @@ public class TaskManager
{
while (_continueRunning)
{
foreach (TrangaTask task in _allTasks.Where(trangaTask => (DateTime.Now - trangaTask.lastExecuted) > trangaTask.reoccurrence))
foreach (TrangaTask task in _allTasks)
{
if (!task.lastExecutedSuccessfully)
{
task.Abort();
//Add logging that task has failed
}
task.Execute();
if(task.ShouldExecute())
TaskExecutor.Execute(this.connectors, task, this._chapterCollection);
}
Thread.Sleep(1000);
}
}
public bool PublicationAlreadyAdded(Publication publication)
public void AddTask(TrangaTask.Task task, string connectorName, Publication? publication, TimeSpan reoccurrence,
string language = "")
{
throw new NotImplementedException();
//TODO fuzzy check publications
Connector? connector = connectors.FirstOrDefault(c => c.name == connectorName);
if (connector is null)
throw new ArgumentException($"Connector {connectorName} is not a known connector.");
if (!_allTasks.Any(trangaTask => trangaTask.task != task && trangaTask.connectorName != connector.name &&
trangaTask.publication?.downloadUrl != publication?.downloadUrl))
{
_allTasks.Add(new TrangaTask(connector.name, task, publication, reoccurrence, language));
ExportTasks(Directory.GetCurrentDirectory());
}
}
public Publication[] GetAddedPublications()
public void RemoveTask(TrangaTask.Task task, string connectorName, Publication? publication)
{
throw new NotImplementedException();
_allTasks.RemoveWhere(trangaTask =>
trangaTask.task == task && trangaTask.connectorName == connectorName &&
trangaTask.publication?.downloadUrl == publication?.downloadUrl);
ExportTasks(Directory.GetCurrentDirectory());
}
public TrangaTask[] GetTasks()
public Dictionary<string, Connector> GetAvailableConnectors()
{
return _allTasks.ToArray();
return this.connectors.ToDictionary(connector => connector.name, connector => connector);
}
public TrangaTask[] GetAllTasks()
{
TrangaTask[] ret = new TrangaTask[_allTasks.Count];
_allTasks.CopyTo(ret);
return ret;
}
public Publication[] GetAllPublications()
{
return this._chapterCollection.Keys.ToArray();
}
public void Shutdown()
{
_continueRunning = false;
ExportTasks(Directory.GetCurrentDirectory());
}
public HashSet<TrangaTask> ImportTasks(string importFolderPath)
{
string filePath = Path.Join(importFolderPath, "tasks.json");
if (!File.Exists(filePath))
return new HashSet<TrangaTask>();
string toRead = File.ReadAllText(filePath);
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();
}
public void ExportTasks(string exportFolderPath)
{
string filePath = Path.Join(exportFolderPath, "tasks.json");
string toWrite = JsonConvert.SerializeObject(_allTasks.ToArray());
File.WriteAllText(filePath,toWrite);
}
}

View File

@ -6,4 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>

View File

@ -2,63 +2,34 @@
public class TrangaTask
{
private readonly Action _taskAction;
private Task? _task;
public bool lastExecutedSuccessfully => _task is not null && _task.IsCompleted;
public TimeSpan reoccurrence { get; }
public DateTime lastExecuted { get; private set; }
public DateTime lastExecuted { get; set; }
public string connectorName { get; }
public Task task { get; }
public Publication? publication { get; }
public string language { get; }
public TrangaTask(Action taskAction, TimeSpan reoccurrence)
public TrangaTask(string connectorName, Task task, Publication? publication, TimeSpan reoccurrence, string language = "")
{
this._taskAction = taskAction;
if (task != Task.UpdatePublications && publication is null)
throw new ArgumentException($"Publication has to be not null for task {task}");
this.publication = publication;
this.reoccurrence = reoccurrence;
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
this.connectorName = connectorName;
this.task = task;
this.language = language;
}
public void Abort()
public bool ShouldExecute()
{
if(_task is not null && !_task.IsCompleted)
_task.Dispose();
return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence;
}
public void Execute()
public enum Task
{
lastExecuted = DateTime.Now;
_task = new (_taskAction);
_task.Start();
}
public static TrangaTask CreateDownloadChapterTask(Connector connector, Publication publication, Chapter chapter, TimeSpan reoccurrence)
{
void TaskAction()
{
connector.DownloadChapter(publication, chapter);
}
return new TrangaTask(TaskAction, reoccurrence);
}
public static TrangaTask CreateUpdateChaptersTask(ref Dictionary<Publication, Chapter[]> chapterCollection, Connector connector, Publication publication, string language, TimeSpan reoccurrence)
{
Dictionary<Publication, Chapter[]> pChapterCollection = chapterCollection;
void TaskAction()
{
Chapter[] chapters = connector.GetChapters(publication, language);
if(pChapterCollection.TryAdd(publication, chapters))
pChapterCollection[publication] = chapters;
}
return new TrangaTask(TaskAction, reoccurrence);
}
public static TrangaTask CreateUpdatePublicationsTask(ref Dictionary<Publication, Chapter[]> chapterCollection, Connector connector, TimeSpan reoccurrence)
{
Dictionary<Publication, Chapter[]> pChapterCollection = chapterCollection;
void TaskAction()
{
Publication[] publications = connector.GetPublications();
foreach (Publication publication in publications)
pChapterCollection.TryAdd(publication, Array.Empty<Chapter>());
}
return new TrangaTask(TaskAction, reoccurrence);
UpdatePublications,
UpdateChapters,
DownloadNewChapters
}
}