Moved libraryManagers, notificationManagers and logger to commonObjects class.

This commit is contained in:
glax 2023-07-30 23:31:25 +02:00
parent f9b5e05974
commit 3d6657b483
11 changed files with 229 additions and 133 deletions

View File

@ -27,25 +27,25 @@ public static class Program
TrangaSettings settings; TrangaSettings settings;
if (File.Exists(settingsFilePath)) if (File.Exists(settingsFilePath))
settings = TrangaSettings.LoadSettings(settingsFilePath, logger); settings = TrangaSettings.LoadSettings(settingsFilePath);
else else
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger); settings = new TrangaSettings(downloadFolderPath, applicationFolderPath);
Directory.CreateDirectory(settings.workingDirectory); Directory.CreateDirectory(settings.workingDirectory);
Directory.CreateDirectory(settings.downloadLocation); Directory.CreateDirectory(settings.downloadLocation);
Directory.CreateDirectory(settings.coverImageCache); Directory.CreateDirectory(settings.coverImageCache);
settings.logger?.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}"); logger.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}");
settings.logger?.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}"); logger.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}");
settings.logger?.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}"); logger.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}");
settings.logger?.WriteLine("Tranga",$"Logfile-Path: {logFilePath}"); logger.WriteLine("Tranga",$"Logfile-Path: {logFilePath}");
settings.logger?.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}"); logger.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}");
settings.logger?.WriteLine("Tranga", "Loading Taskmanager."); logger.WriteLine("Tranga", "Loading Taskmanager.");
TaskManager taskManager = new (settings); TaskManager taskManager = new (settings, logger);
Server server = new (6531, taskManager); Server server = new (6531, taskManager);
foreach(NotificationManager nm in taskManager.settings.notificationManagers) foreach(NotificationManager nm in taskManager.commonObjects.notificationManagers)
nm.SendNotification("Tranga-API", "Started Tranga-API"); nm.SendNotification("Tranga-API", "Started Tranga-API");
} }
} }

117
Tranga/CommonObjects.cs Normal file
View File

@ -0,0 +1,117 @@
using Logging;
using Newtonsoft.Json;
using Tranga.LibraryManagers;
using Tranga.NotificationManagers;
namespace Tranga;
public class CommonObjects
{
public HashSet<LibraryManager> libraryManagers { get; init; }
public HashSet<NotificationManager> notificationManagers { get; init; }
public Logger? logger { get; init; }
[JsonIgnore]private string settingsFilePath { get; init; }
public CommonObjects(HashSet<LibraryManager>? libraryManagers, HashSet<NotificationManager>? notificationManagers, Logger? logger, string settingsFilePath)
{
this.libraryManagers = libraryManagers??new();
this.notificationManagers = notificationManagers??new();
this.logger = logger;
this.settingsFilePath = settingsFilePath;
}
public static CommonObjects LoadSettings(string settingsFilePath, Logger? logger)
{
if (!File.Exists(settingsFilePath))
return new CommonObjects(null, null, logger, settingsFilePath);
string toRead = File.ReadAllText(settingsFilePath);
TrangaSettings.SettingsJsonObject settings = JsonConvert.DeserializeObject<TrangaSettings.SettingsJsonObject>(
toRead,
new JsonSerializerSettings
{
Converters =
{
new NotificationManager.NotificationManagerJsonConverter(),
new LibraryManager.LibraryManagerJsonConverter()
}
})!;
if(settings.co is null)
return new CommonObjects(null, null, logger, settingsFilePath);
if (logger is not null)
{
foreach (LibraryManager lm in settings.co.libraryManagers)
lm.AddLogger(logger);
foreach(NotificationManager nm in settings.co.notificationManagers)
nm.AddLogger(logger);
}
return settings.co;
}
public void ExportSettings()
{
if (File.Exists(settingsFilePath))
{
bool inUse = true;
while (inUse)
{
try
{
using FileStream stream = new (settingsFilePath, FileMode.Open, FileAccess.Read, FileShare.None);
stream.Close();
inUse = false;
}
catch (IOException)
{
inUse = true;
Thread.Sleep(50);
}
}
}
string toRead = File.ReadAllText(settingsFilePath);
TrangaSettings.SettingsJsonObject? settings = JsonConvert.DeserializeObject<TrangaSettings.SettingsJsonObject>(toRead,
new JsonSerializerSettings { Converters = { new NotificationManager.NotificationManagerJsonConverter(), new LibraryManager.LibraryManagerJsonConverter() } });
settings = new TrangaSettings.SettingsJsonObject(settings?.ts, this);
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(settings));
}
public void UpdateSettings(TrangaSettings.UpdateField field, params string[] values)
{
switch (field)
{
case TrangaSettings.UpdateField.Komga:
if (values.Length != 2)
return;
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
libraryManagers.Add(new Komga(values[0], values[1], this.logger));
break;
case TrangaSettings.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));
break;
case TrangaSettings.UpdateField.Gotify:
if (values.Length != 2)
return;
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(Gotify));
Gotify newGotify = new(values[0], values[1], this.logger);
notificationManagers.Add(newGotify);
newGotify.SendNotification("Success!", "Gotify was added to Tranga!");
break;
case TrangaSettings.UpdateField.LunaSea:
if(values.Length != 1)
return;
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(LunaSea));
LunaSea newLunaSea = new(values[0], this.logger);
notificationManagers.Add(newLunaSea);
newLunaSea.SendNotification("Success!", "LunaSea was added to Tranga!");
break;
}
ExportSettings();
}
}

