40 Commits

Author SHA1 Message Date
7612411917 #33 Update Website 2023-06-03 16:25:04 +02:00
ed1402b5ec TrangaSettings Return libraryManageres on serialization 2023-06-03 16:24:54 +02:00
5adaee4821 redundant calls 2023-06-03 16:24:30 +02:00
2d82fe1489 libraryType in constructor 2023-06-03 16:24:14 +02:00
783fd8129e API: Kavita Auth #33 2023-06-03 15:40:26 +02:00
4f29eff48e Kavita authorization 2023-06-03 15:39:48 +02:00
e0e7abb62b #33 Added custom serializer for LibraryManager
Added Code for Kavita
2023-06-03 15:32:54 +02:00
ae63a216a5 unnecessary params 2023-06-03 15:27:35 +02:00
5d98295c59 #33 Preparation:
TrangaSettings now stores Hashset of LibraryManagers
2023-06-03 15:17:08 +02:00
0c580933f9 #33 Preparation:
Abstracted class Komga into LibraryManager
Fixed logger not attaching to LibraryManager
2023-06-03 15:02:15 +02:00
06f735aadd #32 API endpoint 2023-06-01 23:08:43 +02:00
439d69d8e0 Sanitization Manganto 2023-06-01 22:59:51 +02:00
933df58712 Moved publicationFolder creation to Publication with Permissions 2023-06-01 22:59:04 +02:00
165bbc412e Adjusted Manganato ratelimit 2023-06-01 22:49:20 +02:00
6158fa072b File permissions 2023-06-01 22:32:11 +02:00
0d3799e00d Fix Bug when strings where shorter than 25 characters on logger.writeline
Fixed CLI output
2023-06-01 22:27:37 +02:00
e977bed5a5 #32 formatting length 2023-06-01 22:14:00 +02:00
cacd5fede2 removed unnecessary todo 2023-06-01 22:06:10 +02:00
1bca99cb6a #32 Added progress tracking to task (internal and log use for now) 2023-06-01 22:05:48 +02:00
15fc367263 logging 2023-06-01 21:16:57 +02:00
8bb6fb902b File Permissions 2023-06-01 18:28:58 +02:00
a57903cd5a readme update 2023-06-01 16:04:21 +02:00
1cd819b21d update docker-compose 2023-06-01 15:40:14 +02:00
27afedc1b4 year in series.json 2023-06-01 15:25:26 +02:00
fac0a3f7eb resolves #2 2023-06-01 15:08:32 +02:00
03ca480fe8 remove empty lines at start of description 2023-06-01 14:59:09 +02:00
c2915468a5 status .tolower 2023-06-01 14:58:58 +02:00
8805c53cb8 wrong url for manga info page 2023-06-01 13:37:06 +02:00
adbbe3f6cc logs 2023-06-01 13:27:58 +02:00
14b694d3be Description value duplicate #2 2023-06-01 13:25:58 +02:00
72ce75c6e0 #2 Multiple alt titles 2023-06-01 13:18:26 +02:00
8381951168 #2 First Attempt 2023-06-01 13:13:53 +02:00
b24032d124 remove env var 2023-06-01 11:29:47 +02:00
8bc23f7c69 Instead of relying on concreate tasks to do chores, create method in abstract class that calls the BL in concrete class and does chores before and after execution 2023-06-01 10:35:23 +02:00
48b7371a18 Issue missing parameter 2023-05-31 22:34:13 +02:00
61ecefb615 Logging and Chores in abstract class 2023-05-31 22:32:37 +02:00
8ff65bf400 compatibility with older tasks.json 2023-05-31 22:26:53 +02:00
932057cca0 update execution time 2023-05-31 22:20:33 +02:00
67d06cd887 resolves #23 website filter 2023-05-31 22:16:14 +02:00
cbb012a659 alt and label 2023-05-31 22:16:01 +02:00
25 changed files with 762 additions and 310 deletions

View File

@ -54,6 +54,7 @@
Tranga can download Chapters and Metadata from Scanlation sites such as Tranga can download Chapters and Metadata from Scanlation sites such as
- [MangaDex.org](https://mangadex.org/) - [MangaDex.org](https://mangadex.org/)
- [Manganato.com](https://manganato.com/)
and automatically start updates in [Komga](https://komga.org/) to import them. and automatically start updates in [Komga](https://komga.org/) to import them.
@ -114,7 +115,7 @@ Wherever you are mounting `/usr/share/Tranga-API` you also need to mount that sa
- [x] Web-UI #1 - [x] Web-UI #1
- [ ] More Connectors - [ ] More Connectors
- [ ] Manganato #2 - [x] Manganato #2
- [ ] ? - [ ] ?
See the [open issues](https://git.bernloehr.eu/glax/Tranga/issues) for a full list of proposed features (and known issues). See the [open issues](https://git.bernloehr.eu/glax/Tranga/issues) for a full list of proposed features (and known issues).

View File

@ -15,9 +15,9 @@ logger.WriteLine("Tranga", "Loading settings.");
TrangaSettings settings; TrangaSettings settings;
if (File.Exists(settingsFilePath)) if (File.Exists(settingsFilePath))
settings = TrangaSettings.LoadSettings(settingsFilePath); settings = TrangaSettings.LoadSettings(settingsFilePath, logger);
else else
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, null); settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>());
Directory.CreateDirectory(settings.workingDirectory); Directory.CreateDirectory(settings.workingDirectory);
Directory.CreateDirectory(settings.downloadLocation); Directory.CreateDirectory(settings.downloadLocation);
@ -51,8 +51,6 @@ builder.Services.AddCors(options =>
var app = builder.Build(); var app = builder.Build();
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(); app.UseSwaggerUI();
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors(corsHeader); app.UseCors(corsHeader);
@ -105,6 +103,31 @@ app.MapGet("/Tasks/Get", (string taskType, string? connectorName, string? search
} }
}); });
app.MapGet("/Tasks/GetTaskProgress", (string taskType, string? connectorName, string? publicationId) =>
{
try
{
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
TrangaTask? task = null;
if (connectorName is null || publicationId is null)
task = taskManager.GetAllTasks().FirstOrDefault(tTask =>
tTask.task == pTask);
else
task = taskManager.GetAllTasks().FirstOrDefault(tTask =>
tTask.task == pTask && tTask.publication?.internalId == publicationId &&
tTask.connectorName == connectorName);
if (task is null)
return -1f;
return task.progress;
}
catch (ArgumentException)
{
return -1f;
}
});
app.MapPost("/Tasks/Start", (string taskType, string? connectorName, string? publicationId) => app.MapPost("/Tasks/Start", (string taskType, string? connectorName, string? publicationId) =>
{ {
try try
@ -186,6 +209,8 @@ app.MapDelete("/Queue/Dequeue", (string taskType, string? connectorName, string?
app.MapGet("/Settings/Get", () => taskManager.settings); app.MapGet("/Settings/Get", () => taskManager.settings);
app.MapPost("/Settings/Update", (string? downloadLocation, string? komgaUrl, string? komgaAuth) => taskManager.UpdateSettings(downloadLocation, komgaUrl, komgaAuth) ); app.MapPost("/Settings/Update",
(string? downloadLocation, string? komgaUrl, string? komgaAuth, string? kavitaUrl, string? kavitaApiKey) =>
taskManager.UpdateSettings(downloadLocation, komgaUrl, komgaAuth, kavitaUrl, kavitaApiKey));
app.Run(); app.Run();

View File

@ -12,26 +12,17 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "http://localhost:5177", "applicationUrl": "http://localhost:5177"
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}, },
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "https://localhost:7036;http://localhost:5177", "applicationUrl": "https://localhost:7036;http://localhost:5177"
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
} }
} }
} }

View File

