Compare commits

..

No commits in common. "4fcaca1a6e48980fd32305ef8027549175bf236b" and "234735a562b89e20670df687c89374d50387896e" have entirely different histories.

11 changed files with 65 additions and 115 deletions

View File

@ -127,8 +127,7 @@ public abstract class Connector
/// <param name="publication">Publication that contains Chapter</param> /// <param name="publication">Publication that contains Chapter</param>
/// <param name="chapter">Chapter with Images to retrieve</param> /// <param name="chapter">Chapter with Images to retrieve</param>
/// <param name="parentTask">Will be used for progress-tracking</param> /// <param name="parentTask">Will be used for progress-tracking</param>
/// <param name="cancellationToken"></param> public abstract void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask);
public abstract void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null);
/// <summary> /// <summary>
/// Copies the already downloaded cover from cache to downloadLocation /// Copies the already downloaded cover from cache to downloadLocation
@ -167,7 +166,7 @@ public abstract class Connector
new XElement("Tags", string.Join(',',publication.tags)), new XElement("Tags", string.Join(',',publication.tags)),
new XElement("LanguageISO", publication.originalLanguage), new XElement("LanguageISO", publication.originalLanguage),
new XElement("Title", chapter.name), new XElement("Title", chapter.name),
new XElement("Writer", string.Join(',', publication.authors)), new XElement("Writer", publication.author),
new XElement("Volume", chapter.volumeNumber), new XElement("Volume", chapter.volumeNumber),
new XElement("Number", chapter.chapterNumber) new XElement("Number", chapter.chapterNumber)
); );
@ -228,10 +227,8 @@ public abstract class Connector
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param> /// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
/// <param name="requestType">RequestType for RateLimits</param> /// <param name="requestType">RequestType for RateLimits</param>
/// <param name="referrer">Used in http request header</param> /// <param name="referrer">Used in http request header</param>
protected void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, DownloadChapterTask parentTask, string? comicInfoPath = null, string? referrer = null, CancellationToken? cancellationToken = null) protected void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, DownloadChapterTask parentTask, string? comicInfoPath = null, string? referrer = null)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}"); logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
//Check if Publication Directory already exists //Check if Publication Directory already exists
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!; string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
@ -253,8 +250,6 @@ public abstract class Connector
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}");
DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer); DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
parentTask.IncrementProgress(1f / imageUrls.Length); parentTask.IncrementProgress(1f / imageUrls.Length);
if (cancellationToken?.IsCancellationRequested??false)
return;
} }
if(comicInfoPath is not null) if(comicInfoPath is not null)

View File

@ -93,21 +93,19 @@ public class MangaDex : Connector
} }
string? posterId = null; string? posterId = null;
HashSet<string> authorIds = new(); string? authorId = null;
if (manga.ContainsKey("relationships") && manga["relationships"] is not null) if (manga.ContainsKey("relationships") && manga["relationships"] is not null)
{ {
JsonArray relationships = manga["relationships"]!.AsArray(); JsonArray relationships = manga["relationships"]!.AsArray();
posterId = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>(); posterId = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>();
foreach (JsonNode node in relationships.Where(relationship => authorId = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "author")!["id"]!.GetValue<string>();
relationship!["type"]!.GetValue<string>() == "author"))
authorIds.Add(node!["id"]!.GetValue<string>());
} }
string? coverUrl = GetCoverUrl(publicationId, posterId); string? coverUrl = GetCoverUrl(publicationId, posterId);
string? coverCacheName = null; string? coverCacheName = null;
if (coverUrl is not null) if (coverUrl is not null)
coverCacheName = SaveCoverImageToCache(coverUrl, (byte)RequestType.AtHomeServer); coverCacheName = SaveCoverImageToCache(coverUrl, (byte)RequestType.AtHomeServer);
List<string> authors = GetAuthors(authorIds); string? author = GetAuthor(authorId);
Dictionary<string, string> linksDict = new(); Dictionary<string, string> linksDict = new();
if (attributes.ContainsKey("links") && attributes["links"] is not null) if (attributes.ContainsKey("links") && attributes["links"] is not null)
@ -131,7 +129,7 @@ public class MangaDex : Connector
Publication pub = new ( Publication pub = new (
title, title,
authors, author,
description, description,
altTitlesDict, altTitlesDict,
tags.ToArray(), tags.ToArray(),
@ -207,10 +205,8 @@ public class MangaDex : Connector
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null) public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}"); logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
//Request URLs for Chapter-Images //Request URLs for Chapter-Images
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
@ -233,7 +229,7 @@ public class MangaDex : Connector
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger)); File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
//Download Chapter-Images //Download Chapter-Images
DownloadChapterImages(imageUrls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)RequestType.AtHomeServer, parentTask, comicInfoPath, cancellationToken:cancellationToken); DownloadChapterImages(imageUrls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)RequestType.AtHomeServer, parentTask, comicInfoPath);
} }
private string? GetCoverUrl(string publicationId, string? posterId) private string? GetCoverUrl(string publicationId, string? posterId)
@ -261,23 +257,21 @@ public class MangaDex : Connector
return coverUrl; return coverUrl;
} }
private List<string> GetAuthors(IEnumerable<string> authorIds) private string? GetAuthor(string? authorId)
{ {
List<string> ret = new(); if (authorId is null)
foreach (string authorId in authorIds) return null;
{
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
downloadClient.MakeRequest($"https://api.mangadex.org/author/{authorId}", (byte)RequestType.Author); downloadClient.MakeRequest($"https://api.mangadex.org/author/{authorId}", (byte)RequestType.Author);
if (requestResult.statusCode != HttpStatusCode.OK) if (requestResult.statusCode != HttpStatusCode.OK)
return ret; return null;
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result); JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
if (result is null) if (result is null)
return ret; return null;
string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>(); string author = result["data"]!["attributes"]!["name"]!.GetValue<string>();
ret.Add(authorName); logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {author}");
logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}"); return author;
}
return ret;
} }
} }