View File

@ -14,12 +14,14 @@ namespace Tranga.Connectors;
/// </summary> /// </summary>
public abstract class Connector public abstract class Connector
{ {
protected CommonObjects commonObjects;
protected TrangaSettings settings { get; } protected TrangaSettings settings { get; }
internal DownloadClient downloadClient { get; init; } = null!; internal DownloadClient downloadClient { get; init; } = null!;
protected Connector(TrangaSettings settings) protected Connector(TrangaSettings settings, CommonObjects commonObjects)
{ {
this.settings = settings; this.settings = settings;
this.commonObjects = commonObjects;
if (!Directory.Exists(settings.coverImageCache)) if (!Directory.Exists(settings.coverImageCache))
Directory.CreateDirectory(settings.coverImageCache); Directory.CreateDirectory(settings.coverImageCache);
} }
@ -63,11 +65,11 @@ public abstract class Connector
Chapter[] newChapters = this.GetChapters(publication, language); Chapter[] newChapters = this.GetChapters(publication, language);
collection.Add(publication); collection.Add(publication);
NumberFormatInfo decimalPoint = new (){ NumberDecimalSeparator = "." }; NumberFormatInfo decimalPoint = new (){ NumberDecimalSeparator = "." };
settings.logger?.WriteLine(this.GetType().ToString(), "Checking for duplicates"); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Checking for duplicates");
List<Chapter> newChaptersList = newChapters.Where(nChapter => List<Chapter> newChaptersList = newChapters.Where(nChapter =>
float.Parse(nChapter.chapterNumber, decimalPoint) > publication.ignoreChaptersBelow && float.Parse(nChapter.chapterNumber, decimalPoint) > publication.ignoreChaptersBelow &&
!nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList(); !nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
settings.logger?.WriteLine(this.GetType().ToString(), $"{newChaptersList.Count} new chapters."); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"{newChaptersList.Count} new chapters.");
return newChaptersList; return newChaptersList;
} }
@ -161,19 +163,19 @@ public abstract class Connector
/// <param name="publication">Publication to retrieve Cover for</param> /// <param name="publication">Publication to retrieve Cover for</param>
public void CopyCoverFromCacheToDownloadLocation(Publication publication) public void CopyCoverFromCacheToDownloadLocation(Publication publication)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} -> {publication.internalId}"); commonObjects.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 = publication.CreatePublicationFolder(settings.downloadLocation); string publicationFolder = publication.CreatePublicationFolder(settings.downloadLocation);
DirectoryInfo dirInfo = new (publicationFolder); DirectoryInfo dirInfo = new (publicationFolder);
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase))) if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
return; return;
} }
string fileInCache = Path.Join(settings.coverImageCache, publication.coverFileNameInCache); string fileInCache = Path.Join(settings.coverImageCache, publication.coverFileNameInCache);
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" ); string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
settings.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
File.Copy(fileInCache, newFilePath, true); File.Copy(fileInCache, newFilePath, true);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite); File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
@ -211,7 +213,7 @@ public abstract class Connector
{ {
if (cancellationToken?.IsCancellationRequested ?? false) if (cancellationToken?.IsCancellationRequested ?? false)
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
settings.logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}"); commonObjects.logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
//Check if Publication Directory already exists //Check if Publication Directory already exists
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!; string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
if (!Directory.Exists(directoryPath)) if (!Directory.Exists(directoryPath))
@ -229,7 +231,7 @@ public abstract class Connector
{ {
string[] split = imageUrl.Split('.'); string[] split = imageUrl.Split('.');
string extension = split[^1]; 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}"); commonObjects.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); HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
if ((int)status < 200 || (int)status >= 300) if ((int)status < 200 || (int)status >= 300)
return status; return status;
@ -241,7 +243,7 @@ public abstract class Connector
if(comicInfoPath is not null) if(comicInfoPath is not null)
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml")); File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
settings.logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}"); commonObjects.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)) if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
@ -263,7 +265,7 @@ public abstract class Connector
using MemoryStream ms = new(); using MemoryStream ms = new();
coverResult.result.CopyTo(ms); coverResult.result.CopyTo(ms);
File.WriteAllBytes(saveImagePath, ms.ToArray()); File.WriteAllBytes(saveImagePath, ms.ToArray());
settings.logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
return filename; return filename;
} }
} }

