Skip to content

Commit

Permalink
Merge pull request #276 from C9Glax/cuttingedge-merge-candiate
Browse files Browse the repository at this point in the history
Cuttingedge merge candidate
  • Loading branch information
C9Glax authored Nov 28, 2024
2 parents 5186ae6 + ee265a7 commit d6e73ff
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 95 deletions.
67 changes: 45 additions & 22 deletions Tranga/Chapter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using static System.IO.UnixFileMode;

namespace Tranga;

Expand All @@ -17,23 +19,21 @@ namespace Tranga;
public string url { get; }
// ReSharper disable once MemberCanBePrivate.Global
public string fileName { get; }
public string? id { get; }

private static readonly Regex LegalCharacters = new (@"([A-z]*[0-9]* *\.*-*,*\]*\[*'*\'*\)*\(*~*!*)*");
private static readonly Regex IllegalStrings = new(@"(Vol(ume)?|Ch(apter)?)\.?", RegexOptions.IgnoreCase);
private static readonly Regex Digits = new(@"[0-9\.]*");
public Chapter(Manga parentManga, string? name, string? volumeNumber, string chapterNumber, string url)
public Chapter(Manga parentManga, string? name, string? volumeNumber, string chapterNumber, string url, string? id = null)
{
this.parentManga = parentManga;
this.name = name;
this.volumeNumber = volumeNumber is not null ? string.Concat(Digits.Matches(volumeNumber).Select(x => x.Value)) : "0";
this.chapterNumber = string.Concat(Digits.Matches(chapterNumber).Select(x => x.Value));
this.url = url;
this.id = id;

string chapterVolNumStr;
if (volumeNumber is not null && volumeNumber.Length > 0)
chapterVolNumStr = $"Vol.{volumeNumber} Ch.{chapterNumber}";
else
chapterVolNumStr = $"Ch.{chapterNumber}";
string chapterVolNumStr = $"Vol.{this.volumeNumber} Ch.{chapterNumber}";

if (name is not null && name.Length > 0)
{
Expand Down Expand Up @@ -87,24 +87,47 @@ internal bool CheckChapterIsDownloaded()
string mangaDirectory = Path.Join(TrangaSettings.downloadLocation, parentManga.folderName);
if (!Directory.Exists(mangaDirectory))
return false;
FileInfo[] archives = new DirectoryInfo(mangaDirectory).GetFiles("*.cbz");
Regex volChRex = new(@"(?:Vol(?:ume)?\.([0-9]+)\D*)?Ch(?:apter)?\.([0-9]+(?:\.[0-9]+)*)");
FileInfo? mangaArchive = null;
string markerPath = Path.Join(mangaDirectory, $".{id}");
if (this.id is not null && File.Exists(markerPath))
{
if(File.Exists(File.ReadAllText(markerPath)))
mangaArchive = new FileInfo(File.ReadAllText(markerPath));
else
File.Delete(markerPath);
}

if(mangaArchive is null)
{
FileInfo[] archives = new DirectoryInfo(mangaDirectory).GetFiles("*.cbz");
Regex volChRex = new(@"(?:Vol(?:ume)?\.([0-9]+)\D*)?Ch(?:apter)?\.([0-9]+(?:\.[0-9]+)*)");

Chapter t = this;
Chapter t = this;
mangaArchive = archives.FirstOrDefault(archive =>
{
Match m = volChRex.Match(archive.Name);
if (m.Groups[1].Success)
return m.Groups[1].Value == t.volumeNumber && m.Groups[2].Value == t.chapterNumber;
else
return m.Groups[2].Value == t.chapterNumber;
});
}

string correctPath = GetArchiveFilePath();
FileInfo? archive = archives.FirstOrDefault(archive =>
{
Match m = volChRex.Match(archive.Name);
/*Uncommenting this section will only allow *Version without Volume number* -> *Version with Volume number* but not the other way
if (m.Groups[1].Success)
return m.Groups[1].Value == t.volumeNumber && m.Groups[2].Value == t.chapterNumber;
else*/
return m.Groups[2].Value == t.chapterNumber;
});
if(archive is not null && archive.FullName != correctPath)
archive.MoveTo(correctPath, true);
return (archive is not null);
if(mangaArchive is not null && mangaArchive.FullName != correctPath)
mangaArchive.MoveTo(correctPath, true);
return (mangaArchive is not null);
}

public void CreateChapterMarker()
{
string path = Path.Join(TrangaSettings.downloadLocation, parentManga.folderName, $".{id}");
File.WriteAllText(path, GetArchiveFilePath());
File.SetAttributes(path, FileAttributes.Hidden);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(path, UserRead | UserWrite | UserExecute | GroupRead | GroupWrite | GroupExecute | OtherRead | OtherExecute);
}

/// <summary>
/// Creates full file path of chapter-archive
/// </summary>
Expand Down
37 changes: 24 additions & 13 deletions Tranga/Jobs/JobBoss.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Tranga.MangaConnectors;
using static System.IO.UnixFileMode;

namespace Tranga.Jobs;

Expand All @@ -17,18 +19,21 @@ public JobBoss(GlobalBase clone, HashSet<MangaConnector> connectors) : base(clon
Log($"Next job in {jobs.MinBy(job => job.nextExecution)?.nextExecution.Subtract(DateTime.Now)} {jobs.MinBy(job => job.nextExecution)?.id}");
}

public void AddJob(Job job)
public bool AddJob(Job job, string? jobFile = null)
{
if (ContainsJobLike(job))
{
Log($"Already Contains Job {job}");
return false;
}
else
{
if (!this.jobs.Add(job))
return false;
Log($"Added {job}");
this.jobs.Add(job);
UpdateJobFile(job);
UpdateJobFile(job, jobFile);
}
return true;
}

public void AddJobs(IEnumerable<Job> jobsToAdd)
Expand Down Expand Up @@ -140,15 +145,14 @@ private void AddJobsToQueue(IEnumerable<Job> newJobs)

private void LoadJobsList(HashSet<MangaConnector> connectors)
{
Directory.CreateDirectory(TrangaSettings.jobsFolderPath);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(TrangaSettings.jobsFolderPath, UserRead | UserWrite | UserExecute | GroupRead | OtherRead);
if (!Directory.Exists(TrangaSettings.jobsFolderPath)) //No jobs to load
{
Directory.CreateDirectory(TrangaSettings.jobsFolderPath);
return;
}
Regex idRex = new (@"(.*)\.json");

//Load json-job-files
foreach (FileInfo file in new DirectoryInfo(TrangaSettings.jobsFolderPath).EnumerateFiles().Where(fileInfo => idRex.IsMatch(fileInfo.Name)))
foreach (FileInfo file in Directory.GetFiles(TrangaSettings.jobsFolderPath, "*.json").Select(f => new FileInfo(f)))
{
Log($"Adding {file.Name}");
Job? job = JsonConvert.DeserializeObject<Job>(File.ReadAllText(file.FullName),
Expand All @@ -162,8 +166,12 @@ private void LoadJobsList(HashSet<MangaConnector> connectors)
else
{
Log($"Adding Job {job}");
this.jobs.Add(job);
UpdateJobFile(job, file.Name);
if (!AddJob(job, file.FullName)) //If we detect a duplicate, delete the file.
{
string path = string.Concat(file.FullName, ".duplicate");
file.MoveTo(path);
Log($"Duplicate detected or otherwise not able to add job to list.\nMoved job {job} to {path}");
}
}
}

Expand All @@ -183,7 +191,7 @@ private void LoadJobsList(HashSet<MangaConnector> connectors)

string[] coverFiles = Directory.GetFiles(TrangaSettings.coverImageCache);
foreach(string fileName in coverFiles.Where(fileName => !GetAllCachedManga().Any(manga => manga.coverFileNameInCache == fileName)))
File.Delete(fileName);
File.Delete(fileName);
}

internal void UpdateJobFile(Job job, string? oldFile = null)
Expand All @@ -203,7 +211,8 @@ internal void UpdateJobFile(Job job, string? oldFile = null)
}
catch (Exception e)
{
Log(e.ToString());
Log($"Error deleting {oldFilePath} job {job.id}\n{e}");
return; //Don't export a new file when we haven't actually deleted the old one
}
}