@ -1,6 +1,7 @@
using System.Globalization; using System.Globalization;
using Logging; using Logging;
using Tranga; using Tranga;
using Tranga.LibraryManagers;
namespace Tranga_CLI; namespace Tranga_CLI;
@ -25,10 +26,10 @@ public static class Tranga_Cli
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, Console.Out.Encoding, logFilePath);
logger.WriteLine("Tranga_CLI", "Loading Taskmanager."); logger.WriteLine("Tranga_CLI", "Loading Taskmanager.");
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, null); TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, new HashSet<LibraryManager>());
logger.WriteLine("Tranga_CLI", "User Input"); logger.WriteLine("Tranga_CLI", "User Input");
@ -39,11 +40,11 @@ public static class Tranga_Cli
if (tmpPath.Length > 0) if (tmpPath.Length > 0)
settings.downloadLocation = tmpPath; settings.downloadLocation = tmpPath;
Console.WriteLine($"Komga BaseURL [{settings.komga?.baseUrl}]:"); Console.WriteLine($"Komga BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Komga))?.baseUrl}]:");
string? tmpUrl = Console.ReadLine(); string? tmpUrlKomga = Console.ReadLine();
while (tmpUrl is null) while (tmpUrlKomga is null)
tmpUrl = Console.ReadLine(); tmpUrlKomga = Console.ReadLine();
if (tmpUrl.Length > 0) if (tmpUrlKomga.Length > 0)
{ {
Console.WriteLine("Username:"); Console.WriteLine("Username:");
string? tmpUser = Console.ReadLine(); string? tmpUser = Console.ReadLine();
@ -70,7 +71,23 @@ public static class Tranga_Cli
} }
} while (key != ConsoleKey.Enter); } while (key != ConsoleKey.Enter);
settings.komga = new Komga(tmpUrl, tmpUser, tmpPass, logger); settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
settings.libraryManagers.Add(new Komga(tmpUrlKomga, tmpUser, tmpPass, logger));
}
Console.WriteLine($"Kavita BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Kavita))?.baseUrl}]:");
string? tmpUrlKavita = Console.ReadLine();
while (tmpUrlKavita is null)
tmpUrlKavita = Console.ReadLine();
if (tmpUrlKavita.Length > 0)
{
Console.WriteLine("Username:");
string? tmpApiKey = Console.ReadLine();
while (tmpApiKey is null || tmpApiKey.Length < 1)
tmpApiKey = Console.ReadLine();
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
settings.libraryManagers.Add(new Kavita(tmpUrlKavita, tmpApiKey, logger));
} }
logger.WriteLine("Tranga_CLI", "Loaded."); logger.WriteLine("Tranga_CLI", "Loaded.");
@ -202,13 +219,13 @@ public static class Tranga_Cli
int tIndex = 0; int tIndex = 0;
Console.WriteLine($"Tasks (Running/Queue/Total): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}"); Console.WriteLine($"Tasks (Running/Queue/Total): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}");
string header = string header =
$"{"",-5}{"Task",-20} | {"Last Executed",-20} | {"Reoccurrence",-12} | {"State",-10} | {"Connector",-15} | Publication/Manga"; $"{"",-5}{"Task",-20} | {"Last Executed",-20} | {"Reoccurrence",-12} | {"State",-10} | {"Connector",-15} | {"Progress",-9} | Publication/Manga";
Console.WriteLine(header); Console.WriteLine(header);
Console.WriteLine(new string('-', header.Length)); Console.WriteLine(new string('-', header.Length));
foreach (TrangaTask trangaTask in tasks) foreach (TrangaTask trangaTask in tasks)
{ {
string[] taskSplit = trangaTask.ToString().Split(", "); string[] taskSplit = trangaTask.ToString().Split(", ");
Console.WriteLine($"{tIndex++:000}: {taskSplit[0],-20} | {taskSplit[1],-20} | {taskSplit[2],-12} | {taskSplit[3],-10} | {(taskSplit.Length > 4 ? taskSplit[4] : ""),-15} | {(taskSplit.Length > 5 ? taskSplit[5] : "")}"); Console.WriteLine($"{tIndex++:000}: {taskSplit[0],-20} | {taskSplit[1],-20} | {taskSplit[2],-12} | {taskSplit[3],-10} | {(taskSplit.Length > 4 ? taskSplit[4] : ""),-15} | {(taskSplit.Length > 5 ? taskSplit[5] : ""),-9} |{(taskSplit.Length > 6 ? taskSplit[6] : "")}");
} }
} }
@ -332,7 +349,7 @@ public static class Tranga_Cli
TrangaTask.Task task = (TrangaTask.Task)tmpTask; TrangaTask.Task task = (TrangaTask.Task)tmpTask;
Connector? connector = null; Connector? connector = null;
if (task != TrangaTask.Task.UpdateKomgaLibrary) if (task != TrangaTask.Task.UpdateLibraries)
{ {
connector = SelectConnector(taskManager.GetAvailableConnectors().Values.ToArray(), logger); connector = SelectConnector(taskManager.GetAvailableConnectors().Values.ToArray(), logger);
if (connector is null) if (connector is null)
@ -340,7 +357,7 @@ public static class Tranga_Cli
} }
Publication? publication = null; Publication? publication = null;
if (task != TrangaTask.Task.UpdateKomgaLibrary) if (task != TrangaTask.Task.UpdateLibraries)
{ {
publication = SelectPublication(taskManager, connector!, logger); publication = SelectPublication(taskManager, connector!, logger);
if (publication is null) if (publication is null)

View File

@ -1,4 +1,5 @@
<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"> <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/=Komga/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Manganato/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Taskmanager/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Taskmanager/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tranga/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary> <s:Boolean x:Key="/Default/UserDictionary/Words/=Tranga/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -1,7 +1,9 @@
using System.IO.Compression; using System.IO.Compression;
using System.Net; using System.Net;
using System.Runtime.InteropServices;
using System.Xml.Linq; using System.Xml.Linq;
using Logging; using Logging;
using static System.IO.UnixFileMode;
namespace Tranga; namespace Tranga;
@ -56,7 +58,8 @@ public abstract class Connector
/// </summary> /// </summary>
/// <param name="publication">Publication that contains Chapter</param> /// <param name="publication">Publication that contains Chapter</param>
/// <param name="chapter">Chapter with Images to retrieve</param> /// <param name="chapter">Chapter with Images to retrieve</param>
public abstract void DownloadChapter(Publication publication, Chapter chapter); /// <param name="parentTask">Will be used for progress-tracking</param>
public abstract void DownloadChapter(Publication publication, Chapter chapter, TrangaTask parentTask);
/// <summary> /// <summary>
/// Copies the already downloaded cover from cache to downloadLocation /// Copies the already downloaded cover from cache to downloadLocation
@ -67,9 +70,7 @@ public abstract class Connector
{ {
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} {publication.internalId}"); logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} {publication.internalId}");
//Check if Publication already has a Folder and cover //Check if Publication already has a Folder and cover
string publicationFolder = Path.Join(downloadLocation, publication.folderName); string publicationFolder = publication.CreatePublicationFolder(downloadLocation);
if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder);
DirectoryInfo dirInfo = new (publicationFolder); DirectoryInfo dirInfo = new (publicationFolder);
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover."))) if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover.")))
{ {
@ -81,6 +82,8 @@ public abstract class Connector
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" ); string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}"); logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
File.Copy(fileInCache, newFilePath, true); File.Copy(fileInCache, newFilePath, true);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
} }
/// <summary> /// <summary>
@ -97,7 +100,7 @@ public abstract class Connector
new XElement("Title", chapter.name), new XElement("Title", chapter.name),
new XElement("Writer", publication.author), new XElement("Writer", publication.author),
new XElement("Volume", chapter.volumeNumber), new XElement("Volume", chapter.volumeNumber),
new XElement("Number", chapter.chapterNumber) //TODO check if this is correct at some point new XElement("Number", chapter.chapterNumber)
); );
return comicInfo.ToString(); return comicInfo.ToString();
} }
@ -126,12 +129,17 @@ public abstract class Connector
/// <param name="imageUrl"></param> /// <param name="imageUrl"></param>
/// <param name="fullPath"></param> /// <param name="fullPath"></param>
/// <param name="requestType">RequestType for Rate-Limit</param> /// <param name="requestType">RequestType for Rate-Limit</param>
private void DownloadImage(string imageUrl, string fullPath, byte requestType) /// <param name="referrer">referrer used in html request header</param>
private void DownloadImage(string imageUrl, string fullPath, byte requestType, string? referrer = null)
{
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType, referrer);
if (requestResult.result != Stream.Null)
{ {
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType);
byte[] buffer = new byte[requestResult.result.Length]; byte[] buffer = new byte[requestResult.result.Length];
requestResult.result.ReadExactly(buffer, 0, buffer.Length); requestResult.result.ReadExactly(buffer, 0, buffer.Length);
File.WriteAllBytes(fullPath, buffer); File.WriteAllBytes(fullPath, buffer);
}else
logger?.WriteLine(this.GetType().ToString(), "No Stream-Content in result.");
} }
/// <summary> /// <summary>
@ -139,9 +147,11 @@ public abstract class Connector
/// </summary> /// </summary>
/// <param name="imageUrls">List of URLs to download Images from</param> /// <param name="imageUrls">List of URLs to download Images from</param>
/// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param> /// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param>
/// <param name="parentTask">Used for progress tracking</param>
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param> /// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
/// <param name="requestType">RequestType for RateLimits</param> /// <param name="requestType">RequestType for RateLimits</param>
protected void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, string? comicInfoPath = null) /// <param name="referrer">Used in http request header</param>
protected void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, TrangaTask parentTask, string? comicInfoPath = null, string? referrer = null)
{ {
logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}"); logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
//Check if Publication Directory already exists //Check if Publication Directory already exists
@ -161,8 +171,9 @@ public abstract class Connector
{ {
string[] split = imageUrl.Split('.'); string[] split = imageUrl.Split('.');
string extension = split[^1]; string extension = split[^1];
logger?.WriteLine("Connector", $"Downloading Image {chapter + 1}/{imageUrls.Length}"); logger?.WriteLine("Connector", $"Downloading Image {chapter + 1:000}/{imageUrls.Length:000} {(parentTask.publication?.sortName)![..(int)(parentTask.publication?.sortName.Length > 25 ? 25 : parentTask.publication?.sortName.Length)!],-25} {(parentTask.publication?.internalId)![..(int)(parentTask.publication?.internalId.Length > 25 ? 25 : parentTask.publication?.internalId.Length)!],-25} Total Task Progress: {parentTask.progress:00.0}%");
DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType); DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
parentTask.tasksFinished++;
} }
if(comicInfoPath is not null) if(comicInfoPath is not null)
@ -171,9 +182,28 @@ public abstract class Connector
logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}"); logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
//ZIP-it and ship-it //ZIP-it and ship-it
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath); ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(saveArchiveFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
Directory.Delete(tempFolder, true); //Cleanup Directory.Delete(tempFolder, true); //Cleanup
} }
protected string SaveCoverImageToCache(string url, byte requestType)
{
string[] split = url.Split('/');
string filename = split[^1];
string saveImagePath = Path.Join(imageCachePath, filename);
if (File.Exists(saveImagePath))
return filename;
DownloadClient.RequestResult coverResult = downloadClient.MakeRequest(url, requestType);
using MemoryStream ms = new();
coverResult.result.CopyTo(ms);
File.WriteAllBytes(saveImagePath, ms.ToArray());
logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
return filename;
}
protected class DownloadClient protected class DownloadClient
{ {
private static readonly HttpClient Client = new(); private static readonly HttpClient Client = new();
@ -201,8 +231,9 @@ public abstract class Connector
/// </summary> /// </summary>
/// <param name="url"></param> /// <param name="url"></param>
/// <param name="requestType">For RateLimits: Same Endpoints use same type</param> /// <param name="requestType">For RateLimits: Same Endpoints use same type</param>
/// <param name="referrer">Used in http request header</param>
/// <returns>RequestResult with StatusCode and Stream of received data</returns> /// <returns>RequestResult with StatusCode and Stream of received data</returns>
public RequestResult MakeRequest(string url, byte requestType) public RequestResult MakeRequest(string url, byte requestType, string? referrer = null)
{ {
if (_rateLimit.TryGetValue(requestType, out TimeSpan value)) if (_rateLimit.TryGetValue(requestType, out TimeSpan value))
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value)); _lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value));
@ -224,13 +255,15 @@ public abstract class Connector
try try
{ {
HttpRequestMessage requestMessage = new(HttpMethod.Get, url); HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
if(referrer is not null)
requestMessage.Headers.Referrer = new Uri(referrer);
_lastExecutedRateLimit[requestType] = DateTime.Now; _lastExecutedRateLimit[requestType] = DateTime.Now;
response = Client.Send(requestMessage); response = Client.Send(requestMessage);
} }
catch (HttpRequestException e) catch (HttpRequestException e)
{ {
logger?.WriteLine(this.GetType().ToString(), e.Message); logger?.WriteLine(this.GetType().ToString(), e.Message);
logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}"); logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}... Retrying.");
Thread.Sleep(_rateLimit[requestType] * 2); Thread.Sleep(_rateLimit[requestType] * 2);
} }
} }