View File

@ -18,7 +18,7 @@ public class MangaDex : Connector
Author, Author,
} }
public MangaDex(TrangaSettings settings) : base(settings) public MangaDex(TrangaSettings settings, CommonObjects commonObjects) : base(settings, commonObjects)
{ {
name = "MangaDex"; name = "MangaDex";
this.downloadClient = new DownloadClient(new Dictionary<byte, int>() this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
@ -28,12 +28,12 @@ public class MangaDex : Connector
{(byte)RequestType.AtHomeServer, 40}, {(byte)RequestType.AtHomeServer, 40},
{(byte)RequestType.CoverUrl, 250}, {(byte)RequestType.CoverUrl, 250},
{(byte)RequestType.Author, 250} {(byte)RequestType.Author, 250}
}, settings.logger); }, commonObjects.logger);
} }
protected override Publication[] GetPublicationsInternal(string publicationTitle = "") protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
const int limit = 100; //How many values we want returned at once const int limit = 100; //How many values we want returned at once
int offset = 0; //"Page" int offset = 0; //"Page"
int total = int.MaxValue; //How many total results are there, is updated on first request int total = int.MaxValue; //How many total results are there, is updated on first request
@ -59,7 +59,7 @@ public class MangaDex : Connector
//Loop each Manga and extract information from JSON //Loop each Manga and extract information from JSON
foreach (JsonNode? mangeNode in mangaInResult) foreach (JsonNode? mangeNode in mangaInResult)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}");
JsonObject manga = (JsonObject)mangeNode!; JsonObject manga = (JsonObject)mangeNode!;
JsonObject attributes = manga["attributes"]!.AsObject(); JsonObject attributes = manga["attributes"]!.AsObject();
@ -146,13 +146,13 @@ public class MangaDex : Connector
} }
} }
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})");
return publications.ToArray(); return publications.ToArray();
} }
public override Chapter[] GetChapters(Publication publication, string language = "") public override Chapter[] GetChapters(Publication publication, string language = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})"); commonObjects.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 const int limit = 100; //How many values we want returned at once
int offset = 0; //"Page" int offset = 0; //"Page"
int total = int.MaxValue; //How many total results are there, is updated on first request int total = int.MaxValue; //How many total results are there, is updated on first request
@ -203,7 +203,7 @@ public class MangaDex : Connector
{ {
NumberDecimalSeparator = "." NumberDecimalSeparator = "."
}; };
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting {chapters.Count} Chapters for {publication.internalId}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Done getting {chapters.Count} Chapters for {publication.internalId}");
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
@ -211,7 +211,7 @@ public class MangaDex : Connector
{ {
if (cancellationToken?.IsCancellationRequested ?? false) if (cancellationToken?.IsCancellationRequested ?? false)
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); commonObjects.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
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer); downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer);
@ -238,10 +238,10 @@ public class MangaDex : Connector
private string? GetCoverUrl(string publicationId, string? posterId) private string? GetCoverUrl(string publicationId, string? posterId)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}");
if (posterId is null) if (posterId is null)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting");
return null; return null;
} }
@ -257,7 +257,7 @@ public class MangaDex : Connector
string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>(); string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>();
string coverUrl = $"https://uploads.mangadex.org/covers/{publicationId}/{fileName}"; string coverUrl = $"https://uploads.mangadex.org/covers/{publicationId}/{fileName}";
settings.logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}");
return coverUrl; return coverUrl;
} }
@ -276,7 +276,7 @@ public class MangaDex : Connector
string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>(); string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>();
ret.Add(authorName); ret.Add(authorName);
settings.logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}");
} }
return ret; return ret;
} }