View File

@ -71,8 +71,8 @@ public class Manganato : Connector
Dictionary<string, string> altTitles = new(); Dictionary<string, string> altTitles = new();
Dictionary<string, string>? links = null; Dictionary<string, string>? links = null;
HashSet<string> tags = new(); HashSet<string> tags = new();
string[] authors = Array.Empty<string>(); string? author = null, originalLanguage = null;
string originalLanguage = ""; int? year = DateTime.Now.Year;
HtmlNode infoNode = document.DocumentNode.Descendants("div").First(d => d.HasClass("story-info-right")); HtmlNode infoNode = document.DocumentNode.Descendants("div").First(d => d.HasClass("story-info-right"));
@ -94,7 +94,7 @@ public class Manganato : Connector
altTitles.Add(i.ToString(), alts[i]); altTitles.Add(i.ToString(), alts[i]);
break; break;
case "authors": case "authors":
authors = value.Split('-'); author = value;
break; break;
case "status": case "status":
status = value; status = value;
@ -119,9 +119,9 @@ public class Manganato : Connector
string yearString = document.DocumentNode.Descendants("li").Last(li => li.HasClass("a-h")).Descendants("span") string yearString = document.DocumentNode.Descendants("li").Last(li => li.HasClass("a-h")).Descendants("span")
.First(s => s.HasClass("chapter-time")).InnerText; .First(s => s.HasClass("chapter-time")).InnerText;
int year = Convert.ToInt32(yearString.Split(',')[^1]) + 2000; year = Convert.ToInt32(yearString.Split(',')[^1]) + 2000;
return new Publication(sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links, return new Publication(sortName, author, description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
year, originalLanguage, status, publicationId); year, originalLanguage, status, publicationId);
} }
@ -169,10 +169,8 @@ public class Manganato : Connector
return ret; return ret;
} }
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null) public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
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; string requestUrl = chapter.url;
DownloadClient.RequestResult requestResult = DownloadClient.RequestResult requestResult =
@ -185,7 +183,7 @@ public class Manganato : Connector
string comicInfoPath = Path.GetTempFileName(); string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger)); File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
DownloadChapterImages(imageUrls, GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, "https://chapmanganato.com/", cancellationToken); DownloadChapterImages(imageUrls, GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, "https://chapmanganato.com/");
} }
private string[] ParseImageUrlsFromHtml(Stream html) private string[] ParseImageUrlsFromHtml(Stream html)

View File