View File

@ -102,7 +102,7 @@ public class MangaDex : Connector
string? coverUrl = GetCoverUrl(publicationId, posterId); string? coverUrl = GetCoverUrl(publicationId, posterId);
string? coverCacheName = null; string? coverCacheName = null;
if (coverUrl is not null) if (coverUrl is not null)
coverCacheName = SaveImage(coverUrl); coverCacheName = SaveCoverImageToCache(coverUrl, (byte)RequestType.AtHomeServer);
string? author = GetAuthor(authorId); string? author = GetAuthor(authorId);
@ -204,7 +204,7 @@ public class MangaDex : Connector
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
public override void DownloadChapter(Publication publication, Chapter chapter) public override void DownloadChapter(Publication publication, Chapter chapter, TrangaTask parentTask)
{ {
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
//Request URLs for Chapter-Images //Request URLs for Chapter-Images
@ -228,7 +228,7 @@ public class MangaDex : Connector
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger)); File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
//Download Chapter-Images //Download Chapter-Images
DownloadChapterImages(imageUrls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)RequestType.AtHomeServer, comicInfoPath); DownloadChapterImages(imageUrls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)RequestType.AtHomeServer, parentTask, comicInfoPath);
} }
private string? GetCoverUrl(string publicationId, string? posterId) private string? GetCoverUrl(string publicationId, string? posterId)
@ -273,21 +273,4 @@ public class MangaDex : Connector
logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {author}"); logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {author}");
return author; return author;
} }
private string SaveImage(string url)
{
string[] split = url.Split('/');
string filename = split[^1];
string saveImagePath = Path.Join(imageCachePath, filename);
if (File.Exists(saveImagePath))
return filename;
DownloadClient.RequestResult coverResult = downloadClient.MakeRequest(url, (byte)RequestType.AtHomeServer);
using MemoryStream ms = new();
coverResult.result.CopyTo(ms);
File.WriteAllBytes(saveImagePath, ms.ToArray());
logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
return filename;
}
} }

View File