View File

@ -10,18 +10,18 @@ public class MangaKatana : Connector
{ {
public override string name { get; } public override string name { get; }
public MangaKatana(TrangaSettings settings) : base(settings) public MangaKatana(TrangaSettings settings, CommonObjects commonObjects) : base(settings, commonObjects)
{ {
this.name = "MangaKatana"; this.name = "MangaKatana";
this.downloadClient = new DownloadClient(new Dictionary<byte, int>() this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
{ {
{1, 60} {1, 60}
}, settings.logger); }, commonObjects.logger);
} }
protected override Publication[] GetPublicationsInternal(string publicationTitle = "") protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_'); string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_');
string requestUrl = $"https://mangakatana.com/?search={sanitizedTitle}&search_by=book_name"; string requestUrl = $"https://mangakatana.com/?search={sanitizedTitle}&search_by=book_name";
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
@ -135,7 +135,7 @@ public class MangaKatana : Connector
public override Chapter[] GetChapters(Publication publication, string language = "") public override Chapter[] GetChapters(Publication publication, string language = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
string requestUrl = $"https://mangakatana.com/manga/{publication.publicationId}"; string requestUrl = $"https://mangakatana.com/manga/{publication.publicationId}";
// Leaving this in for verification if the page exists // Leaving this in for verification if the page exists
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
@ -149,7 +149,7 @@ public class MangaKatana : Connector
NumberDecimalSeparator = "." NumberDecimalSeparator = "."
}; };
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestUrl); List<Chapter> chapters = ParseChaptersFromHtml(publication, requestUrl);
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
@ -182,7 +182,7 @@ public class MangaKatana : Connector
{ {
if (cancellationToken?.IsCancellationRequested ?? false) if (cancellationToken?.IsCancellationRequested ?? false)
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
string requestUrl = chapter.url; string requestUrl = chapter.url;
// Leaving this in to check if the page exists // Leaving this in to check if the page exists
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =

View File

@ -10,18 +10,18 @@ public class Manganato : Connector
{ {
public override string name { get; } public override string name { get; }
public Manganato(TrangaSettings settings) : base(settings) public Manganato(TrangaSettings settings, CommonObjects commonObjects) : base(settings, commonObjects)
{ {
this.name = "Manganato"; this.name = "Manganato";
this.downloadClient = new DownloadClient(new Dictionary<byte, int>() this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
{ {
{1, 60} {1, 60}
}, settings.logger); }, commonObjects.logger);
} }
protected override Publication[] GetPublicationsInternal(string publicationTitle = "") protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*")).ToLower(); string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*")).ToLower();
string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}"; string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}";
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
@ -125,7 +125,7 @@ public class Manganato : Connector
public override Chapter[] GetChapters(Publication publication, string language = "") public override Chapter[] GetChapters(Publication publication, string language = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
string requestUrl = $"https://chapmanganato.com/{publication.publicationId}"; string requestUrl = $"https://chapmanganato.com/{publication.publicationId}";
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, 1); downloadClient.MakeRequest(requestUrl, 1);
@ -138,7 +138,7 @@ public class Manganato : Connector
NumberDecimalSeparator = "." NumberDecimalSeparator = "."
}; };
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestResult.result); List<Chapter> chapters = ParseChaptersFromHtml(publication, requestResult.result);
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
@ -171,7 +171,7 @@ public class Manganato : Connector
{ {
if (cancellationToken?.IsCancellationRequested ?? false) if (cancellationToken?.IsCancellationRequested ?? false)
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
string requestUrl = chapter.url; string requestUrl = chapter.url;
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, 1); downloadClient.MakeRequest(requestUrl, 1);

View File

@ -15,13 +15,13 @@ public class Mangasee : Connector
private IBrowser? _browser; private IBrowser? _browser;
private const string ChromiumVersion = "1154303"; private const string ChromiumVersion = "1154303";
public Mangasee(TrangaSettings settings) : base(settings) public Mangasee(TrangaSettings settings, CommonObjects commonObjects) : base(settings, commonObjects)
{ {
this.name = "Mangasee"; this.name = "Mangasee";
this.downloadClient = new DownloadClient(new Dictionary<byte, int>() this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
{ {
{ 1, 60 } { 1, 60 }
}, settings.logger); }, commonObjects.logger);
Task d = new Task(DownloadBrowser); Task d = new Task(DownloadBrowser);
d.Start(); d.Start();
@ -34,31 +34,31 @@ public class Mangasee : Connector
browserFetcher.Remove(rev); browserFetcher.Remove(rev);
if (!browserFetcher.LocalRevisions().Contains(ChromiumVersion)) if (!browserFetcher.LocalRevisions().Contains(ChromiumVersion))
{ {
settings.logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser"); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser");
DateTime last = DateTime.Now.Subtract(TimeSpan.FromSeconds(5)); DateTime last = DateTime.Now.Subtract(TimeSpan.FromSeconds(5));
browserFetcher.DownloadProgressChanged += (_, args) => browserFetcher.DownloadProgressChanged += (_, args) =>
{ {
double currentBytes = Convert.ToDouble(args.BytesReceived) / Convert.ToDouble(args.TotalBytesToReceive); double currentBytes = Convert.ToDouble(args.BytesReceived) / Convert.ToDouble(args.TotalBytesToReceive);
if (args.TotalBytesToReceive == args.BytesReceived) if (args.TotalBytesToReceive == args.BytesReceived)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), "Browser downloaded."); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Browser downloaded.");
} }
else if (DateTime.Now > last.AddSeconds(5)) else if (DateTime.Now > last.AddSeconds(5))
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}");
last = DateTime.Now; last = DateTime.Now;
} }
}; };
if (!browserFetcher.CanDownloadAsync(ChromiumVersion).Result) if (!browserFetcher.CanDownloadAsync(ChromiumVersion).Result)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}");
return; return;
} }
await browserFetcher.DownloadAsync(ChromiumVersion); await browserFetcher.DownloadAsync(ChromiumVersion);
} }
settings.logger?.WriteLine(this.GetType().ToString(), "Starting browser."); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Starting browser.");
this._browser = await Puppeteer.LaunchAsync(new LaunchOptions this._browser = await Puppeteer.LaunchAsync(new LaunchOptions
{ {
Headless = true, Headless = true,
@ -73,7 +73,7 @@ public class Mangasee : Connector
protected override Publication[] GetPublicationsInternal(string publicationTitle = "") protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
string requestUrl = $"https://mangasee123.com/_search.php"; string requestUrl = $"https://mangasee123.com/_search.php";
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest(requestUrl, 1); downloadClient.MakeRequest(requestUrl, 1);
@ -98,7 +98,7 @@ public class Mangasee : Connector
queryFiltered = queryFiltered.Where(item => item.Value >= publicationTitle.Split(' ').Length - 1) queryFiltered = queryFiltered.Where(item => item.Value >= publicationTitle.Split(' ').Length - 1)
.ToDictionary(item => item.Key, item => item.Value); .ToDictionary(item => item.Key, item => item.Value);
settings.logger?.WriteLine(this.GetType().ToString(), $"Got {queryFiltered.Count} Publications (title={publicationTitle})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Got {queryFiltered.Count} Publications (title={publicationTitle})");
HashSet<Publication> ret = new(); HashSet<Publication> ret = new();
List<SearchResultItem> orderedFiltered = List<SearchResultItem> orderedFiltered =
@ -111,7 +111,7 @@ public class Mangasee : Connector
downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", 1); downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", 1);
if ((int)requestResult.statusCode >= 200 || (int)requestResult.statusCode < 300) if ((int)requestResult.statusCode >= 200 || (int)requestResult.statusCode < 300)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Retrieving Publication info: {orderedItem.s} {index++}/{orderedFiltered.Count}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Retrieving Publication info: {orderedItem.s} {index++}/{orderedFiltered.Count}");
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, orderedItem.s, orderedItem.i, orderedItem.a)); ret.Add(ParseSinglePublicationFromHtml(requestResult.result, orderedItem.s, orderedItem.i, orderedItem.a));
} }
} }
@ -235,7 +235,7 @@ public class Mangasee : Connector
{ {
NumberDecimalSeparator = "." NumberDecimalSeparator = "."
}; };
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
@ -245,13 +245,13 @@ public class Mangasee : Connector
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
while (this._browser is null && !(cancellationToken?.IsCancellationRequested??false)) while (this._browser is null && !(cancellationToken?.IsCancellationRequested??false))
{ {
settings.logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download..."); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download...");
Thread.Sleep(1000); Thread.Sleep(1000);
} }
if (cancellationToken?.IsCancellationRequested??false) if (cancellationToken?.IsCancellationRequested??false)
return HttpStatusCode.RequestTimeout; return HttpStatusCode.RequestTimeout;
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
IPage page = _browser!.NewPageAsync().Result; IPage page = _browser!.NewPageAsync().Result;
IResponse response = page.GoToAsync(chapter.url).Result; IResponse response = page.GoToAsync(chapter.url).Result;
if (response.Ok) if (response.Ok)