@ -141,9 +141,10 @@ public class Mangasee : Connector
HtmlNode[] authorsNodes = attributes.Descendants("li") HtmlNode[] authorsNodes = attributes.Descendants("li")
.First(node => node.InnerText.Contains("author(s):", StringComparison.CurrentCultureIgnoreCase)) .First(node => node.InnerText.Contains("author(s):", StringComparison.CurrentCultureIgnoreCase))
.Descendants("a").ToArray(); .Descendants("a").ToArray();
List<string> authors = new(); string[] authors = new string[authorsNodes.Length];
foreach(HtmlNode authorNode in authorsNodes) for (int j = 0; j < authors.Length; j++)
authors.Add(authorNode.InnerText); authors[j] = authorsNodes[j].InnerText;
string author = string.Join(" - ", authors);
HtmlNode[] genreNodes = attributes.Descendants("li") HtmlNode[] genreNodes = attributes.Descendants("li")
.First(node => node.InnerText.Contains("genre(s):", StringComparison.CurrentCultureIgnoreCase)) .First(node => node.InnerText.Contains("genre(s):", StringComparison.CurrentCultureIgnoreCase))
@ -170,7 +171,7 @@ public class Mangasee : Connector
foreach(string at in a) foreach(string at in a)
altTitles.Add((i++).ToString(), at); altTitles.Add((i++).ToString(), at);
return new Publication(sortName, authors, description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links, return new Publication(sortName, author, description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
year, originalLanguage, status, publicationId); year, originalLanguage, status, publicationId);
} }
@ -209,20 +210,16 @@ public class Mangasee : Connector
return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray(); return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
} }
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null) public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask)
{ {
if (cancellationToken?.IsCancellationRequested??false) while (this._browser is null)
return;
while (this._browser is null && !(cancellationToken?.IsCancellationRequested??false))
{ {
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); Thread.Sleep(1000);
} }
if (cancellationToken?.IsCancellationRequested??false)
return;
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; 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)
{ {
@ -238,7 +235,7 @@ public class Mangasee : Connector
string comicInfoPath = Path.GetTempFileName(); string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger)); File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
DownloadChapterImages(urls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, cancellationToken:cancellationToken); DownloadChapterImages(urls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath);
} }
} }
} }

View File