@ -0,0 +1,196 @@
using System.Net;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Logging;
namespace Tranga.Connectors;
public class Manganato : Connector
{
public override string name { get; }
public Manganato(string downloadLocation, string imageCachePath, Logger? logger) : base(downloadLocation, imageCachePath, logger)
{
this.name = "Manganato";
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
{
{(byte)1, 60}
}, logger);
}
public override Publication[] GetPublications(string publicationTitle = "")
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_');
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={sanitizedTitle})");
string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}";
DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, (byte)1);
if (requestResult.statusCode != HttpStatusCode.OK)
return Array.Empty<Publication>();
return ParsePublicationsFromHtml(requestResult.result);
}
private Publication[] ParsePublicationsFromHtml(Stream html)
{
StreamReader reader = new (html);
string htmlString = reader.ReadToEnd();
HtmlDocument document = new ();
document.LoadHtml(htmlString);
IEnumerable<HtmlNode> searchResults = document.DocumentNode.Descendants("div").Where(n => n.HasClass("search-story-item"));
List<string> urls = new();
foreach (HtmlNode mangaResult in searchResults)
{
urls.Add(mangaResult.Descendants("a").First(n => n.HasClass("item-title")).GetAttributes()
.First(a => a.Name == "href").Value);
}
HashSet<Publication> ret = new();
foreach (string url in urls)
{
DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(url, (byte)1);
if (requestResult.statusCode != HttpStatusCode.OK)
return Array.Empty<Publication>();
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, url.Split('/')[^1]));
}
return ret.ToArray();
}
private Publication ParseSinglePublicationFromHtml(Stream html, string publicationId)
{
StreamReader reader = new (html);
string htmlString = reader.ReadToEnd();
HtmlDocument document = new ();
document.LoadHtml(htmlString);
string status = "";
Dictionary<string, string> altTitles = new();
Dictionary<string, string>? links = null;
HashSet<string> tags = new();
string? author = null, originalLanguage = null;
int? year = DateTime.Now.Year;
HtmlNode infoNode = document.DocumentNode.Descendants("div").First(d => d.HasClass("story-info-right"));
string sortName = infoNode.Descendants("h1").First().InnerText;
HtmlNode infoTable = infoNode.Descendants().First(d => d.Name == "table");
foreach (HtmlNode row in infoTable.Descendants("tr"))
{
string key = row.SelectNodes("td").First().InnerText.ToLower();
string value = row.SelectNodes("td").Last().InnerText;
string keySanitized = string.Concat(Regex.Matches(key, "[a-z]"));
switch (keySanitized)
{
case "alternative":
string[] alts = value.Split(" ; ");
for(int i = 0; i < alts.Length; i++)
altTitles.Add(i.ToString(), alts[i]);
break;
case "authors":
author = value;
break;
case "status":
status = value;
break;
case "genres":
string[] genres = value.Split(" - ");
tags = genres.ToHashSet();
break;
default: break;
}
}
string posterUrl = document.DocumentNode.Descendants("span").First(s => s.HasClass("info-image")).Descendants("img").First()
.GetAttributes().First(a => a.Name == "src").Value;
string coverFileNameInCache = SaveCoverImageToCache(posterUrl, 1);
string description = document.DocumentNode.Descendants("div").First(d => d.HasClass("panel-story-info-description"))
.InnerText.Replace("Description :", "");
while (description.StartsWith('\n'))
description = description.Substring(1);
string yearString = document.DocumentNode.Descendants("li").Last(li => li.HasClass("a-h")).Descendants("span")
.First(s => s.HasClass("chapter-time")).InnerText;
year = Convert.ToInt32(yearString.Split(',')[^1]) + 2000;
return new Publication(sortName, author, description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
year, originalLanguage, status, publicationId);
}
public override Chapter[] GetChapters(Publication publication, string language = "")
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
string requestUrl = $"https://chapmanganato.com/{publication.publicationId}";
DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, (byte)1);
if (requestResult.statusCode != HttpStatusCode.OK)
return Array.Empty<Chapter>();
return ParseChaptersFromHtml(requestResult.result);
}
private Chapter[] ParseChaptersFromHtml(Stream html)
{
StreamReader reader = new (html);
string htmlString = reader.ReadToEnd();
HtmlDocument document = new ();
document.LoadHtml(htmlString);
List<Chapter> ret = new();
HtmlNode chapterList = document.DocumentNode.Descendants("ul").First(l => l.HasClass("row-content-chapter"));
foreach (HtmlNode chapterInfo in chapterList.Descendants("li"))
{
string fullString = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name")).InnerText;
string? volumeNumber = fullString.Contains("Vol.") ? fullString.Replace("Vol.", "").Split(' ')[0] : null;
string? chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Replace('-','.');
string chapterName = string.Concat(fullString.Split(':')[1..]);
string url = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name"))
.GetAttributeValue("href", "");
ret.Add(new Chapter(chapterName, volumeNumber, chapterNumber, url));
}
return ret.ToArray();
}
public override void DownloadChapter(Publication publication, Chapter chapter, TrangaTask parentTask)
{
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
string requestUrl = chapter.url;
DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, (byte)1);
if (requestResult.statusCode != HttpStatusCode.OK)
return;
string[] imageUrls = ParseImageUrlsFromHtml(requestResult.result);
string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
DownloadChapterImages(imageUrls, GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, "https://chapmanganato.com/");
}
private string[] ParseImageUrlsFromHtml(Stream html)
{
StreamReader reader = new (html);
string htmlString = reader.ReadToEnd();
HtmlDocument document = new ();
document.LoadHtml(htmlString);
List<string> ret = new();
HtmlNode imageContainer =
document.DocumentNode.Descendants("div").First(i => i.HasClass("container-chapter-reader"));
foreach(HtmlNode imageNode in imageContainer.Descendants("img"))
ret.Add(imageNode.GetAttributeValue("src", ""));
return ret.ToArray();
}
}

View File

@ -1,148 +0,0 @@
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json.Nodes;
using Logging;
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
private Logger? logger;
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
/// <param name="username">Komga Username</param>
/// <param name="password">Komga password, will be base64 encoded. yea</param>
public Komga(string baseUrl, string username, string password, Logger? logger)
{
this.baseUrl = baseUrl;
this.auth = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
this.logger = logger;
}
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
/// <param name="auth">Base64 string of username and password (username):(password)</param>
[JsonConstructor]
public Komga(string baseUrl, string auth, Logger? logger)
{
this.baseUrl = baseUrl;
this.auth = auth;
this.logger = logger;
}
/// <summary>
/// Fetches all libraries available to the user
/// </summary>
/// <returns>Array of KomgaLibraries</returns>
public KomgaLibrary[] GetLibraries()
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries");
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth);
if (data == Stream.Null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
return Array.Empty<KomgaLibrary>();
}
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
if (result is null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
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)
{
logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries");
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)
{
HttpClientHandler clientHandler = new ();
clientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true;
HttpClient client = new(clientHandler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
HttpRequestMessage requestMessage = new ()
{
Method = HttpMethod.Get,
RequestUri = new Uri(url)
};
HttpResponseMessage response = client.Send(requestMessage);
Stream ret;
if (response.StatusCode is HttpStatusCode.Unauthorized)
{
ret = MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, auth);
}else
return response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null;
return ret;
}
public static bool MakePost(string url, string auth)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true;
HttpClient client = new(clientHandler)
{
DefaultRequestHeaders =
{
{ "Accept", "application/json" },
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
}
};
HttpRequestMessage requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url)
};
HttpResponseMessage response = client.Send(requestMessage);
bool ret;
if (response.StatusCode is HttpStatusCode.Unauthorized)
{
ret = MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, auth);
}else
return response.IsSuccessStatusCode;
return ret;
}
}
}

123
Tranga/LibraryManager.cs Normal file
View File