View File

@ -16,21 +16,23 @@ public class TaskManager
private bool _continueRunning = true; private bool _continueRunning = true;
private readonly Connector[] _connectors; private readonly Connector[] _connectors;
public TrangaSettings settings { get; } public TrangaSettings settings { get; }
public CommonObjects commonObjects { get; init; }
public TaskManager(TrangaSettings settings) public TaskManager(TrangaSettings settings, Logging.Logger? logger)
{ {
settings.logger?.WriteLine("Tranga", value: "\n"+ commonObjects = CommonObjects.LoadSettings(settings.settingsFilePath, logger);
@"-----------------------------------------------------------------"+"\n"+ commonObjects.logger?.WriteLine("Tranga", value: "\n"+
@" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+ @"-----------------------------------------------------------------"+"\n"+
@" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+ @" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+
@" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+ @" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+
@"-----------------------------------------------------------------"); @" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+
@"-----------------------------------------------------------------");
this._connectors = new Connector[] this._connectors = new Connector[]
{ {
new MangaDex(settings), new MangaDex(settings, commonObjects),
new Manganato(settings), new Manganato(settings, commonObjects),
new Mangasee(settings), new Mangasee(settings, commonObjects),
new MangaKatana(settings) new MangaKatana(settings, commonObjects)
}; };
this.settings = settings; this.settings = settings;
@ -47,7 +49,7 @@ public class TaskManager
/// </summary> /// </summary>
private void TaskCheckerThread() private void TaskCheckerThread()
{ {
settings.logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread."); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
int waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting); int waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
while (_continueRunning) while (_continueRunning)
{ {
@ -146,7 +148,7 @@ public class TaskManager
{ {
case TrangaTask.Task.UpdateLibraries: case TrangaTask.Task.UpdateLibraries:
//Only one UpdateKomgaLibrary Task //Only one UpdateKomgaLibrary Task
settings.logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task."); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task.");
if (GetTasksMatching(newTask).FirstOrDefault() is { } exists) if (GetTasksMatching(newTask).FirstOrDefault() is { } exists)
_allTasks.Remove(exists); _allTasks.Remove(exists);
_allTasks.Add(newTask); _allTasks.Add(newTask);
@ -155,19 +157,19 @@ public class TaskManager
default: default:
if (!GetTasksMatching(newTask).Any()) if (!GetTasksMatching(newTask).Any())
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}");
_allTasks.Add(newTask); _allTasks.Add(newTask);
ExportDataAndSettings(); ExportDataAndSettings();
} }
else else
settings.logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
break; break;
} }
} }
public void DeleteTask(TrangaTask removeTask) public void DeleteTask(TrangaTask removeTask)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}");
if(_allTasks.Contains(removeTask)) if(_allTasks.Contains(removeTask))
_allTasks.Remove(removeTask); _allTasks.Remove(removeTask);
removeTask.parentTask?.RemoveChildTask(removeTask); removeTask.parentTask?.RemoveChildTask(removeTask);
@ -319,7 +321,7 @@ public class TaskManager
/// <param name="force">If force is true, tasks are aborted.</param> /// <param name="force">If force is true, tasks are aborted.</param>
public void Shutdown(bool force = false) public void Shutdown(bool force = false)
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
_continueRunning = false; _continueRunning = false;
ExportDataAndSettings(); ExportDataAndSettings();
@ -329,16 +331,16 @@ public class TaskManager
//Wait for tasks to finish //Wait for tasks to finish
while(_allTasks.Any(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Enqueued)) while(_allTasks.Any(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Enqueued))
Thread.Sleep(10); Thread.Sleep(10);
settings.logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!"); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!");
Environment.Exit(0); Environment.Exit(0);
} }
private void ImportData() private void ImportData()
{ {
settings.logger?.WriteLine(this.GetType().ToString(), "Importing Data"); commonObjects.logger?.WriteLine(this.GetType().ToString(), "Importing Data");
if (File.Exists(settings.tasksFilePath)) if (File.Exists(settings.tasksFilePath))
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
string buffer = File.ReadAllText(settings.tasksFilePath); string buffer = File.ReadAllText(settings.tasksFilePath);
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!; this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
} }
@ -359,10 +361,10 @@ public class TaskManager
/// </summary> /// </summary>
private void ExportDataAndSettings() private void ExportDataAndSettings()
{ {
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
settings.ExportSettings(); settings.ExportSettings();
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}"); commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}");
while(IsFileInUse(settings.tasksFilePath)) while(IsFileInUse(settings.tasksFilePath))
Thread.Sleep(50); Thread.Sleep(50);
File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(this._allTasks)); File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(this._allTasks));