@ -12,7 +12,7 @@ namespace Tranga;
public readonly struct Publication public readonly struct Publication
{ {
public string sortName { get; } public string sortName { get; }
public List<string> authors { get; } public string? author { get; }
public Dictionary<string,string> altTitles { get; } public Dictionary<string,string> altTitles { get; }
// ReSharper disable trice MemberCanBePrivate.Global, trust // ReSharper disable trice MemberCanBePrivate.Global, trust
public string? description { get; } public string? description { get; }
@ -29,22 +29,10 @@ public readonly struct Publication
private static readonly Regex LegalCharacters = new Regex(@"[A-Z]*[a-z]*[0-9]* *\.*-*,*'*\'*\)*\(*~*!*"); private static readonly Regex LegalCharacters = new Regex(@"[A-Z]*[a-z]*[0-9]* *\.*-*,*'*\'*\)*\(*~*!*");
[JsonConstructor] //Legacy public Publication(string sortName, string? author, string? description, Dictionary<string,string> altTitles, string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string,string>? links, int? year, string? originalLanguage, string status, string publicationId)
public Publication(string sortName, string? author, string? description, Dictionary<string, string> altTitles,
string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string, string>? links, int? year,
string? originalLanguage, string status, string publicationId)
{
List<string> pAuthors = new();
if(author is not null)
pAuthors.Add(author);
this = new Publication(sortName, pAuthors, description, altTitles, tags, posterUrl,
coverFileNameInCache, links, year, originalLanguage, status, publicationId);
}
public Publication(string sortName, List<string> authors, string? description, Dictionary<string,string> altTitles, string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string,string>? links, int? year, string? originalLanguage, string status, string publicationId)
{ {
this.sortName = sortName; this.sortName = sortName;
this.authors = authors; this.author = author;
this.description = description; this.description = description;
this.altTitles = altTitles; this.altTitles = altTitles;
this.tags = tags; this.tags = tags;

View File

@ -19,7 +19,7 @@ public class TaskManager
public TrangaSettings settings { get; } public TrangaSettings settings { get; }
private Logger? logger { get; } private Logger? logger { get; }
private readonly Dictionary<DownloadChapterTask, CancellationTokenSource> _runningDownloadChapterTasks = new(); private readonly Dictionary<DownloadChapterTask, Task> _runningDownloadChapterTasks = new();
/// <param name="downloadFolderPath">Local path to save data (Manga) to</param> /// <param name="downloadFolderPath">Local path to save data (Manga) to</param>
/// <param name="workingDirectory">Path to the working directory</param> /// <param name="workingDirectory">Path to the working directory</param>
@ -122,25 +122,23 @@ public class TaskManager
} }
HashSet<DownloadChapterTask> toRemove = new(); HashSet<DownloadChapterTask> toRemove = new();
foreach (KeyValuePair<DownloadChapterTask, CancellationTokenSource> removeTask in _runningDownloadChapterTasks) foreach (KeyValuePair<DownloadChapterTask,Task> removeTask in _runningDownloadChapterTasks)
{ {
if (removeTask.Key.GetType() == typeof(DownloadChapterTask) && if (removeTask.Key.GetType() == typeof(DownloadChapterTask) &&
DateTime.Now.Subtract(removeTask.Key.lastChange) > TimeSpan.FromMinutes(3))//3 Minutes since last update to task -> remove DateTime.Now.Subtract(removeTask.Key.lastChange) > TimeSpan.FromMinutes(3))//3 Minutes since last update to task -> remove
{ {
logger?.WriteLine(this.GetType().ToString(), $"Disposing failed task {removeTask.Key}."); logger?.WriteLine(this.GetType().ToString(), $"Disposing failed task {removeTask.Key}.");
removeTask.Key.parentTask?.DecrementProgress(removeTask.Key.progress); removeTask.Key.parentTask?.DecrementProgress(removeTask.Key.progress);
removeTask.Value.Cancel(); //removeTask.Value.Dispose(); Currently not available, however since task is removed from _allTasks should work. Memory leak however...
toRemove.Add(removeTask.Key); toRemove.Add(removeTask.Key);
} }
} }
foreach (DownloadChapterTask taskToRemove in toRemove) foreach (DownloadChapterTask taskToRemove in toRemove)
{ {
DeleteTask(taskToRemove); DeleteTask(taskToRemove);
DownloadChapterTask newTask = new DownloadChapterTask(taskToRemove.task, taskToRemove.connectorName, AddTask(new DownloadChapterTask(taskToRemove.task, taskToRemove.connectorName,
taskToRemove.publication, taskToRemove.chapter, taskToRemove.language, taskToRemove.publication, taskToRemove.chapter, taskToRemove.language,
taskToRemove.parentTask); taskToRemove.parentTask));
AddTask(newTask);
taskToRemove.parentTask?.ReplaceFailedChildTask(taskToRemove, newTask);
} }
if(allTasksWaitingLength != _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting)) if(allTasksWaitingLength != _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting))
@ -157,13 +155,12 @@ public class TaskManager
public void ExecuteTaskNow(TrangaTask task) public void ExecuteTaskNow(TrangaTask task)
{ {
task.state = TrangaTask.ExecutionState.Running; task.state = TrangaTask.ExecutionState.Running;
CancellationTokenSource cToken = new ();
Task t = new(() => Task t = new(() =>
{ {
task.Execute(this, this.logger, cToken.Token); task.Execute(this, this.logger);
}, cToken.Token); });
if(task.GetType() == typeof(DownloadChapterTask)) if(task.GetType() == typeof(DownloadChapterTask))
_runningDownloadChapterTasks.Add((DownloadChapterTask)task, cToken); _runningDownloadChapterTasks.Add((DownloadChapterTask)task, t);
t.Start(); t.Start();
} }

View File

@ -71,22 +71,20 @@ public abstract class TrangaTask
/// </summary> /// </summary>
/// <param name="taskManager"></param> /// <param name="taskManager"></param>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="cancellationToken"></param> protected abstract void ExecuteTask(TaskManager taskManager, Logger? logger);
protected abstract void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null);
/// <summary> /// <summary>
/// Execute the task /// Execute the task
/// </summary> /// </summary>
/// <param name="taskManager">Should be the parent taskManager</param> /// <param name="taskManager">Should be the parent taskManager</param>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="cancellationToken"></param> public void Execute(TaskManager taskManager, Logger? logger)
public void Execute(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
{ {
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}"); 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;
ExecuteTask(taskManager, logger, cancellationToken); ExecuteTask(taskManager, logger);
this.lastExecuted = DateTime.Now; this.lastExecuted = DateTime.Now;
this.state = ExecutionState.Waiting; this.state = ExecutionState.Waiting;
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}"); logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");

View File

@ -20,12 +20,10 @@ public class DownloadChapterTask : TrangaTask
this.parentTask = parentTask; this.parentTask = parentTask;
} }
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null) protected override void ExecuteTask(TaskManager taskManager, Logger? logger)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
Connector connector = taskManager.GetConnector(this.connectorName); Connector connector = taskManager.GetConnector(this.connectorName);
connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken); connector.DownloadChapter(this.publication, this.chapter, this);
taskManager.DeleteTask(this); taskManager.DeleteTask(this);
} }