@ -0,0 +1,123 @@
using System.Net;
using System.Net.Http.Headers;
using Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tranga.LibraryManagers;
namespace Tranga;
public abstract class LibraryManager
{
public enum LibraryType : byte
{
Komga = 0,
Kavita = 1
}
public LibraryType libraryType { get; }
public string baseUrl { get; }
protected string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems
protected Logger? logger;
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
/// <param name="auth">Base64 string of username and password (username):(password)</param>
/// <param name="logger"></param>
protected LibraryManager(string baseUrl, string auth, Logger? logger, LibraryType libraryType)
{
this.baseUrl = baseUrl;
this.auth = auth;
this.logger = logger;
this.libraryType = libraryType;
}
public abstract void UpdateLibrary();
public void AddLogger(Logger newLogger)
{
this.logger = newLogger;
}
protected static class NetClient
{
public static Stream MakeRequest(string url, string auth, Logger? logger)
{
HttpClientHandler clientHandler = new ();
HttpClient client = new(clientHandler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
HttpRequestMessage requestMessage = new ()
{
Method = HttpMethod.Get,
RequestUri = new Uri(url)
};
logger?.WriteLine("LibraryManager", $"GET {url}");
HttpResponseMessage response = client.Send(requestMessage);
logger?.WriteLine("LibraryManager", $"{(int)response.StatusCode} {response.StatusCode}: {response.ReasonPhrase}");
if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url)
return MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, auth, logger);
else if (response.IsSuccessStatusCode)
return response.Content.ReadAsStream();
else
return Stream.Null;
}
public static bool MakePost(string url, string auth, Logger? logger)
{
HttpClientHandler clientHandler = new ();
HttpClient client = new(clientHandler)
{
DefaultRequestHeaders =
{
{ "Accept", "application/json" },
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
}
};
HttpRequestMessage requestMessage = new ()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url)
};
logger?.WriteLine("LibraryManager", $"POST {url}");
HttpResponseMessage response = client.Send(requestMessage);
logger?.WriteLine("LibraryManager", $"{(int)response.StatusCode} {response.StatusCode}: {response.ReasonPhrase}");
if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url)
return MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, auth, logger);
else if (response.IsSuccessStatusCode)
return true;
else
return false;
}
}
public class LibraryManagerJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(LibraryManager));
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo["libraryType"]!.Value<Int64>() == (Int64)LibraryType.Komga)
return jo.ToObject<Komga>(serializer)!;
if (jo["libraryType"]!.Value<Int64>() == (Int64)LibraryType.Kavita)
return jo.ToObject<Kavita>(serializer)!;
throw new Exception();
}
public override bool CanWrite => false;
/// <summary>
/// Don't call this
/// </summary>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new Exception("Dont call this");
}
}
}

View File

@ -0,0 +1,64 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Logging;
namespace Tranga.LibraryManagers;
public class Kavita : LibraryManager
{
public Kavita(string baseUrl, string apiKey, Logger? logger) : base(baseUrl, apiKey, logger, LibraryType.Kavita)
{
}
public override void UpdateLibrary()
{
logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries");
foreach (KavitaLibrary lib in GetLibraries())
NetClient.MakePost($"{baseUrl}/api/Library/scan?libraryId={lib.id}", auth, logger);
}
/// <summary>
/// Fetches all libraries available to the user
/// </summary>
/// <returns>Array of KavitaLibrary</returns>
private IEnumerable<KavitaLibrary> GetLibraries()
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries");
Stream data = NetClient.MakeRequest($"{baseUrl}/api/Library", auth, logger);
if (data == Stream.Null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
return Array.Empty<KavitaLibrary>();
}
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
if (result is null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
return Array.Empty<KavitaLibrary>();
}
HashSet<KavitaLibrary> 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 KavitaLibrary(libraryId, libraryName));
}
return ret;
}
private struct KavitaLibrary
{
public string id { get; }
public string name { get; }
public KavitaLibrary(string id, string name)
{
this.id = id;
this.name = name;
}
}
}

View File