Expand All @@ -215,6 +224,8 @@ internal void UpdateJobFile(Job job, string? oldFile = null)
while(IsFileInUse(newJobFilePath))
Thread.Sleep(10);
File.WriteAllText(newJobFilePath, jobStr);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(newJobFilePath, UserRead | UserWrite | GroupRead | OtherRead);
}
}

Expand Down
10 changes: 4 additions & 6 deletions Tranga/MangaConnectors/Bato.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,15 @@ private List<Chapter> ParseChaptersFromHtml(Manga manga, string mangaUrl)
HtmlNode chapterList =
result.htmlDocument.DocumentNode.SelectSingleNode("/html/body/div/main/div[3]/astro-island/div/div[2]/div/div/astro-slot");

Regex numberRex = new(@"\/title\/.+\/[0-9]+(-vol_([0-9]+))?-ch_([0-9\.]+)");
Regex numberRex = new(@"\/title\/.+\/([0-9])+(?:-vol_([0-9]+))?-ch_([0-9\.]+)");

foreach (HtmlNode chapterInfo in chapterList.SelectNodes("div"))
{
HtmlNode infoNode = chapterInfo.FirstChild.FirstChild;
string chapterUrl = infoNode.GetAttributeValue("href", "");

Match match = numberRex.Match(chapterUrl);
string id = match.Groups[1].Value;
string? volumeNumber = match.Groups[2].Success ? match.Groups[2].Value : null;
string chapterNumber = match.Groups[3].Value;
string chapterName = chapterNumber;
Expand Down Expand Up @@ -189,11 +190,8 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
}