View File

@ -8,59 +8,46 @@ public class DownloadNewChaptersTask : TrangaTask
public string connectorName { get; } public string connectorName { get; }
public Publication publication { get; } public Publication publication { get; }
public string language { get; } public string language { get; }
[JsonIgnore]private HashSet<DownloadChapterTask> childTasks { get; } [JsonIgnore]private int childTaskAmount { get; set; }
public DownloadNewChaptersTask(Task task, string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(task, reoccurrence) public DownloadNewChaptersTask(Task task, string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(task, reoccurrence)
{ {
this.connectorName = connectorName; this.connectorName = connectorName;
this.publication = publication; this.publication = publication;
this.language = language; this.language = language;
this.childTasks = new(); childTaskAmount = 0;
} }
public new float IncrementProgress(float amount) public new float IncrementProgress(float amount)
{ {
this.progress += amount / this.childTasks.Count; this.progress += amount / this.childTaskAmount;
this.lastChange = DateTime.Now; this.lastChange = DateTime.Now;
return this.progress; return this.progress;
} }
public new float DecrementProgress(float amount) public new float DecrementProgress(float amount)
{ {
this.progress -= amount / this.childTasks.Count; this.progress -= amount / this.childTaskAmount;
this.lastChange = DateTime.Now; this.lastChange = DateTime.Now;
return this.progress; return this.progress;
} }
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null) protected override void ExecuteTask(TaskManager taskManager, Logger? logger)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
Publication pub = publication!; Publication pub = publication!;
Connector connector = taskManager.GetConnector(this.connectorName); Connector connector = taskManager.GetConnector(this.connectorName);
//Check if Publication already has a Folder //Check if Publication already has a Folder
pub.CreatePublicationFolder(taskManager.settings.downloadLocation); pub.CreatePublicationFolder(taskManager.settings.downloadLocation);
List<Chapter> newChapters = GetNewChaptersList(connector, pub, language!, ref taskManager.chapterCollection); List<Chapter> newChapters = GetNewChaptersList(connector, pub, language!, ref taskManager.chapterCollection);
this.childTaskAmount = newChapters.Count;
connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings); connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings);
pub.SaveSeriesInfoJson(connector.downloadLocation); pub.SaveSeriesInfoJson(connector.downloadLocation);
foreach (Chapter newChapter in newChapters) foreach (Chapter newChapter in newChapters)
{ taskManager.AddTask(new DownloadChapterTask(Task.DownloadChapter, this.connectorName!, pub, newChapter, this.language, this));
DownloadChapterTask newTask = new (Task.DownloadChapter, this.connectorName!, pub, newChapter, this.language, this);
taskManager.AddTask(newTask);
this.childTasks.Add(newTask);
}
}
public void ReplaceFailedChildTask(DownloadChapterTask failed, DownloadChapterTask newTask)
{
if (!this.childTasks.Contains(failed))
throw new ArgumentException($"Task {failed} is not childTask of {this}");
this.childTasks.Remove(failed);
this.childTasks.Add(newTask);
} }
/// <summary> /// <summary>

View File

@ -8,10 +8,8 @@ public class UpdateLibrariesTask : TrangaTask
{ {
} }
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null) protected override void ExecuteTask(TaskManager taskManager, Logger? logger)
{ {
if (cancellationToken?.IsCancellationRequested??false)
return;
foreach(LibraryManager lm in taskManager.settings.libraryManagers) foreach(LibraryManager lm in taskManager.settings.libraryManagers)
lm.UpdateLibrary(); lm.UpdateLibrary();
this.progress = 1f; this.progress = 1f;

View File

@ -233,7 +233,7 @@ function ShowPublicationViewerWindow(publicationId, event, add){
publicationViewerName.innerText = publication.sortName; publicationViewerName.innerText = publication.sortName;
publicationViewerTags.innerText = publication.tags.join(", "); publicationViewerTags.innerText = publication.tags.join(", ");
publicationViewerDescription.innerText = publication.description; publicationViewerDescription.innerText = publication.description;
publicationViewerAuthor.innerText = publication.authors.join(','); publicationViewerAuthor.innerText = publication.author;
pubviewcover.src = `imageCache/${publication.coverFileNameInCache}`; pubviewcover.src = `imageCache/${publication.coverFileNameInCache}`;
toEditId = publicationId; toEditId = publicationId;