View File

@ -1,4 +1,5 @@
using Logging; using System.Text.Json.Nodes;
using Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Tranga.LibraryManagers; using Tranga.LibraryManagers;
using Tranga.NotificationManagers; using Tranga.NotificationManagers;
@ -12,41 +13,26 @@ public class TrangaSettings
[JsonIgnore] public string settingsFilePath => Path.Join(workingDirectory, "settings.json"); [JsonIgnore] public string settingsFilePath => Path.Join(workingDirectory, "settings.json");
[JsonIgnore] public string tasksFilePath => Path.Join(workingDirectory, "tasks.json"); [JsonIgnore] public string tasksFilePath => Path.Join(workingDirectory, "tasks.json");
[JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache"); [JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache");
public HashSet<LibraryManager> libraryManagers { get; }
public HashSet<NotificationManager> notificationManagers { get; }
public ushort? version { get; set; } public ushort? version { get; set; }
[JsonIgnore] public Logger? logger { get; init; }
public TrangaSettings(string downloadLocation, string workingDirectory, HashSet<LibraryManager>? libraryManagers, public TrangaSettings(string downloadLocation, string workingDirectory)
HashSet<NotificationManager>? notificationManagers, Logger? logger)
{ {
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.libraryManagers = libraryManagers??new();
this.notificationManagers = notificationManagers??new();
this.logger = logger;
} }
public static TrangaSettings LoadSettings(string importFilePath, Logger? logger) public static TrangaSettings LoadSettings(string importFilePath)
{ {
if (!File.Exists(importFilePath)) if (!File.Exists(importFilePath))
return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory());
Directory.GetCurrentDirectory(), new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
string toRead = File.ReadAllText(importFilePath); string toRead = File.ReadAllText(importFilePath);
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead, SettingsJsonObject settings = JsonConvert.DeserializeObject<SettingsJsonObject>(toRead,
new JsonSerializerSettings { Converters = { new NotificationManager.NotificationManagerJsonConverter(), new LibraryManager.LibraryManagerJsonConverter() } })!; new JsonSerializerSettings { Converters = { new NotificationManager.NotificationManagerJsonConverter(), new LibraryManager.LibraryManagerJsonConverter() } })!;
if (logger is not null) return settings.ts ?? new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory());
{
foreach (LibraryManager lm in settings.libraryManagers)
lm.AddLogger(logger);
foreach(NotificationManager nm in settings.notificationManagers)
nm.AddLogger(logger);
}
return settings;
} }
public void ExportSettings() public void ExportSettings()
@ -69,7 +55,12 @@ public class TrangaSettings
} }
} }
} }
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this));
string toRead = File.ReadAllText(settingsFilePath);
SettingsJsonObject? settings = JsonConvert.DeserializeObject<SettingsJsonObject>(toRead,
new JsonSerializerSettings { Converters = { new NotificationManager.NotificationManagerJsonConverter(), new LibraryManager.LibraryManagerJsonConverter() } });
settings = new SettingsJsonObject(this, settings?.co);
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(settings));
} }
public void UpdateSettings(UpdateField field, params string[] values) public void UpdateSettings(UpdateField field, params string[] values)
@ -81,37 +72,21 @@ public class TrangaSettings
return; return;
this.downloadLocation = values[0]; this.downloadLocation = values[0];
break; break;
case UpdateField.Komga:
if (values.Length != 2)
return;
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
libraryManagers.Add(new Komga(values[0], values[1], this.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));
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);
notificationManagers.Add(newGotify);
newGotify.SendNotification("Success!", "Gotify was added to Tranga!");
break;
case UpdateField.LunaSea:
if(values.Length != 1)
return;
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(LunaSea));
LunaSea newLunaSea = new(values[0], this.logger);
notificationManagers.Add(newLunaSea);
newLunaSea.SendNotification("Success!", "LunaSea was added to Tranga!");
break;
} }
ExportSettings(); ExportSettings();
} }
public enum UpdateField { DownloadLocation, Komga, Kavita, Gotify, LunaSea} public enum UpdateField { DownloadLocation, Komga, Kavita, Gotify, LunaSea}
internal class SettingsJsonObject
{
internal TrangaSettings? ts;
internal CommonObjects? co;
public SettingsJsonObject(TrangaSettings? ts, CommonObjects? co)
{
this.ts = ts;
this.co = co;
}
}
} }