string[] imageUrls = ParseImageUrlsFromHtml(requestUrl);

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, "https://mangakatana.com/", progressToken:progressToken);

return DownloadChapterImages(imageUrls, chapter, RequestType.MangaImage, progressToken:progressToken);
}

private string[] ParseImageUrlsFromHtml(string mangaUrl)
Expand Down
22 changes: 11 additions & 11 deletions Tranga/MangaConnectors/MangaConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,10 @@ private HttpStatusCode DownloadImage(string imageUrl, string fullPath, RequestTy
return requestResult.statusCode;
}

protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, RequestType requestType, string? comicInfoPath = null, string? referrer = null, ProgressToken? progressToken = null)
protected HttpStatusCode DownloadChapterImages(string[] imageUrls, Chapter chapter, RequestType requestType, string? referrer = null, ProgressToken? progressToken = null)
{
string saveArchiveFilePath = chapter.GetArchiveFilePath();

if (progressToken?.cancellationRequested ?? false)
return HttpStatusCode.RequestTimeout;
Log($"Downloading Images for {saveArchiveFilePath}");
Expand All @@ -239,7 +241,7 @@ protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveAr
//Create a temporary folder to store images
string tempFolder = Directory.CreateTempSubdirectory("trangatemp").FullName;

int chapter = 0;
int chapterNum = 0;
//Download all Images to temporary Folder
if (imageUrls.Length == 0)
{
Expand All @@ -253,9 +255,9 @@ protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveAr
foreach (string imageUrl in imageUrls)
{
string extension = imageUrl.Split('.')[^1].Split('?')[0];
Log($"Downloading image {chapter + 1:000}/{imageUrls.Length:000}"); //TODO
HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
Log($"{saveArchiveFilePath} {chapter + 1:000}/{imageUrls.Length:000} {status}");
Log($"Downloading image {chapterNum + 1:000}/{imageUrls.Length:000}"); //TODO
HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapterNum++}.{extension}"), requestType, referrer);
Log($"{saveArchiveFilePath} {chapterNum + 1:000}/{imageUrls.Length:000} {status}");
if ((int)status < 200 || (int)status >= 300)
{
progressToken?.Complete();
Expand All @@ -269,16 +271,14 @@ protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveAr
progressToken?.Increment();
}

if(comicInfoPath is not null){
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
File.Delete(comicInfoPath); //Delete tmp-file
}
File.WriteAllText(Path.Join(tempFolder, "ComicInfo.xml"), chapter.GetComicInfoXmlString());

Log($"Creating archive {saveArchiveFilePath}");
//ZIP-it and ship-it
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(saveArchiveFilePath, UserRead | UserWrite | UserExecute | GroupRead | GroupWrite | GroupExecute);
chapter.CreateChapterMarker();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
File.SetUnixFileMode(saveArchiveFilePath, UserRead | UserWrite | UserExecute | GroupRead | GroupWrite | GroupExecute | OtherRead | OtherExecute);
Directory.Delete(tempFolder, true); //Cleanup

progressToken?.Complete();
Expand Down
7 changes: 2 additions & 5 deletions Tranga/MangaConnectors/MangaDex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public override Chapter[] GetChapters(Manga manga, string language="en")
}

if(chapterNum is not "null" && !chapters.Any(chp => chp.volumeNumber.Equals(volume) && chp.chapterNumber.Equals(chapterNum)))
chapters.Add(new Chapter(manga, title, volume, chapterNum, chapterId));
chapters.Add(new Chapter(manga, title, volume, chapterNum, chapterId, chapterId));
}
}