@ -0,0 +1,75 @@
using System.Text.Json.Nodes;
using Logging;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Tranga.LibraryManagers;
/// <summary>
/// Provides connectivity to Komga-API
/// Can fetch and update libraries
/// </summary>
public class Komga : LibraryManager
{
public Komga(string baseUrl, string username, string password, Logger? logger)
: base(baseUrl, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")), logger, LibraryType.Komga)
{
}
[JsonConstructor]
public Komga(string baseUrl, string auth, Logger? logger) : base(baseUrl, auth, logger, LibraryType.Komga)
{
}
public override void UpdateLibrary()
{
logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries");
foreach (KomgaLibrary lib in GetLibraries())
NetClient.MakePost($"{baseUrl}/api/v1/libraries/{lib.id}/scan", auth, logger);
}
/// <summary>
/// Fetches all libraries available to the user
/// </summary>
/// <returns>Array of KomgaLibraries</returns>
private IEnumerable<KomgaLibrary> GetLibraries()
{
logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries");
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth, logger);
if (data == Stream.Null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
return Array.Empty<KomgaLibrary>();
}
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
if (result is null)
{
logger?.WriteLine(this.GetType().ToString(), $"No libraries returned");
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;
}
private struct KomgaLibrary
{
public string id { get; }
public string name { get; }
public KomgaLibrary(string id, string name)
{
this.id = id;
this.name = name;
}
}
}

View File

@ -1,6 +1,8 @@
using System.Text; using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Newtonsoft.Json; using Newtonsoft.Json;
using static System.IO.UnixFileMode;
namespace Tranga; namespace Tranga;
@ -48,14 +50,24 @@ public readonly struct Publication
this.internalId = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{onlyLowerLetters}{this.year}")); this.internalId = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{onlyLowerLetters}{this.year}"));
} }
public void SaveSeriesInfoJson(string downloadDirectory) public string CreatePublicationFolder(string downloadDirectory)
{ {
string publicationFolder = Path.Join(downloadDirectory, this.folderName); string publicationFolder = Path.Join(downloadDirectory, this.folderName);
if(!Directory.Exists(publicationFolder)) if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder); Directory.CreateDirectory(publicationFolder);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(publicationFolder, GroupRead | GroupWrite | GroupExecute | OtherRead | OtherWrite | OtherExecute | UserRead | UserWrite | UserExecute);
return publicationFolder;
}
public void SaveSeriesInfoJson(string downloadDirectory)
{
string publicationFolder = CreatePublicationFolder(downloadDirectory);
string seriesInfoPath = Path.Join(publicationFolder, "series.json"); string seriesInfoPath = Path.Join(publicationFolder, "series.json");
if(!File.Exists(seriesInfoPath)) if(!File.Exists(seriesInfoPath))
File.WriteAllText(seriesInfoPath,this.GetSeriesInfoJson()); File.WriteAllText(seriesInfoPath,this.GetSeriesInfoJson());
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(seriesInfoPath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
} }
/// <returns>Serialized JSON String for series.json</returns> /// <returns>Serialized JSON String for series.json</returns>
@ -95,9 +107,9 @@ public readonly struct Publication
{ {
this.name = name; this.name = name;
this.year = year; this.year = year;
if(status == "ongoing" || status == "hiatus") if(status.ToLower() == "ongoing" || status.ToLower() == "hiatus")
this.status = "Continuing"; this.status = "Continuing";
else if (status == "completed" || status == "cancelled") else if (status.ToLower() == "completed" || status.ToLower() == "cancelled")
this.status = "Ended"; this.status = "Ended";
else else
this.status = status; this.status = status;

View File

@ -1,6 +1,7 @@
using Logging; using Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Tranga.Connectors; using Tranga.Connectors;
using Tranga.LibraryManagers;
using Tranga.TrangaTasks; using Tranga.TrangaTasks;
namespace Tranga; namespace Tranga;
@ -18,7 +19,6 @@ public class TaskManager
private readonly Dictionary<Connector, List<TrangaTask>> _taskQueue = new(); private readonly Dictionary<Connector, List<TrangaTask>> _taskQueue = new();
public TrangaSettings settings { get; } public TrangaSettings settings { get; }
private Logger? logger { get; } private Logger? logger { get; }
public Komga? komga => settings.komga;
/// <param name="downloadFolderPath">Local path to save data (Manga) to</param> /// <param name="downloadFolderPath">Local path to save data (Manga) to</param>
/// <param name="workingDirectory">Path to the working directory</param> /// <param name="workingDirectory">Path to the working directory</param>
@ -27,19 +27,19 @@ public class TaskManager
/// <param name="komgaUsername">The Komga username</param> /// <param name="komgaUsername">The Komga username</param>
/// <param name="komgaPassword">The Komga password</param> /// <param name="komgaPassword">The Komga password</param>
/// <param name="logger"></param> /// <param name="logger"></param>
public TaskManager(string downloadFolderPath, string workingDirectory, string imageCachePath, string? komgaBaseUrl = null, string? komgaUsername = null, string? komgaPassword = null, Logger? logger = null) public TaskManager(string downloadFolderPath, string workingDirectory, string imageCachePath, HashSet<LibraryManager> libraryManagers, Logger? logger = null)
{ {
this.logger = logger; this.logger = logger;
_allTasks = new HashSet<TrangaTask>(); _allTasks = new HashSet<TrangaTask>();
Komga? newKomga = null; this.settings = new TrangaSettings(downloadFolderPath, workingDirectory, libraryManagers);
if (komgaBaseUrl != null && komgaUsername != null && komgaPassword != null)
newKomga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword, logger);
this.settings = new TrangaSettings(downloadFolderPath, workingDirectory, newKomga);
ExportDataAndSettings(); ExportDataAndSettings();
this._connectors = new Connector[]{ new MangaDex(downloadFolderPath, imageCachePath, logger) }; this._connectors = new Connector[]
{
new MangaDex(downloadFolderPath, imageCachePath, logger),
new Manganato(downloadFolderPath, imageCachePath, logger)
};
foreach(Connector cConnector in this._connectors) foreach(Connector cConnector in this._connectors)
_taskQueue.Add(cConnector, new List<TrangaTask>()); _taskQueue.Add(cConnector, new List<TrangaTask>());
@ -47,10 +47,18 @@ public class TaskManager
taskChecker.Start(); taskChecker.Start();
} }
public void UpdateSettings(string? downloadLocation, string? komgaUrl, string? komgaAuth) public void UpdateSettings(string? downloadLocation, string? komgaUrl, string? komgaAuth, string? kavitaUrl, string? kavitaApiKey)
{ {
if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 0 && komgaAuth.Length > 0) if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 0 && komgaAuth.Length > 0)
settings.komga = new Komga(komgaUrl, komgaAuth, null); {
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
settings.libraryManagers.Add(new Komga(komgaUrl, komgaAuth, logger));
}
if (kavitaUrl is not null && kavitaApiKey is not null && kavitaUrl.Length > 0 && kavitaApiKey.Length > 0)
{
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
settings.libraryManagers.Add(new Kavita(kavitaUrl, kavitaApiKey, logger));
}
if (downloadLocation is not null && downloadLocation.Length > 0) if (downloadLocation is not null && downloadLocation.Length > 0)
settings.downloadLocation = downloadLocation; settings.downloadLocation = downloadLocation;
ExportDataAndSettings(); ExportDataAndSettings();
@ -59,7 +67,11 @@ public class TaskManager
public TaskManager(TrangaSettings settings, Logger? logger = null) public TaskManager(TrangaSettings settings, Logger? logger = null)
{ {
this.logger = logger; this.logger = logger;
this._connectors = new Connector[]{ new MangaDex(settings.downloadLocation, settings.coverImageCache, logger) }; this._connectors = new Connector[]
{
new MangaDex(settings.downloadLocation, settings.coverImageCache, logger),
new Manganato(settings.downloadLocation, settings.coverImageCache, logger)
};
foreach(Connector cConnector in this._connectors) foreach(Connector cConnector in this._connectors)
_taskQueue.Add(cConnector, new List<TrangaTask>()); _taskQueue.Add(cConnector, new List<TrangaTask>());
_allTasks = new HashSet<TrangaTask>(); _allTasks = new HashSet<TrangaTask>();
@ -95,7 +107,7 @@ public class TaskManager
foreach (TrangaTask task in _allTasks.Where(aTask => aTask.ShouldExecute())) foreach (TrangaTask task in _allTasks.Where(aTask => aTask.ShouldExecute()))
{ {
task.state = TrangaTask.ExecutionState.Enqueued; task.state = TrangaTask.ExecutionState.Enqueued;
if(task.task == TrangaTask.Task.UpdateKomgaLibrary) if(task.task == TrangaTask.Task.UpdateLibraries)
ExecuteTaskNow(task); ExecuteTaskNow(task);
else else
{ {
@ -116,10 +128,9 @@ public class TaskManager
if (!this._allTasks.Contains(task)) if (!this._allTasks.Contains(task))
return; return;
logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}");
Task t = new(() => Task t = new(() =>
{ {
task.Execute(this); task.Execute(this, this.logger);
}); });
t.Start(); t.Start();
} }
@ -139,12 +150,12 @@ public class TaskManager
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {task} {connectorName} {publication?.sortName}"); logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {task} {connectorName} {publication?.sortName}");
TrangaTask? newTask = null; TrangaTask? newTask = null;
if (task == TrangaTask.Task.UpdateKomgaLibrary) if (task == TrangaTask.Task.UpdateLibraries)
{ {
newTask = new UpdateKomgaLibraryTask(task, reoccurrence); newTask = new UpdateLibrariesTask(task, reoccurrence);
logger?.WriteLine(this.GetType().ToString(), $"Removing old {task}-Task."); logger?.WriteLine(this.GetType().ToString(), $"Removing old {task}-Task.");
//Only one UpdateKomgaLibrary Task //Only one UpdateKomgaLibrary Task
_allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateKomgaLibrary); _allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateLibraries);
_allTasks.Add(newTask); _allTasks.Add(newTask);
logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask}"); logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask}");
}else if (task == TrangaTask.Task.DownloadNewChapters) }else if (task == TrangaTask.Task.DownloadNewChapters)
@ -185,9 +196,9 @@ public class TaskManager
public void DeleteTask(TrangaTask.Task task, string? connectorName, Publication? publication) public void DeleteTask(TrangaTask.Task task, string? connectorName, Publication? publication)
{ {
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {task} {publication?.sortName}"); logger?.WriteLine(this.GetType().ToString(), $"Removing Task {task} {publication?.sortName}");
if (task == TrangaTask.Task.UpdateKomgaLibrary) if (task == TrangaTask.Task.UpdateLibraries)
{ {
_allTasks.RemoveWhere(uTask => uTask.task == TrangaTask.Task.UpdateKomgaLibrary); _allTasks.RemoveWhere(uTask => uTask.task == TrangaTask.Task.UpdateLibraries);
logger?.WriteLine(this.GetType().ToString(), $"Removed Task {task} from all Tasks."); logger?.WriteLine(this.GetType().ToString(), $"Removed Task {task} from all Tasks.");
} }
else if (connectorName is null) else if (connectorName is null)

View File

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="HtmlAgilityPack" Version="1.11.46" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup> </ItemGroup>

View File

@ -1,4 +1,6 @@
using Newtonsoft.Json; using Logging;
using Newtonsoft.Json;
using Tranga.LibraryManagers;
namespace Tranga; namespace Tranga;
@ -10,24 +12,27 @@ public class TrangaSettings
[JsonIgnore]public string tasksFilePath => Path.Join(workingDirectory, "tasks.json"); [JsonIgnore]public string tasksFilePath => Path.Join(workingDirectory, "tasks.json");
[JsonIgnore]public string knownPublicationsPath => Path.Join(workingDirectory, "knownPublications.json"); [JsonIgnore]public string knownPublicationsPath => Path.Join(workingDirectory, "knownPublications.json");
[JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache"); [JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache");
public Komga? komga { get; set; } public HashSet<LibraryManager> libraryManagers { get; }
public TrangaSettings(string downloadLocation, string workingDirectory, Komga? komga) public TrangaSettings(string downloadLocation, string workingDirectory, HashSet<LibraryManager> libraryManagers)
{ {
if (downloadLocation.Length < 1 || workingDirectory.Length < 1) if (downloadLocation.Length < 1 || workingDirectory.Length < 1)
throw new ArgumentException("Download-location and working-directory paths can not be empty!"); throw new ArgumentException("Download-location and working-directory paths can not be empty!");
this.workingDirectory = workingDirectory; this.workingDirectory = workingDirectory;
this.downloadLocation = downloadLocation; this.downloadLocation = downloadLocation;
this.komga = komga; this.libraryManagers = libraryManagers;
} }
public static TrangaSettings LoadSettings(string importFilePath) public static TrangaSettings LoadSettings(string importFilePath, Logger? logger)
{ {
if (!File.Exists(importFilePath)) if (!File.Exists(importFilePath))
return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory(), null); return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory(), new HashSet<LibraryManager>());
string toRead = File.ReadAllText(importFilePath); string toRead = File.ReadAllText(importFilePath);
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead)!; TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead, new JsonSerializerSettings() { Converters = { new LibraryManager.LibraryManagerJsonConverter()} })!;
if(logger is not null)
foreach(LibraryManager lm in settings.libraryManagers)
lm.AddLogger(logger);
return settings; return settings;
} }