View File

@ -32,10 +32,10 @@ public class DownloadChapterTask : TrangaTask
HttpStatusCode downloadSuccess = connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken); HttpStatusCode downloadSuccess = connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken);
if ((int)downloadSuccess >= 200 && (int)downloadSuccess < 300) if ((int)downloadSuccess >= 200 && (int)downloadSuccess < 300)
{ {
foreach(NotificationManager nm in taskManager.settings.notificationManagers) foreach(NotificationManager nm in taskManager.commonObjects.notificationManagers)
nm.SendNotification("Chapter downloaded", $"{this.publication.sortName} {this.chapter.chapterNumber} {this.chapter.name}"); nm.SendNotification("Chapter downloaded", $"{this.publication.sortName} {this.chapter.chapterNumber} {this.chapter.name}");
foreach (LibraryManager lm in taskManager.settings.libraryManagers) foreach (LibraryManager lm in taskManager.commonObjects.libraryManagers)
lm.UpdateLibrary(); lm.UpdateLibrary();
} }
return downloadSuccess; return downloadSuccess;

View File

@ -66,7 +66,7 @@ public abstract class TrangaTask
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
public void Execute(TaskManager taskManager, CancellationToken? cancellationToken = null) public void Execute(TaskManager taskManager, CancellationToken? cancellationToken = null)
{ {
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}"); taskManager.commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
this.state = ExecutionState.Running; this.state = ExecutionState.Running;
this.executionStarted = DateTime.Now; this.executionStarted = DateTime.Now;
this.lastChange = DateTime.Now; this.lastChange = DateTime.Now;
@ -89,7 +89,7 @@ public abstract class TrangaTask
if (this is DownloadChapterTask) if (this is DownloadChapterTask)
taskManager.DeleteTask(this); taskManager.DeleteTask(this);
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}"); taskManager.commonObjects.logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
} }
public void AddChildTask(TrangaTask childTask) public void AddChildTask(TrangaTask childTask)