Compare commits
No commits in common. "f9b5e05974ce5a6f58c8314f1a4d3bcdf9f90779" and "bad4330330d1ca24a1d28c613eaf1bf889c391d7" have entirely different histories.
f9b5e05974
...
bad4330330
@ -1,12 +1,10 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace API;
|
||||
|
||||
public static class Program
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
@ -29,22 +27,22 @@ public static class Program
|
||||
if (File.Exists(settingsFilePath))
|
||||
settings = TrangaSettings.LoadSettings(settingsFilePath, logger);
|
||||
else
|
||||
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>());
|
||||
|
||||
Directory.CreateDirectory(settings.workingDirectory);
|
||||
Directory.CreateDirectory(settings.downloadLocation);
|
||||
Directory.CreateDirectory(settings.coverImageCache);
|
||||
|
||||
settings.logger?.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}");
|
||||
settings.logger?.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}");
|
||||
settings.logger?.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}");
|
||||
settings.logger?.WriteLine("Tranga",$"Logfile-Path: {logFilePath}");
|
||||
settings.logger?.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}");
|
||||
logger.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}");
|
||||
logger.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}");
|
||||
logger.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}");
|
||||
logger.WriteLine("Tranga",$"Logfile-Path: {logFilePath}");
|
||||
logger.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}");
|
||||
|
||||
settings.logger?.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings);
|
||||
logger.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings, logger);
|
||||
|
||||
Server server = new (6531, taskManager);
|
||||
Server server = new (6531, taskManager, logger);
|
||||
foreach(NotificationManager nm in taskManager.settings.notificationManagers)
|
||||
nm.SendNotification("Tranga-API", "Started Tranga-API");
|
||||
}
|
||||
|
@ -2,7 +2,6 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace API;
|
||||
@ -23,6 +22,7 @@ public class RequestHandler
|
||||
new(HttpMethod.Get, "/Tasks/Types", Array.Empty<string>()),
|
||||
new(HttpMethod.Post, "/Tasks/CreateMonitorTask",
|
||||
new[] { "connectorName", "internalId", "reoccurrenceTime", "language?", "ignoreChaptersBelow?" }),
|
||||
//DEPRECATED new(HttpMethod.Post, "/Tasks/CreateUpdateLibraryTask", new[] { "reoccurrenceTime" }),
|
||||
new(HttpMethod.Post, "/Tasks/CreateDownloadChaptersTask",
|
||||
new[] { "connectorName", "internalId", "chapters", "language?" }),
|
||||
new(HttpMethod.Get, "/Tasks", new[] { "taskType", "connectorName?", "publicationId?" }),
|
||||
@ -167,6 +167,12 @@ public class RequestHandler
|
||||
pPublication1.ignoreChaptersBelow = float.Parse(minChapter,new NumberFormatInfo() { NumberDecimalSeparator = "." });
|
||||
_taskManager.AddTask(new MonitorPublicationTask(connectorName1, pPublication1, TimeSpan.Parse(reoccurrenceTime1), language1 ?? "en"));
|
||||
break;
|
||||
case "/Tasks/CreateUpdateLibraryTask": // DEPRECATED
|
||||
/*variables.TryGetValue("reoccurrenceTime", out string? reoccurrenceTime2);
|
||||
if (reoccurrenceTime2 is null)
|
||||
return;
|
||||
_taskManager.AddTask(new UpdateLibrariesTask(TimeSpan.Parse(reoccurrenceTime2)));*/
|
||||
break;
|
||||
case "/Tasks/CreateDownloadChaptersTask":
|
||||
variables.TryGetValue("connectorName", out string? connectorName2);
|
||||
variables.TryGetValue("internalId", out string? internalId2);
|
||||
@ -240,17 +246,17 @@ public class RequestHandler
|
||||
variables.TryGetValue("lunaseaWebhook", out string? lunaseaWebhook);
|
||||
|
||||
if (downloadLocation is not null && downloadLocation.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, downloadLocation);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, _parent.logger, downloadLocation);
|
||||
if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 5 && komgaAuth.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Komga, komgaUrl, komgaAuth);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Komga, _parent.logger, komgaUrl, komgaAuth);
|
||||
if (kavitaUrl is not null && kavitaPassword is not null && kavitaUsername is not null && kavitaUrl.Length > 5 &&
|
||||
kavitaUsername.Length > 0 && kavitaPassword.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, kavitaUrl, kavitaUsername,
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, _parent.logger, kavitaUrl, kavitaUsername,
|
||||
kavitaPassword);
|
||||
if (gotifyUrl is not null && gotifyAppToken is not null && gotifyUrl.Length > 5 && gotifyAppToken.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, gotifyUrl, gotifyAppToken);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, _parent.logger, gotifyUrl, gotifyAppToken);
|
||||
if(lunaseaWebhook is not null && lunaseaWebhook.Length > 5)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.LunaSea, lunaseaWebhook);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.LunaSea, _parent.logger, lunaseaWebhook);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.TrangaTasks;
|
||||
@ -32,16 +31,16 @@ public static class Tranga_Cli
|
||||
Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, Console.Out.Encoding, logFilePath);
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "Loading Taskmanager.");
|
||||
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>());
|
||||
|
||||
|
||||
settings.logger?.WriteLine("Tranga_CLI", "User Input");
|
||||
logger.WriteLine("Tranga_CLI", "User Input");
|
||||
Console.WriteLine($"Output folder path [{settings.downloadLocation}]:");
|
||||
string? tmpPath = Console.ReadLine();
|
||||
while(tmpPath is null)
|
||||
tmpPath = Console.ReadLine();
|
||||
if (tmpPath.Length > 0)
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, tmpPath);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, logger, tmpPath);
|
||||
|
||||
Console.WriteLine($"Komga BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Komga))?.baseUrl}]:");
|
||||
string? tmpUrlKomga = Console.ReadLine();
|
||||
@ -74,7 +73,7 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Komga, tmpUrlKomga, tmpKomgaUser, tmpKomgaPass);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Komga, logger, tmpUrlKomga, tmpKomgaUser, tmpKomgaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Kavita BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Kavita))?.baseUrl}]:");
|
||||
@ -108,7 +107,7 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, tmpUrlKavita, tmpKavitaUser, tmpKavitaPass);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, logger, tmpUrlKavita, tmpKavitaUser, tmpKavitaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Gotify BaseURL [{((Gotify?)settings.notificationManagers.FirstOrDefault(lm => lm.GetType() == typeof(Gotify)))?.endpoint}]:");
|
||||
@ -122,7 +121,7 @@ public static class Tranga_Cli
|
||||
while (tmpGotifyAppToken is null || tmpGotifyAppToken.Length < 1)
|
||||
tmpGotifyAppToken = Console.ReadLine();
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, tmpGotifyUrl, tmpGotifyAppToken);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, logger, tmpGotifyUrl, tmpGotifyAppToken);
|
||||
}
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "Loaded.");
|
||||
@ -133,7 +132,7 @@ public static class Tranga_Cli
|
||||
|
||||
private static void TaskMode(TrangaSettings settings, Logger logger)
|
||||
{
|
||||
TaskManager taskManager = new (settings);
|
||||
TaskManager taskManager = new (settings, logger);
|
||||
ConsoleKey selection = ConsoleKey.EraseEndOfFile;
|
||||
PrintMenu(taskManager, taskManager.settings.downloadLocation);
|
||||
while (selection != ConsoleKey.Q)
|
||||
|
@ -1,9 +1,6 @@
|
||||
<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/=altnames/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=authorsartists/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Gotify/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Komga/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=mangakatana/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Manganato/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Mangasee/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Taskmanager/@EntryIndexedValue">True</s:Boolean>
|
||||
|
@ -7,15 +7,13 @@ namespace Tranga;
|
||||
/// Has to be Part of a publication
|
||||
/// Includes the Chapter-Name, -VolumeNumber, -ChapterNumber, the location of the chapter on the internet and the saveName of the local file.
|
||||
/// </summary>
|
||||
public readonly struct Chapter
|
||||
public struct Chapter
|
||||
{
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public Publication parentPublication { get; }
|
||||
public string? name { get; }
|
||||
public string? volumeNumber { get; }
|
||||
public string chapterNumber { get; }
|
||||
public string url { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string fileName { get; }
|
||||
|
||||
private static readonly Regex LegalCharacters = new (@"([A-z]*[0-9]* *\.*-*,*\]*\[*'*\'*\)*\(*~*!*)*");
|
||||
|
@ -3,10 +3,11 @@ using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
using static System.IO.UnixFileMode;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
namespace Tranga;
|
||||
|
||||
/// <summary>
|
||||
/// Base-Class for all Connectors
|
||||
@ -15,11 +16,15 @@ namespace Tranga.Connectors;
|
||||
public abstract class Connector
|
||||
{
|
||||
protected TrangaSettings settings { get; }
|
||||
internal DownloadClient downloadClient { get; init; } = null!;
|
||||
|
||||
protected Connector(TrangaSettings settings)
|
||||
protected DownloadClient downloadClient { get; init; } = null!;
|
||||
|
||||
protected readonly Logger? logger;
|
||||
|
||||
|
||||
protected Connector(TrangaSettings settings, Logger? logger = null)
|
||||
{
|
||||
this.settings = settings;
|
||||
this.logger = logger;
|
||||
if (!Directory.Exists(settings.coverImageCache))
|
||||
Directory.CreateDirectory(settings.coverImageCache);
|
||||
}
|
||||
@ -63,11 +68,11 @@ public abstract class Connector
|
||||
Chapter[] newChapters = this.GetChapters(publication, language);
|
||||
collection.Add(publication);
|
||||
NumberFormatInfo decimalPoint = new (){ NumberDecimalSeparator = "." };
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Checking for duplicates");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Checking for duplicates");
|
||||
List<Chapter> newChaptersList = newChapters.Where(nChapter =>
|
||||
float.Parse(nChapter.chapterNumber, decimalPoint) > publication.ignoreChaptersBelow &&
|
||||
!nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"{newChaptersList.Count} new chapters.");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"{newChaptersList.Count} new chapters.");
|
||||
|
||||
return newChaptersList;
|
||||
}
|
||||
@ -159,21 +164,22 @@ public abstract class Connector
|
||||
/// Copies the already downloaded cover from cache to downloadLocation
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to retrieve Cover for</param>
|
||||
public void CopyCoverFromCacheToDownloadLocation(Publication publication)
|
||||
/// <param name="settings">TrangaSettings</param>
|
||||
public void CopyCoverFromCacheToDownloadLocation(Publication publication, TrangaSettings settings)
|
||||
{
|
||||
settings.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
|
||||
string publicationFolder = publication.CreatePublicationFolder(settings.downloadLocation);
|
||||
DirectoryInfo dirInfo = new (publicationFolder);
|
||||
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
|
||||
return;
|
||||
}
|
||||
|
||||
string fileInCache = Path.Join(settings.coverImageCache, publication.coverFileNameInCache);
|
||||
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
|
||||
File.Copy(fileInCache, newFilePath, true);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||
@ -211,7 +217,7 @@ public abstract class Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
//Check if Publication Directory already exists
|
||||
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
|
||||
if (!Directory.Exists(directoryPath))
|
||||
@ -229,7 +235,7 @@ public abstract class Connector
|
||||
{
|
||||
string[] split = imageUrl.Split('.');
|
||||
string extension = split[^1];
|
||||
settings.logger?.WriteLine("Connector", $"Downloading Image {chapter + 1:000}/{imageUrls.Length:000} {parentTask.publication.sortName} {parentTask.publication.internalId} Vol.{parentTask.chapter.volumeNumber} Ch.{parentTask.chapter.chapterNumber} {parentTask.progress:P2}");
|
||||
logger?.WriteLine("Connector", $"Downloading Image {chapter + 1:000}/{imageUrls.Length:000} {parentTask.publication.sortName} {parentTask.publication.internalId} Vol.{parentTask.chapter.volumeNumber} Ch.{parentTask.chapter.chapterNumber} {parentTask.progress:P2}");
|
||||
HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
|
||||
if ((int)status < 200 || (int)status >= 300)
|
||||
return status;
|
||||
@ -241,7 +247,7 @@ public abstract class Connector
|
||||
if(comicInfoPath is not null)
|
||||
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
||||
|
||||
settings.logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
//ZIP-it and ship-it
|
||||
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
@ -263,7 +269,111 @@ public abstract class Connector
|
||||
using MemoryStream ms = new();
|
||||
coverResult.result.CopyTo(ms);
|
||||
File.WriteAllBytes(saveImagePath, ms.ToArray());
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
return filename;
|
||||
}
|
||||
|
||||
protected class DownloadClient
|
||||
{
|
||||
private static readonly HttpClient Client = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(60)
|
||||
};
|
||||
|
||||
private readonly Dictionary<byte, DateTime> _lastExecutedRateLimit;
|
||||
private readonly Dictionary<byte, TimeSpan> _rateLimit;
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private readonly Logger? logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a httpClient
|
||||
/// </summary>
|
||||
/// <param name="rateLimitRequestsPerMinute">Rate limits for requests. byte is RequestType, int maximum requests per minute for RequestType</param>
|
||||
/// <param name="logger"></param>
|
||||
public DownloadClient(Dictionary<byte, int> rateLimitRequestsPerMinute, Logger? logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
_lastExecutedRateLimit = new();
|
||||
_rateLimit = new();
|
||||
foreach(KeyValuePair<byte, int> limit in rateLimitRequestsPerMinute)
|
||||
_rateLimit.Add(limit.Key, TimeSpan.FromMinutes(1).Divide(limit.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request Webpage
|
||||
/// </summary>
|
||||
/// <param name="url"></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>
|
||||
public RequestResult MakeRequest(string url, byte requestType, string? referrer = null)
|
||||
{
|
||||
if (_rateLimit.TryGetValue(requestType, out TimeSpan value))
|
||||
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value));
|
||||
else
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "RequestType not configured for rate-limit.");
|
||||
return new RequestResult(HttpStatusCode.NotAcceptable, Stream.Null);
|
||||
}
|
||||
|
||||
TimeSpan rateLimitTimeout = _rateLimit[requestType]
|
||||
.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
|
||||
|
||||
if(rateLimitTimeout > TimeSpan.Zero)
|
||||
Thread.Sleep(rateLimitTimeout);
|
||||
|
||||
HttpResponseMessage? response = null;
|
||||
while (response is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
||||
if(referrer is not null)
|
||||
requestMessage.Headers.Referrer = new Uri(referrer);
|
||||
_lastExecutedRateLimit[requestType] = DateTime.Now;
|
||||
response = Client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), e.Message);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}... Retrying.");
|
||||
Thread.Sleep(_rateLimit[requestType] * 2);
|
||||
}
|
||||
}
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Request-Error {response.StatusCode}: {response.ReasonPhrase}");
|
||||
return new RequestResult(response.StatusCode, Stream.Null);
|
||||
}
|
||||
|
||||
// Request has been redirected to another page. For example, it redirects directly to the results when there is only 1 result
|
||||
if(response.RequestMessage is not null && response.RequestMessage.RequestUri is not null)
|
||||
{
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream(), true, response.RequestMessage.RequestUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream());
|
||||
}
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
public HttpStatusCode statusCode { get; }
|
||||
public Stream result { get; }
|
||||
public bool HasBeenRedirected { get; }
|
||||
public string? RedirectedToUrl { get; }
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result, bool hasBeenRedirected, string redirectedTo)
|
||||
: this(statusCode, result)
|
||||
{
|
||||
this.HasBeenRedirected = hasBeenRedirected;
|
||||
RedirectedToUrl = redirectedTo;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -2,6 +2,7 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
@ -18,7 +19,7 @@ public class MangaDex : Connector
|
||||
Author,
|
||||
}
|
||||
|
||||
public MangaDex(TrangaSettings settings) : base(settings)
|
||||
public MangaDex(TrangaSettings settings, Logger? logger = null) : base(settings, logger)
|
||||
{
|
||||
name = "MangaDex";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
@ -28,12 +29,12 @@ public class MangaDex : Connector
|
||||
{(byte)RequestType.AtHomeServer, 40},
|
||||
{(byte)RequestType.CoverUrl, 250},
|
||||
{(byte)RequestType.Author, 250}
|
||||
}, settings.logger);
|
||||
}, logger);
|
||||
}
|
||||
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
const int limit = 100; //How many values we want returned at once
|
||||
int offset = 0; //"Page"
|
||||
int total = int.MaxValue; //How many total results are there, is updated on first request
|
||||
@ -59,7 +60,7 @@ public class MangaDex : Connector
|
||||
//Loop each Manga and extract information from JSON
|
||||
foreach (JsonNode? mangeNode in mangaInResult)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}");
|
||||
JsonObject manga = (JsonObject)mangeNode!;
|
||||
JsonObject attributes = manga["attributes"]!.AsObject();
|
||||
|
||||
@ -146,13 +147,13 @@ public class MangaDex : Connector
|
||||
}
|
||||
}
|
||||
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})");
|
||||
return publications.ToArray();
|
||||
}
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
const int limit = 100; //How many values we want returned at once
|
||||
int offset = 0; //"Page"
|
||||
int total = int.MaxValue; //How many total results are there, is updated on first request
|
||||
@ -203,7 +204,7 @@ public class MangaDex : Connector
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting {chapters.Count} Chapters for {publication.internalId}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting {chapters.Count} Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
@ -211,7 +212,7 @@ public class MangaDex : Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.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
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer);
|
||||
@ -238,10 +239,10 @@ public class MangaDex : Connector
|
||||
|
||||
private string? GetCoverUrl(string publicationId, string? posterId)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}");
|
||||
if (posterId is null)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting");
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -257,7 +258,7 @@ public class MangaDex : Connector
|
||||
string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>();
|
||||
|
||||
string coverUrl = $"https://uploads.mangadex.org/covers/{publicationId}/{fileName}";
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}");
|
||||
return coverUrl;
|
||||
}
|
||||
|
||||
@ -276,7 +277,7 @@ public class MangaDex : Connector
|
||||
|
||||
string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>();
|
||||
ret.Add(authorName);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
@ -2,6 +2,7 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using HtmlAgilityPack;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
@ -10,32 +11,31 @@ public class MangaKatana : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
|
||||
public MangaKatana(TrangaSettings settings) : base(settings)
|
||||
public MangaKatana(TrangaSettings settings, Logger? logger = null) : base(settings, logger)
|
||||
{
|
||||
this.name = "MangaKatana";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{1, 60}
|
||||
}, settings.logger);
|
||||
{(byte)1, 60}
|
||||
}, logger);
|
||||
}
|
||||
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_');
|
||||
string requestUrl = $"https://mangakatana.com/?search={sanitizedTitle}&search_by=book_name";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
// ReSharper disable once MergeIntoPattern
|
||||
// If a single result is found, the user will be redirected to the results directly instead of a result page
|
||||
if(requestResult.hasBeenRedirected
|
||||
&& requestResult.redirectedToUrl is not null
|
||||
&& requestResult.redirectedToUrl.Contains("mangakatana.com/manga"))
|
||||
if(requestResult.HasBeenRedirected
|
||||
&& requestResult.RedirectedToUrl is not null
|
||||
&& requestResult.RedirectedToUrl.Contains("mangakatana.com/manga"))
|
||||
{
|
||||
return new [] { ParseSinglePublicationFromHtml(requestResult.result, requestResult.redirectedToUrl.Split('/')[^1]) };
|
||||
return new Publication[] { ParseSinglePublicationFromHtml(requestResult.result, requestResult.RedirectedToUrl.Split('/')[^1]) };
|
||||
}
|
||||
|
||||
return ParsePublicationsFromHtml(requestResult.result);
|
||||
@ -59,7 +59,7 @@ public class MangaKatana : Connector
|
||||
foreach (string url in urls)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(url, 1);
|
||||
downloadClient.MakeRequest(url, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -108,6 +108,7 @@ public class MangaKatana : Connector
|
||||
case "genres":
|
||||
tags = row.SelectNodes("div").Last().Descendants("a").Select(a => a.InnerText).ToHashSet();
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -135,11 +136,11 @@ public class MangaKatana : Connector
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
string requestUrl = $"https://mangakatana.com/manga/{publication.publicationId}";
|
||||
// Leaving this in for verification if the page exists
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Chapter>();
|
||||
|
||||
@ -149,7 +150,7 @@ public class MangaKatana : Connector
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestUrl);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
@ -168,7 +169,7 @@ public class MangaKatana : Connector
|
||||
string fullString = chapterInfo.Descendants("a").First().InnerText;
|
||||
|
||||
string? volumeNumber = fullString.Contains("Vol.") ? fullString.Replace("Vol.", "").Split(' ')[0] : null;
|
||||
string chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Split(" ")[0].Replace('-', '.');
|
||||
string? chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Split(" ")[0].Replace('-', '.');
|
||||
string chapterName = string.Concat(fullString.Split(':')[1..]);
|
||||
string url = chapterInfo.Descendants("a").First()
|
||||
.GetAttributeValue("href", "");
|
||||
@ -182,11 +183,11 @@ public class MangaKatana : Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.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}");
|
||||
string requestUrl = chapter.url;
|
||||
// Leaving this in to check if the page exists
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return requestResult.statusCode;
|
||||
|
||||
@ -195,7 +196,7 @@ public class MangaKatana : Connector
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, "https://mangakatana.com/", cancellationToken);
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), (byte)1, parentTask, comicInfoPath, "https://mangakatana.com/", cancellationToken);
|
||||
}
|
||||
|
||||
private string[] ParseImageUrlsFromHtml(string mangaUrl)
|
||||
@ -208,8 +209,6 @@ public class MangaKatana : Connector
|
||||
.Replace("\r", "")
|
||||
.Replace("\n", "")
|
||||
.Replace("\t", "");
|
||||
|
||||
// ReSharper disable once StringLiteralTypo
|
||||
string regexPat = @"(var thzq=\[')(.*)(,];function)";
|
||||
var group = Regex.Matches(js, regexPat).First().Groups[2].Value.Replace("'", "");
|
||||
var urls = group.Split(',');
|
||||
|
@ -2,6 +2,7 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using HtmlAgilityPack;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
@ -10,22 +11,22 @@ public class Manganato : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
|
||||
public Manganato(TrangaSettings settings) : base(settings)
|
||||
public Manganato(TrangaSettings settings, Logger? logger = null) : base(settings, logger)
|
||||
{
|
||||
this.name = "Manganato";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{1, 60}
|
||||
}, settings.logger);
|
||||
{(byte)1, 60}
|
||||
}, logger);
|
||||
}
|
||||
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*")).ToLower();
|
||||
string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -50,7 +51,7 @@ public class Manganato : Connector
|
||||
foreach (string url in urls)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(url, 1);
|
||||
downloadClient.MakeRequest(url, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -102,6 +103,7 @@ public class Manganato : Connector
|
||||
string[] genres = value.Split(" - ");
|
||||
tags = genres.ToHashSet();
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -125,10 +127,10 @@ public class Manganato : Connector
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={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, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Chapter>();
|
||||
|
||||
@ -138,7 +140,7 @@ public class Manganato : Connector
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestResult.result);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
@ -157,7 +159,7 @@ public class Manganato : Connector
|
||||
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? 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", "");
|
||||
@ -171,10 +173,10 @@ public class Manganato : Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.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}");
|
||||
string requestUrl = chapter.url;
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return requestResult.statusCode;
|
||||
|
||||
@ -183,7 +185,7 @@ public class Manganato : Connector
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, "https://chapmanganato.com/", cancellationToken);
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), (byte)1, parentTask, comicInfoPath, "https://chapmanganato.com/", cancellationToken);
|
||||
}
|
||||
|
||||
private string[] ParseImageUrlsFromHtml(Stream html)
|
||||
|
@ -3,6 +3,7 @@ using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using HtmlAgilityPack;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using PuppeteerSharp;
|
||||
using Tranga.TrangaTasks;
|
||||
@ -12,16 +13,16 @@ namespace Tranga.Connectors;
|
||||
public class Mangasee : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
private IBrowser? _browser;
|
||||
private IBrowser? _browser = null;
|
||||
private const string ChromiumVersion = "1154303";
|
||||
|
||||
public Mangasee(TrangaSettings settings) : base(settings)
|
||||
public Mangasee(TrangaSettings settings, Logger? logger = null) : base(settings, logger)
|
||||
{
|
||||
this.name = "Mangasee";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{ 1, 60 }
|
||||
}, settings.logger);
|
||||
{ (byte)1, 60 }
|
||||
}, logger);
|
||||
|
||||
Task d = new Task(DownloadBrowser);
|
||||
d.Start();
|
||||
@ -34,31 +35,31 @@ public class Mangasee : Connector
|
||||
browserFetcher.Remove(rev);
|
||||
if (!browserFetcher.LocalRevisions().Contains(ChromiumVersion))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser");
|
||||
DateTime last = DateTime.Now.Subtract(TimeSpan.FromSeconds(5));
|
||||
browserFetcher.DownloadProgressChanged += (_, args) =>
|
||||
browserFetcher.DownloadProgressChanged += (sender, args) =>
|
||||
{
|
||||
double currentBytes = Convert.ToDouble(args.BytesReceived) / Convert.ToDouble(args.TotalBytesToReceive);
|
||||
if (args.TotalBytesToReceive == args.BytesReceived)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Browser downloaded.");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Browser downloaded.");
|
||||
}
|
||||
else if (DateTime.Now > last.AddSeconds(5))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}");
|
||||
last = DateTime.Now;
|
||||
}
|
||||
|
||||
};
|
||||
if (!browserFetcher.CanDownloadAsync(ChromiumVersion).Result)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}");
|
||||
return;
|
||||
}
|
||||
await browserFetcher.DownloadAsync(ChromiumVersion);
|
||||
}
|
||||
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Starting browser.");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Starting browser.");
|
||||
this._browser = await Puppeteer.LaunchAsync(new LaunchOptions
|
||||
{
|
||||
Headless = true,
|
||||
@ -73,10 +74,10 @@ public class Mangasee : Connector
|
||||
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string requestUrl = $"https://mangasee123.com/_search.php";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -98,7 +99,7 @@ public class Mangasee : Connector
|
||||
queryFiltered = queryFiltered.Where(item => item.Value >= publicationTitle.Split(' ').Length - 1)
|
||||
.ToDictionary(item => item.Key, item => item.Value);
|
||||
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got {queryFiltered.Count} Publications (title={publicationTitle})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Got {queryFiltered.Count} Publications (title={publicationTitle})");
|
||||
|
||||
HashSet<Publication> ret = new();
|
||||
List<SearchResultItem> orderedFiltered =
|
||||
@ -108,10 +109,10 @@ public class Mangasee : Connector
|
||||
foreach (SearchResultItem orderedItem in orderedFiltered)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", 1);
|
||||
downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", (byte)1);
|
||||
if ((int)requestResult.statusCode >= 200 || (int)requestResult.statusCode < 300)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Retrieving Publication info: {orderedItem.s} {index++}/{orderedFiltered.Count}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Retrieving Publication info: {orderedItem.s} {index++}/{orderedFiltered.Count}");
|
||||
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, orderedItem.s, orderedItem.i, orderedItem.a));
|
||||
}
|
||||
}
|
||||
@ -177,17 +178,11 @@ public class Mangasee : Connector
|
||||
// ReSharper disable once ClassNeverInstantiated.Local Will be instantiated during deserialization
|
||||
private class SearchResultItem
|
||||
{
|
||||
public string i { get; init; }
|
||||
public string s { get; init; }
|
||||
public string[] a { get; init; }
|
||||
|
||||
[JsonConstructor]
|
||||
public SearchResultItem(string i, string s, string[] a)
|
||||
{
|
||||
this.i = i;
|
||||
this.s = s;
|
||||
this.a = a;
|
||||
}
|
||||
#pragma warning disable CS8618 //Will always be set
|
||||
public string i { get; set; }
|
||||
public string s { get; set; }
|
||||
public string[] a { get; set; }
|
||||
#pragma warning restore CS8618
|
||||
|
||||
public int GetMatches(string title)
|
||||
{
|
||||
@ -221,7 +216,7 @@ public class Mangasee : Connector
|
||||
List<Chapter> ret = new();
|
||||
foreach (XElement chapter in chapterItems)
|
||||
{
|
||||
string volumeNumber = "1";
|
||||
string? volumeNumber = "1";
|
||||
string chapterName = chapter.Descendants("title").First().Value;
|
||||
string chapterNumber = Regex.Matches(chapterName, "[0-9]+")[^1].ToString();
|
||||
|
||||
@ -235,7 +230,7 @@ public class Mangasee : Connector
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
@ -245,13 +240,13 @@ public class Mangasee : Connector
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
while (this._browser is null && !(cancellationToken?.IsCancellationRequested??false))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download...");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download...");
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
|
||||
settings.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}");
|
||||
IPage page = _browser!.NewPageAsync().Result;
|
||||
IResponse response = page.GoToAsync(chapter.url).Result;
|
||||
if (response.Ok)
|
||||
@ -268,7 +263,7 @@ public class Mangasee : Connector
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), (byte)1, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
}
|
||||
return response.Status;
|
||||
}
|
||||
|
@ -1,108 +0,0 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
internal class DownloadClient
|
||||
{
|
||||
private static readonly HttpClient Client = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(60)
|
||||
};
|
||||
|
||||
private readonly Dictionary<byte, DateTime> _lastExecutedRateLimit;
|
||||
private readonly Dictionary<byte, TimeSpan> _rateLimit;
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private readonly Logger? logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a httpClient
|
||||
/// </summary>
|
||||
/// <param name="rateLimitRequestsPerMinute">Rate limits for requests. byte is RequestType, int maximum requests per minute for RequestType</param>
|
||||
/// <param name="logger"></param>
|
||||
public DownloadClient(Dictionary<byte, int> rateLimitRequestsPerMinute, Logger? logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
_lastExecutedRateLimit = new();
|
||||
_rateLimit = new();
|
||||
foreach(KeyValuePair<byte, int> limit in rateLimitRequestsPerMinute)
|
||||
_rateLimit.Add(limit.Key, TimeSpan.FromMinutes(1).Divide(limit.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request Webpage
|
||||
/// </summary>
|
||||
/// <param name="url"></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>
|
||||
public RequestResult MakeRequest(string url, byte requestType, string? referrer = null)
|
||||
{
|
||||
if (_rateLimit.TryGetValue(requestType, out TimeSpan value))
|
||||
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value));
|
||||
else
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "RequestType not configured for rate-limit.");
|
||||
return new RequestResult(HttpStatusCode.NotAcceptable, Stream.Null);
|
||||
}
|
||||
|
||||
TimeSpan rateLimitTimeout = _rateLimit[requestType]
|
||||
.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
|
||||
|
||||
if(rateLimitTimeout > TimeSpan.Zero)
|
||||
Thread.Sleep(rateLimitTimeout);
|
||||
|
||||
HttpResponseMessage? response = null;
|
||||
while (response is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
||||
if(referrer is not null)
|
||||
requestMessage.Headers.Referrer = new Uri(referrer);
|
||||
_lastExecutedRateLimit[requestType] = DateTime.Now;
|
||||
response = Client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), e.Message);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}... Retrying.");
|
||||
Thread.Sleep(_rateLimit[requestType] * 2);
|
||||
}
|
||||
}
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Request-Error {response.StatusCode}: {response.ReasonPhrase}");
|
||||
return new RequestResult(response.StatusCode, Stream.Null);
|
||||
}
|
||||
|
||||
// Request has been redirected to another page. For example, it redirects directly to the results when there is only 1 result
|
||||
if(response.RequestMessage is not null && response.RequestMessage.RequestUri is not null)
|
||||
{
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream(), true, response.RequestMessage.RequestUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream());
|
||||
}
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
public HttpStatusCode statusCode { get; }
|
||||
public Stream result { get; }
|
||||
public bool hasBeenRedirected { get; }
|
||||
public string? redirectedToUrl { get; }
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result, bool hasBeenRedirected, string redirectedTo)
|
||||
: this(statusCode, result)
|
||||
{
|
||||
this.hasBeenRedirected = hasBeenRedirected;
|
||||
redirectedToUrl = redirectedTo;
|
||||
}
|
||||
}
|
||||
}
|
@ -3,8 +3,9 @@ using System.Net.Http.Headers;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace Tranga.LibraryManagers;
|
||||
namespace Tranga;
|
||||
|
||||
public abstract class LibraryManager
|
||||
{
|
||||
@ -14,10 +15,8 @@ public abstract class LibraryManager
|
||||
Kavita = 1
|
||||
}
|
||||
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public LibraryType libraryType { get; }
|
||||
public string baseUrl { get; }
|
||||
// ReSharper disable once MemberCanBeProtected.Global
|
||||
public string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems
|
||||
protected Logger? logger;
|
||||
|
@ -36,7 +36,7 @@ public class Kavita : LibraryManager
|
||||
HttpResponseMessage response = client.Send(requestMessage);
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(response.Content.ReadAsStream());
|
||||
if (result is not null)
|
||||
return result["token"]!.GetValue<string>();
|
||||
return result!["token"]!.GetValue<string>();
|
||||
else return "";
|
||||
}
|
||||
|
||||
@ -73,7 +73,7 @@ public class Kavita : LibraryManager
|
||||
{
|
||||
var jObject = (JsonObject?)jsonNode;
|
||||
int libraryId = jObject!["id"]!.GetValue<int>();
|
||||
string libraryName = jObject["name"]!.GetValue<string>();
|
||||
string libraryName = jObject!["name"]!.GetValue<string>();
|
||||
ret.Add(new KavitaLibrary(libraryId, libraryName));
|
||||
}
|
||||
|
||||
@ -83,7 +83,6 @@ public class Kavita : LibraryManager
|
||||
private struct KavitaLibrary
|
||||
{
|
||||
public int id { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||
public string name { get; }
|
||||
|
||||
public KavitaLibrary(int id, string name)
|
||||
|
@ -54,7 +54,7 @@ public class Komga : LibraryManager
|
||||
{
|
||||
var jObject = (JsonObject?)jsonNode;
|
||||
string libraryId = jObject!["id"]!.GetValue<string>();
|
||||
string libraryName = jObject["name"]!.GetValue<string>();
|
||||
string libraryName = jObject!["name"]!.GetValue<string>();
|
||||
ret.Add(new KomgaLibrary(libraryId, libraryName));
|
||||
}
|
||||
|
||||
@ -64,7 +64,6 @@ public class Komga : LibraryManager
|
||||
private struct KomgaLibrary
|
||||
{
|
||||
public string id { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||
public string name { get; }
|
||||
|
||||
public KomgaLibrary(string id, string name)
|
||||
|
@ -1,5 +1,5 @@
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.TrangaTasks;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
|
@ -1,8 +1,9 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.NotificationManagers;
|
||||
|
||||
namespace Tranga.NotificationManagers;
|
||||
namespace Tranga;
|
||||
|
||||
public abstract class NotificationManager
|
||||
{
|
@ -7,11 +7,9 @@ namespace Tranga.NotificationManagers;
|
||||
public class Gotify : NotificationManager
|
||||
{
|
||||
public string endpoint { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string appToken { get; }
|
||||
private readonly HttpClient _client = new();
|
||||
|
||||
[JsonConstructor]
|
||||
public Gotify(string endpoint, string appToken, Logger? logger = null) : base(NotificationManagerType.Gotify, logger)
|
||||
{
|
||||
this.endpoint = endpoint;
|
||||
@ -35,7 +33,6 @@ public class Gotify : NotificationManager
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable four times UnusedAutoPropertyAccessor.Local
|
||||
public string message { get; }
|
||||
public long priority { get; }
|
||||
public string title { get; }
|
||||
|
@ -6,11 +6,8 @@ namespace Tranga.NotificationManagers;
|
||||
|
||||
public class LunaSea : NotificationManager
|
||||
{
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string id { get; init; }
|
||||
public string id { get; }
|
||||
private readonly HttpClient _client = new();
|
||||
|
||||
[JsonConstructor]
|
||||
public LunaSea(string id, Logger? logger = null) : base(NotificationManagerType.LunaSea, logger)
|
||||
{
|
||||
this.id = id;
|
||||
@ -32,7 +29,6 @@ public class LunaSea : NotificationManager
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable twice UnusedAutoPropertyAccessor.Local
|
||||
public string title { get; }
|
||||
public string body { get; }
|
||||
|
||||
|
@ -13,20 +13,15 @@ public struct Publication
|
||||
{
|
||||
public string sortName { get; }
|
||||
public List<string> authors { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public Dictionary<string,string> altTitles { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
// ReSharper disable trice MemberCanBePrivate.Global, trust
|
||||
public string? description { get; }
|
||||
public string[] tags { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public string? posterUrl { get; }
|
||||
public string? coverFileNameInCache { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public Dictionary<string,string> links { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public int? year { get; }
|
||||
public string? originalLanguage { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string status { get; }
|
||||
public string folderName { get; }
|
||||
public string publicationId { get; }
|
||||
@ -79,7 +74,7 @@ public struct Publication
|
||||
}
|
||||
|
||||
/// <returns>Serialized JSON String for series.json</returns>
|
||||
private string GetSeriesInfoJson()
|
||||
public string GetSeriesInfoJson()
|
||||
{
|
||||
SeriesInfo si = new (new Metadata(this.sortName, this.year.ToString() ?? string.Empty, this.status, this.description ?? ""));
|
||||
return System.Text.Json.JsonSerializer.Serialize(si);
|
||||
|
@ -1,4 +1,5 @@
|
||||
using Newtonsoft.Json;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
@ -16,21 +17,23 @@ public class TaskManager
|
||||
private bool _continueRunning = true;
|
||||
private readonly Connector[] _connectors;
|
||||
public TrangaSettings settings { get; }
|
||||
private Logger? logger { get; }
|
||||
|
||||
public TaskManager(TrangaSettings settings)
|
||||
public TaskManager(TrangaSettings settings, Logger? logger = null)
|
||||
{
|
||||
settings.logger?.WriteLine("Tranga", value: "\n"+
|
||||
@"-----------------------------------------------------------------"+"\n"+
|
||||
@" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+
|
||||
@" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+
|
||||
@" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+
|
||||
@"-----------------------------------------------------------------");
|
||||
this.logger = logger;
|
||||
logger?.WriteLine("Tranga", value: "\n"+
|
||||
@"-----------------------------------------------------------------"+"\n"+
|
||||
@" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+
|
||||
@" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+
|
||||
@" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+
|
||||
@"-----------------------------------------------------------------");
|
||||
this._connectors = new Connector[]
|
||||
{
|
||||
new MangaDex(settings),
|
||||
new Manganato(settings),
|
||||
new Mangasee(settings),
|
||||
new MangaKatana(settings)
|
||||
new MangaDex(settings, logger),
|
||||
new Manganato(settings, logger),
|
||||
new Mangasee(settings, logger),
|
||||
new MangaKatana(settings, logger)
|
||||
};
|
||||
|
||||
this.settings = settings;
|
||||
@ -47,7 +50,7 @@ public class TaskManager
|
||||
/// </summary>
|
||||
private void TaskCheckerThread()
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
int waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
while (_continueRunning)
|
||||
{
|
||||
@ -134,7 +137,7 @@ public class TaskManager
|
||||
CancellationTokenSource cToken = new ();
|
||||
Task t = new(() =>
|
||||
{
|
||||
task.Execute(this, cToken.Token);
|
||||
task.Execute(this, this.logger, cToken.Token);
|
||||
}, cToken.Token);
|
||||
_runningTasks.Add(task, cToken);
|
||||
t.Start();
|
||||
@ -146,7 +149,7 @@ public class TaskManager
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
//Only one UpdateKomgaLibrary Task
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task.");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task.");
|
||||
if (GetTasksMatching(newTask).FirstOrDefault() is { } exists)
|
||||
_allTasks.Remove(exists);
|
||||
_allTasks.Add(newTask);
|
||||
@ -155,19 +158,19 @@ public class TaskManager
|
||||
default:
|
||||
if (!GetTasksMatching(newTask).Any())
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}");
|
||||
_allTasks.Add(newTask);
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
else
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteTask(TrangaTask removeTask)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}");
|
||||
if(_allTasks.Contains(removeTask))
|
||||
_allTasks.Remove(removeTask);
|
||||
removeTask.parentTask?.RemoveChildTask(removeTask);
|
||||
@ -181,7 +184,6 @@ public class TaskManager
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public IEnumerable<TrangaTask> GetTasksMatching(TrangaTask mTask)
|
||||
{
|
||||
switch (mTask.task)
|
||||
@ -319,7 +321,7 @@ public class TaskManager
|
||||
/// <param name="force">If force is true, tasks are aborted.</param>
|
||||
public void Shutdown(bool force = false)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
|
||||
_continueRunning = false;
|
||||
ExportDataAndSettings();
|
||||
|
||||
@ -329,17 +331,18 @@ public class TaskManager
|
||||
//Wait for tasks to finish
|
||||
while(_allTasks.Any(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Enqueued))
|
||||
Thread.Sleep(10);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!");
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
private void ImportData()
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Importing Data");
|
||||
logger?.WriteLine(this.GetType().ToString(), "Importing Data");
|
||||
string buffer;
|
||||
if (File.Exists(settings.tasksFilePath))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
|
||||
string buffer = File.ReadAllText(settings.tasksFilePath);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
|
||||
buffer = File.ReadAllText(settings.tasksFilePath);
|
||||
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
|
||||
}
|
||||
|
||||
@ -359,10 +362,10 @@ public class TaskManager
|
||||
/// </summary>
|
||||
private void ExportDataAndSettings()
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
|
||||
settings.ExportSettings();
|
||||
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}");
|
||||
while(IsFileInUse(settings.tasksFilePath))
|
||||
Thread.Sleep(50);
|
||||
File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(this._allTasks));
|
||||
|
@ -1,4 +1,5 @@
|
||||
using Logging;
|
||||
using System.Text.RegularExpressions;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.NotificationManagers;
|
||||
@ -7,18 +8,17 @@ namespace Tranga;
|
||||
|
||||
public class TrangaSettings
|
||||
{
|
||||
public string downloadLocation { get; private set; }
|
||||
public string workingDirectory { get; init; }
|
||||
public string downloadLocation { get; set; }
|
||||
public string workingDirectory { get; set; }
|
||||
[JsonIgnore] public string settingsFilePath => Path.Join(workingDirectory, "settings.json");
|
||||
[JsonIgnore] public string tasksFilePath => Path.Join(workingDirectory, "tasks.json");
|
||||
[JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache");
|
||||
public HashSet<LibraryManager> libraryManagers { get; }
|
||||
public HashSet<NotificationManager> notificationManagers { get; }
|
||||
public ushort? version { get; set; }
|
||||
[JsonIgnore] public Logger? logger { get; init; }
|
||||
|
||||
public TrangaSettings(string downloadLocation, string workingDirectory, HashSet<LibraryManager>? libraryManagers,
|
||||
HashSet<NotificationManager>? notificationManagers, Logger? logger)
|
||||
HashSet<NotificationManager>? notificationManagers)
|
||||
{
|
||||
if (downloadLocation.Length < 1 || workingDirectory.Length < 1)
|
||||
throw new ArgumentException("Download-location and working-directory paths can not be empty!");
|
||||
@ -26,14 +26,13 @@ public class TrangaSettings
|
||||
this.downloadLocation = downloadLocation;
|
||||
this.libraryManagers = libraryManagers??new();
|
||||
this.notificationManagers = notificationManagers??new();
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public static TrangaSettings LoadSettings(string importFilePath, Logger? logger)
|
||||
{
|
||||
if (!File.Exists(importFilePath))
|
||||
return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"),
|
||||
Directory.GetCurrentDirectory(), new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
Directory.GetCurrentDirectory(), new HashSet<LibraryManager>(), new HashSet<NotificationManager>());
|
||||
|
||||
string toRead = File.ReadAllText(importFilePath);
|
||||
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead,
|
||||
@ -72,7 +71,7 @@ public class TrangaSettings
|
||||
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this));
|
||||
}
|
||||
|
||||
public void UpdateSettings(UpdateField field, params string[] values)
|
||||
public void UpdateSettings(UpdateField field, Logger? logger = null, params string[] values)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
@ -85,19 +84,19 @@ public class TrangaSettings
|
||||
if (values.Length != 2)
|
||||
return;
|
||||
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
|
||||
libraryManagers.Add(new Komga(values[0], values[1], this.logger));
|
||||
libraryManagers.Add(new Komga(values[0], values[1], logger));
|
||||
break;
|
||||
case UpdateField.Kavita:
|
||||
if (values.Length != 3)
|
||||
return;
|
||||
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
|
||||
libraryManagers.Add(new Kavita(values[0], values[1], values[2], this.logger));
|
||||
libraryManagers.Add(new Kavita(values[0], values[1], values[2], logger));
|
||||
break;
|
||||
case UpdateField.Gotify:
|
||||
if (values.Length != 2)
|
||||
return;
|
||||
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(Gotify));
|
||||
Gotify newGotify = new(values[0], values[1], this.logger);
|
||||
Gotify newGotify = new(values[0], values[1], logger);
|
||||
notificationManagers.Add(newGotify);
|
||||
newGotify.SendNotification("Success!", "Gotify was added to Tranga!");
|
||||
break;
|
||||
@ -105,7 +104,7 @@ public class TrangaSettings
|
||||
if(values.Length != 1)
|
||||
return;
|
||||
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(LunaSea));
|
||||
LunaSea newLunaSea = new(values[0], this.logger);
|
||||
LunaSea newLunaSea = new(values[0], logger);
|
||||
notificationManagers.Add(newLunaSea);
|
||||
newLunaSea.SendNotification("Success!", "LunaSea was added to Tranga!");
|
||||
break;
|
||||
|
@ -1,10 +1,12 @@
|
||||
using System.Net;
|
||||
using System.Text.Json.Serialization;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.TrangaTasks;
|
||||
using JsonConverter = Newtonsoft.Json.JsonConverter;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
namespace Tranga;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information on Task, when implementing new Tasks also update the serializer
|
||||
@ -14,7 +16,8 @@ namespace Tranga.TrangaTasks;
|
||||
[JsonDerivedType(typeof(DownloadChapterTask), 4)]
|
||||
public abstract class TrangaTask
|
||||
{
|
||||
// ReSharper disable once MemberCanBeProtected.Global
|
||||
// ReSharper disable once CommentTypo ...Tell me why!
|
||||
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
|
||||
public TimeSpan reoccurrence { get; }
|
||||
public DateTime lastExecuted { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore] public ExecutionState state { get; set; }
|
||||
@ -24,12 +27,9 @@ public abstract class TrangaTask
|
||||
public string? parentTaskId { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore] internal HashSet<TrangaTask> childTasks { get; }
|
||||
public double progress => GetProgress();
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionStarted { get; private set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime lastChange { get; internal set; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionApproximatelyFinished => lastChange.Add(GetRemainingTime());
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public TimeSpan executionApproximatelyRemaining => executionApproximatelyFinished.Subtract(DateTime.Now);
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime nextExecution => lastExecuted.Add(reoccurrence);
|
||||
|
||||
@ -52,8 +52,9 @@ public abstract class TrangaTask
|
||||
/// BL for concrete Tasks
|
||||
/// </summary>
|
||||
/// <param name="taskManager"></param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
protected abstract HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null);
|
||||
protected abstract HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null);
|
||||
|
||||
public abstract TrangaTask Clone();
|
||||
|
||||
@ -63,17 +64,18 @@ public abstract class TrangaTask
|
||||
/// Execute the task
|
||||
/// </summary>
|
||||
/// <param name="taskManager">Should be the parent taskManager</param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public void Execute(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
public void Execute(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
this.state = ExecutionState.Running;
|
||||
this.executionStarted = DateTime.Now;
|
||||
this.lastChange = DateTime.Now;
|
||||
if(parentTask is not null && parentTask.childTasks.All(ct => ct.state is ExecutionState.Waiting or ExecutionState.Failed))
|
||||
parentTask.executionStarted = DateTime.Now;
|
||||
|
||||
HttpStatusCode statusCode = ExecuteTask(taskManager, cancellationToken);
|
||||
HttpStatusCode statusCode = ExecuteTask(taskManager, logger, cancellationToken);
|
||||
|
||||
if ((int)statusCode >= 200 && (int)statusCode < 300)
|
||||
{
|
||||
@ -89,7 +91,7 @@ public abstract class TrangaTask
|
||||
if (this is DownloadChapterTask)
|
||||
taskManager.DeleteTask(this);
|
||||
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
}
|
||||
|
||||
public void AddChildTask(TrangaTask childTask)
|
@ -1,7 +1,5 @@
|
||||
using System.Net;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -9,11 +7,10 @@ public class DownloadChapterTask : TrangaTask
|
||||
{
|
||||
public string connectorName { get; }
|
||||
public Publication publication { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string language { get; }
|
||||
public Chapter chapter { get; }
|
||||
|
||||
private double _dctProgress;
|
||||
private double _dctProgress = 0;
|
||||
|
||||
public DownloadChapterTask(string connectorName, Publication publication, Chapter chapter, string language = "en", MonitorPublicationTask? parentTask = null) : base(Task.DownloadChapter, TimeSpan.Zero, parentTask)
|
||||
{
|
||||
@ -23,12 +20,12 @@ public class DownloadChapterTask : TrangaTask
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
Connector connector = taskManager.GetConnector(this.connectorName);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(this.publication);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(this.publication, taskManager.settings);
|
||||
HttpStatusCode downloadSuccess = connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken);
|
||||
if ((int)downloadSuccess >= 200 && (int)downloadSuccess < 300)
|
||||
{
|
||||
|
@ -1,5 +1,5 @@
|
||||
using System.Net;
|
||||
using Tranga.Connectors;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -7,7 +7,6 @@ public class MonitorPublicationTask : TrangaTask
|
||||
{
|
||||
public string connectorName { get; }
|
||||
public Publication publication { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string language { get; }
|
||||
public MonitorPublicationTask(string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(Task.MonitorPublication, reoccurrence)
|
||||
{
|
||||
@ -16,7 +15,7 @@ public class MonitorPublicationTask : TrangaTask
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
@ -26,7 +25,7 @@ public class MonitorPublicationTask : TrangaTask
|
||||
publication.CreatePublicationFolder(taskManager.settings.downloadLocation);
|
||||
List<Chapter> newChapters = connector.GetNewChaptersList(publication, language, ref taskManager.collection);
|
||||
|
||||
connector.CopyCoverFromCacheToDownloadLocation(publication);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(publication, taskManager.settings);
|
||||
|
||||
publication.SaveSeriesInfoJson(taskManager.settings.downloadLocation);
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -11,7 +12,7 @@ public class UpdateLibrariesTask : TrangaTask
|
||||
{
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
return HttpStatusCode.BadRequest;
|
||||
}
|
||||
|
@ -106,6 +106,11 @@ function CreateMonitorTask(connectorName, internalId, reoccurrence, language){
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function CreateUpdateLibraryTask(reoccurrence){
|
||||
var uri = apiUri + `/Tasks/CreateUpdateLibraryTask?reoccurrenceTime=${reoccurrence}`;
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function CreateDownloadChaptersTask(connectorName, internalId, chapters, language){
|
||||
var uri = apiUri + `/Tasks/CreateDownloadChaptersTask?connectorName=${connectorName}&internalId=${internalId}&chapters=${chapters}&language=${language}`;
|
||||
PostData(uri);
|
||||
|
@ -70,6 +70,13 @@ createDownloadChapterTaskButton.addEventListener("click", () => {
|
||||
OpenDownloadChapterTaskPopup();
|
||||
});
|
||||
publicationTaskStart.addEventListener("click", () => StartTaskClick());
|
||||
settingApiUri.addEventListener("keypress", (event) => {
|
||||
if(event.key === "Enter"){
|
||||
apiUri = settingApiUri.value;
|
||||
setTimeout(() => GetSettingsClick(), 100);
|
||||
document.cookie = `apiUri=${apiUri};`;
|
||||
}
|
||||
});
|
||||
searchPublicationQuery.addEventListener("keypress", (event) => {
|
||||
if(event.key === "Enter"){
|
||||
NewSearch();
|
||||
@ -330,10 +337,12 @@ function UpdateLibrarySettings(){
|
||||
var auth = utf8_to_b64(`${settingKomgaUser.value}:${settingKomgaPass.value}`);
|
||||
console.log(auth);
|
||||
UpdateKomga(settingKomgaUrl.value, auth);
|
||||
CreateUpdateLibraryTask(libraryUpdateTime.value);
|
||||
}
|
||||
|
||||
if(settingKavitaUrl.value != "" && settingKavitaUser.value != "" && settingKavitaPass.value != ""){
|
||||
UpdateKavita(settingKavitaUrl.value, settingKavitaUser.value, settingKavitaPass.value);
|
||||
CreateUpdateLibraryTask(libraryUpdateTime.value);
|
||||
}
|
||||
|
||||
if(settingGotifyUrl.value != "" && settingGotifyAppToken.value != ""){
|
||||
@ -343,11 +352,6 @@ function UpdateLibrarySettings(){
|
||||
if(settingLunaseaWebhook.value != ""){
|
||||
UpdateLunaSea(settingLunaseaWebhook.value);
|
||||
}
|
||||
|
||||
if(settingApiUri.value != ""){
|
||||
apiUri = settingApiUri.value;
|
||||
document.cookie = `apiUri=${apiUri};`;
|
||||
}
|
||||
|
||||
setTimeout(() => GetSettingsClick(), 200);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user