Expand Down Expand Up @@ -288,11 +288,8 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
HashSet<string> imageUrls = new();
foreach (JsonNode? image in imageFileNames)
imageUrls.Add($"{baseUrl}/data/{hash}/{image!.GetValue<string>()}");

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

//Download Chapter-Images
return DownloadChapterImages(imageUrls.ToArray(), chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, progressToken:progressToken);
return DownloadChapterImages(imageUrls.ToArray(), chapter, RequestType.MangaImage, progressToken:progressToken);
}
}
7 changes: 2 additions & 5 deletions Tranga/MangaConnectors/MangaHere.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public override Chapter[] GetChapters(Manga manga, string language="en")
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300 || requestResult.htmlDocument is null)
return Array.Empty<Chapter>();

List<string> urls = requestResult.htmlDocument.DocumentNode.SelectNodes("//div[@id='list-2']/ul//li//a[contains(@href, '/manga/')]")
List<string> urls = requestResult.htmlDocument.DocumentNode.SelectNodes("//div[@id='list-1']/ul//li//a[contains(@href, '/manga/')]")
.Select(node => node.GetAttributeValue("href", "")).ToList();
Regex chapterRex = new(@".*\/manga\/[a-zA-Z0-9\-\._\~\!\$\&\'\(\)\*\+\,\;\=\:\@]+\/v([0-9(TBD)]+)\/c([0-9\.]+)\/.*");

Expand Down Expand Up @@ -181,12 +181,9 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
}
} while (downloaded++ <= images);

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

if (progressToken is not null)
progressToken.increments = images;//we blip to normal length, in downloadchapterimages it is increasaed by the amount of urls again
return DownloadChapterImages(imageUrls.ToArray(), chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, progressToken:progressToken);
return DownloadChapterImages(imageUrls.ToArray(), chapter, RequestType.MangaImage, progressToken:progressToken);
}

private string[] ParseImageUrlsFromHtml(HtmlDocument document)
Expand Down
7 changes: 2 additions & 5 deletions Tranga/MangaConnectors/MangaKatana.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,8 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
}

string[] imageUrls = ParseImageUrlsFromHtml(requestUrl);

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, "https://mangakatana.com/", progressToken:progressToken);

return DownloadChapterImages(imageUrls, chapter, RequestType.MangaImage, progressToken:progressToken);
}

private string[] ParseImageUrlsFromHtml(string mangaUrl)
Expand Down
2 changes: 1 addition & 1 deletion Tranga/MangaConnectors/MangaLife.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,6 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, progressToken:progressToken);
return DownloadChapterImages(urls.ToArray(), chapter, RequestType.MangaImage, progressToken:progressToken);
}
}
5 changes: 1 addition & 4 deletions Tranga/MangaConnectors/Manganato.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,7 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p

string[] imageUrls = ParseImageUrlsFromHtml(requestResult.htmlDocument);

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, "https://chapmanganato.com/", progressToken:progressToken);
return DownloadChapterImages(imageUrls, chapter, RequestType.MangaImage, "https://chapmanganato.com/", progressToken:progressToken);
}

private string[] ParseImageUrlsFromHtml(HtmlDocument document)
Expand Down
5 changes: 1 addition & 4 deletions Tranga/MangaConnectors/Mangasee.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,7 @@ public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? p
List<string> urls = new();
foreach(HtmlNode galleryImage in images)
urls.Add(galleryImage.GetAttributeValue("src", ""));

string comicInfoPath = Path.GetTempFileName();
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());

return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(), RequestType.MangaImage, comicInfoPath, progressToken:progressToken);
return DownloadChapterImages(urls.ToArray(), chapter, RequestType.MangaImage, progressToken:progressToken);
}
}
Loading

0 comments on commit d6e73ff

Please sign in to comment.