View File

@ -1,4 +1,5 @@
using Newtonsoft.Json; using Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Tranga.TrangaTasks; using Tranga.TrangaTasks;
@ -18,6 +19,9 @@ public abstract class TrangaTask
public Publication? publication { get; } public Publication? publication { get; }
public string? language { get; } public string? language { get; }
[JsonIgnore]public ExecutionState state { get; set; } [JsonIgnore]public ExecutionState state { get; set; }
[JsonIgnore] public float progress => (tasksFinished != 0f ? tasksFinished / tasksCount : 0f);
[JsonIgnore]public float tasksCount { get; set; }
[JsonIgnore]public float tasksFinished { get; set; }
public enum ExecutionState public enum ExecutionState
{ {
@ -34,13 +38,32 @@ public abstract class TrangaTask
this.connectorName = connectorName; this.connectorName = connectorName;
this.task = task; this.task = task;
this.language = language; this.language = language;
this.tasksCount = 1;
this.tasksFinished = 0;
} }
/// <summary> /// <summary>
/// Set state to running /// BL for concrete Tasks
/// </summary> /// </summary>
/// <param name="taskManager"></param> /// <param name="taskManager"></param>
public abstract void Execute(TaskManager taskManager); /// <param name="logger"></param>
protected abstract void ExecuteTask(TaskManager taskManager, Logger? logger);
/// <summary>
/// Execute the task
/// </summary>
/// <param name="taskManager">Should be the parent taskManager</param>
/// <param name="logger"></param>
public void Execute(TaskManager taskManager, Logger? logger)
{
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
this.state = ExecutionState.Running;
ExecuteTask(taskManager, logger);
this.lastExecuted = DateTime.Now;
this.state = ExecutionState.Waiting;
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
}
/// <returns>True if elapsed time since last execution is greater than set interval</returns> /// <returns>True if elapsed time since last execution is greater than set interval</returns>
public bool ShouldExecute() public bool ShouldExecute()
@ -48,15 +71,15 @@ public abstract class TrangaTask
return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence && state is ExecutionState.Waiting; return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence && state is ExecutionState.Waiting;
} }
public enum Task public enum Task : byte
{ {
DownloadNewChapters, DownloadNewChapters = 2,
UpdateKomgaLibrary UpdateLibraries = 3
} }
public override string ToString() public override string ToString()
{ {
return $"{task}, {lastExecuted}, {reoccurrence}, {state} {(connectorName is not null ? $", {connectorName}" : "" )} {(publication is not null ? $", {publication?.sortName}": "")}"; return $"{task}, {lastExecuted}, {reoccurrence}, {state} {(connectorName is not null ? $", {connectorName}" : "" )} {(publication is not null ? $", {progress:00.00}%" : "")} {(publication is not null ? $", {publication?.sortName}" : "")}";
} }
public class TrangaTaskJsonConverter : JsonConverter public class TrangaTaskJsonConverter : JsonConverter
@ -72,8 +95,8 @@ public abstract class TrangaTask
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadNewChapters) if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadNewChapters)
return jo.ToObject<DownloadNewChaptersTask>(serializer)!; return jo.ToObject<DownloadNewChaptersTask>(serializer)!;
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateKomgaLibrary) if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateLibraries)
return jo.ToObject<UpdateKomgaLibraryTask>(serializer)!; return jo.ToObject<UpdateLibrariesTask>(serializer)!;
throw new Exception(); throw new Exception();
} }
@ -83,10 +106,6 @@ public abstract class TrangaTask
/// <summary> /// <summary>
/// Don't call this /// Don't call this
/// </summary> /// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
/// <exception cref="Exception"></exception>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{ {
throw new Exception("Dont call this"); throw new Exception("Dont call this");

View File

@ -1,4 +1,6 @@
namespace Tranga.TrangaTasks; using Logging;
namespace Tranga.TrangaTasks;
public class DownloadNewChaptersTask : TrangaTask public class DownloadNewChaptersTask : TrangaTask
{ {
@ -6,26 +8,22 @@ public class DownloadNewChaptersTask : TrangaTask
{ {
} }
public override void Execute(TaskManager taskManager) protected override void ExecuteTask(TaskManager taskManager, Logger? logger)
{ {
this.state = ExecutionState.Running;
Publication pub = (Publication)this.publication!; Publication pub = (Publication)this.publication!;
Connector connector = taskManager.GetConnector(this.connectorName); Connector connector = taskManager.GetConnector(this.connectorName);
//Check if Publication already has a Folder //Check if Publication already has a Folder
string publicationFolder = Path.Join(connector.downloadLocation, pub.folderName); pub.CreatePublicationFolder(taskManager.settings.downloadLocation);
if(!Directory.Exists(publicationFolder))
Directory.CreateDirectory(publicationFolder);
List<Chapter> newChapters = UpdateChapters(connector, pub, language!, ref taskManager.chapterCollection); List<Chapter> newChapters = UpdateChapters(connector, pub, language!, ref taskManager.chapterCollection);
this.tasksCount = newChapters.Count;
connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings); connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings);
pub.SaveSeriesInfoJson(connector.downloadLocation); pub.SaveSeriesInfoJson(connector.downloadLocation);
foreach(Chapter newChapter in newChapters) foreach(Chapter newChapter in newChapters)
connector.DownloadChapter(pub, newChapter); connector.DownloadChapter(pub, newChapter, this);
this.state = ExecutionState.Waiting;
} }
/// <summary> /// <summary>

View File

@ -1,21 +0,0 @@
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);
this.state = ExecutionState.Waiting;
}
}

View File

@ -0,0 +1,16 @@
using Logging;
namespace Tranga.TrangaTasks;
public class UpdateLibrariesTask : TrangaTask
{
public UpdateLibrariesTask(Task task, TimeSpan reoccurrence) : base(task, null, null, reoccurrence)
{
}
protected override void ExecuteTask(TaskManager taskManager, Logger? logger)
{
foreach(LibraryManager lm in taskManager.settings.libraryManagers)
lm.UpdateLibrary();
}
}

View File

@ -84,7 +84,7 @@ async function GetSettings(){
} }
async function GetKomgaTask(){ async function GetKomgaTask(){
var uri = apiUri + "/Tasks/Get?taskType=UpdateKomgaLibrary"; var uri = apiUri + "/Tasks/Get?taskType=UpdateLibraries";
let json = await GetData(uri); let json = await GetData(uri);
return json; return json;
} }

View File

@ -10,12 +10,12 @@
<wrapper> <wrapper>
<topbar> <topbar>
<titlebox> <titlebox>
<img src="media/blahaj.png"> <img alt="website image is Blahaj" src="media/blahaj.png">
<span>Tranga</span> <span>Tranga</span>
</titlebox> </titlebox>
<spacer></spacer> <spacer></spacer>
<searchdiv> <searchdiv>
<input id="searchbox" placeholder="Filter" type="text"> <label for="searchbox"></label><input id="searchbox" placeholder="Filter" type="text">
</searchdiv> </searchdiv>
<img id="settingscog" src="media/settings-cogwheel.svg" height="100%" alt="settingscog"> <img id="settingscog" src="media/settings-cogwheel.svg" height="100%" alt="settingscog">
</topbar> </topbar>
@ -94,9 +94,17 @@
<label for="komgaUrl"></label><input placeholder="URL" id="komgaUrl" type="text"> <label for="komgaUrl"></label><input placeholder="URL" id="komgaUrl" type="text">
<label for="komgaUsername"></label><input placeholder="Username" id="komgaUsername" type="text"> <label for="komgaUsername"></label><input placeholder="Username" id="komgaUsername" type="text">
<label for="komgaPassword"></label><input placeholder="Password" id="komgaPassword" type="password"> <label for="komgaPassword"></label><input placeholder="Password" id="komgaPassword" type="password">
<label for="komgaUpdateTime" style="margin-right: 5px;">Update Time</label><input id="komgaUpdateTime" type="time" value="00:01:00" step="10">
<input type="submit" value="Update" onclick="UpdateKomgaSettings()">
</komga-settings> </komga-settings>
<kavita-settings>
<span class="title">Kavita</span>
<div>Configured: <span id="kavitaConfigured">✅❌</span></div>
<label for="kavitaUrl"></label><input placeholder="URL" id="kavitaUrl" type="text">
<label for="kavitaApiKey"></label><input placeholder="API-Key" id="kavitaApiKey" type="text">
</kavita-settings>
<div>
<label for="libraryUpdateTime" style="margin-right: 5px;">Update Time</label><input id="libraryUpdateTime" type="time" value="00:01:00" step="10">
<input type="submit" value="Update" onclick="UpdateLibrarySettings()">
</div>
</settings> </settings>
</popup> </popup>
</viewport> </viewport>

View File

@ -2,6 +2,7 @@
let tasks = []; let tasks = [];
let toEditId; let toEditId;
const searchBox = document.querySelector("#searchbox");
const searchPublicationQuery = document.querySelector("#searchPublicationQuery"); const searchPublicationQuery = document.querySelector("#searchPublicationQuery");
const selectPublication = document.querySelector("#taskSelectOutput"); const selectPublication = document.querySelector("#taskSelectOutput");
const connectorSelect = document.querySelector("#connectors"); const connectorSelect = document.querySelector("#connectors");
@ -25,8 +26,11 @@ const settingDownloadLocation = document.querySelector("#downloadLocation");
const settingKomgaUrl = document.querySelector("#komgaUrl"); const settingKomgaUrl = document.querySelector("#komgaUrl");
const settingKomgaUser = document.querySelector("#komgaUsername"); const settingKomgaUser = document.querySelector("#komgaUsername");
const settingKomgaPass = document.querySelector("#komgaPassword"); const settingKomgaPass = document.querySelector("#komgaPassword");
const settingKomgaTime = document.querySelector("#komgaUpdateTime"); const settingKavitaUrl = document.querySelector("#kavitaUrl");
const settingKavitaApi = document.querySelector("#kavitaApiKey");
const libraryUpdateTime = document.querySelector("#libraryUpdateTime");
const settingKomgaConfigured = document.querySelector("#komgaConfigured"); const settingKomgaConfigured = document.querySelector("#komgaConfigured");
const settingKavitaConfigured = document.querySelector("#kavitaConfigured");
const settingApiUri = document.querySelector("#settingApiUri"); const settingApiUri = document.querySelector("#settingApiUri");
const tagTasksRunning = document.querySelector("#tasksRunningTag"); const tagTasksRunning = document.querySelector("#tasksRunningTag");
const tagTasksQueued = document.querySelector("#tasksQueuedTag"); const tagTasksQueued = document.querySelector("#tasksQueuedTag");
@ -34,6 +38,7 @@ const tagTasksTotal = document.querySelector("#totalTasksTag");
const tagTaskPopup = document.querySelector("footer-tag-popup"); const tagTaskPopup = document.querySelector("footer-tag-popup");
const tagTasksPopupContent = document.querySelector("footer-tag-content"); const tagTasksPopupContent = document.querySelector("footer-tag-content");
searchbox.addEventListener("keyup", (event) => FilterResults());
settingsCog.addEventListener("click", () => OpenSettings()); settingsCog.addEventListener("click", () => OpenSettings());
document.querySelector("#blurBackgroundSettingsPopup").addEventListener("click", () => HideSettings()); document.querySelector("#blurBackgroundSettingsPopup").addEventListener("click", () => HideSettings());
closetaskpopup.addEventListener("click", () => HideAddTaskPopup()); closetaskpopup.addEventListener("click", () => HideAddTaskPopup());
@ -237,38 +242,50 @@ function GetSettingsClick(){
settingKomgaUrl.value = ""; settingKomgaUrl.value = "";
settingKomgaUser.value = ""; settingKomgaUser.value = "";
settingKomgaPass.value = ""; settingKomgaPass.value = "";
settingKavitaUrl.value = "";
settingKavitaApi.value = "";
settingKomgaConfigured.innerText = "❌";
settingKavitaConfigured.innerText = "❌";
settingApiUri.placeholder = apiUri; settingApiUri.placeholder = apiUri;
GetSettings().then(json => { GetSettings().then(json => {
settingDownloadLocation.innerText = json.downloadLocation; settingDownloadLocation.innerText = json.downloadLocation;
if(json.komga != null) { json.libraryManagers.forEach(lm => {
settingKomgaUrl.placeholder = json.komga.baseUrl; if(lm.libraryType == 0){
settingKomgaUrl.placeholder = lm.baseUrl;
settingKomgaUser.placeholder = "Configured"; settingKomgaUser.placeholder = "Configured";
settingKomgaPass.placeholder = "***"; settingKomgaPass.placeholder = "***";
settingKomgaConfigured.innerText = "✅";
} else if(libraryType == 1){
settingKavitaUrl.placeholder = lm.baseUrl;
settingKavitaApi.placeholder = "***";
settingKavitaConfigured.innerText = "✅";
} }
}); });
});
GetKomgaTask().then(json => { GetKomgaTask().then(json => {
settingKomgaTime.value = json[0].reoccurrence;
if(json.length > 0) if(json.length > 0)
settingKomgaConfigured.innerText = "✅"; libraryUpdateTime.value = json[0].reoccurrence;
else
settingKomgaConfigured.innerText = "❌";
}); });
} }
function UpdateKomgaSettings(){ function UpdateLibrarySettings(){
if(settingKomgaUser.value != "" && settingKomgaPass != ""){ if(settingKomgaUser.value != "" && settingKomgaPass != ""){
var auth = utf8_to_b64(`${settingKomgaUser.value}:${settingKomgaPass.value}`); var auth = utf8_to_b64(`${settingKomgaUser.value}:${settingKomgaPass.value}`);
console.log(auth); console.log(auth);
if(settingKomgaUrl.value != "") if(settingKomgaUrl.value != "")
UpdateSettings("", settingKomgaUrl.value, auth); UpdateSettings("", settingKomgaUrl.value, auth, "", "");
else else
UpdateSettings("", settingKomgaUrl.placeholder, auth); UpdateSettings("", settingKomgaUrl.placeholder, auth, "", "");
} }
CreateTask("UpdateKomgaLibrary", settingKomgaTime.value, "","","");
if(settingKavitaUrl.value != "" && settingKavitaApi != ""){
UpdateSettings("", "", "", settingKavitaUrl.value, settingKavitaApi.value);
}
CreateTask("UpdateLibraries", libraryUpdateTime.value, "","","");
setTimeout(() => GetSettingsClick(), 100); setTimeout(() => GetSettingsClick(), 100);
} }
@ -331,6 +348,30 @@ function CloseTasksPopup(){
tagTaskPopup.style.display = "none"; tagTaskPopup.style.display = "none";
} }
function FilterResults(){
if(searchBox.value.length > 0){
tasksContent.childNodes.forEach(publication => {
publication.childNodes.forEach(item => {
if(item.nodeName.toLowerCase() == "publication-information"){
item.childNodes.forEach(information => {
if(information.nodeName.toLowerCase() == "publication-name"){
if(!information.textContent.toLowerCase().includes(searchBox.value.toLowerCase())){
publication.style.display = "none";
}else{
publication.style.display = "initial";
}
}
});
}
});
});
}else{
tasksContent.childNodes.forEach(publication => publication.style.display = "initial");
}
}
//Resets the tasks shown //Resets the tasks shown
ResetContent(); ResetContent();
//Get Tasks and show them //Get Tasks and show them

View File

@ -155,7 +155,7 @@ settings {
z-index: 10; z-index: 10;
position: absolute; position: absolute;
left: 25%; left: 25%;
top: 25%; top: 100px;
border-radius: 5px; border-radius: 5px;
padding: 10px 0; padding: 10px 0;
} }

View File

@ -18,3 +18,4 @@ services:
- 9555:80 - 9555:80
depends_on: depends_on:
- tranga-api - tranga-api
restart: unless-stopped