Tranga/API/Schema/MangaConnectors/WeebCentral.cs

230 lines
10 KiB
C#
Raw Normal View History

2024-12-14 22:02:32 +01:00
using System.Text.RegularExpressions;
using API.MangaDownloadClients;
using HtmlAgilityPack;
using Soenneker.Utils.String.NeedlemanWunsch;
namespace API.Schema.MangaConnectors;
public class Weebcentral : MangaConnector
{
private readonly string _baseUrl = "https://weebcentral.com";
private readonly string[] _filterWords =
{ "a", "the", "of", "as", "to", "no", "for", "on", "with", "be", "and", "in", "wa", "at", "be", "ni" };
public Weebcentral() : base("Weebcentral", ["en"], ["https://weebcentral.com"])
{
downloadClient = new ChromiumDownloadClient();
}
public override (Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?)[] GetManga(
string publicationTitle = "")
2024-12-14 22:02:32 +01:00
{
const int limit = 32; //How many values we want returned at once
int offset = 0; //"Page"
string requestUrl =
2024-12-14 22:02:32 +01:00
$"{_baseUrl}/search/data?limit={limit}&offset={offset}&text={publicationTitle}&sort=Best+Match&order=Ascending&official=Any&display_mode=Minimal%20Display";
RequestResult requestResult =
2024-12-14 22:02:32 +01:00
downloadClient.MakeRequest(requestUrl, RequestType.Default);
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300 ||
requestResult.htmlDocument == null)
return [];
(Manga, List<Author>, List<MangaTag>, List<Link>, List<MangaAltTitle>)[] publications =
ParsePublicationsFromHtml(requestResult.htmlDocument);
2024-12-14 22:02:32 +01:00
return publications;
}
private (Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?)[] ParsePublicationsFromHtml(
HtmlDocument document)
2024-12-14 22:02:32 +01:00
{
if (document.DocumentNode.SelectNodes("//article") == null)
return [];
List<string> urls = document.DocumentNode.SelectNodes("/html/body/article/a[@class='link link-hover']")
2024-12-14 22:02:32 +01:00
.Select(elem => elem.GetAttributeValue("href", "")).ToList();
List<(Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?)> ret = new();
foreach (string url in urls)
2024-12-14 22:02:32 +01:00
{
(Manga, List<Author>, List<MangaTag>, List<Link>, List<MangaAltTitle>)? manga = GetMangaFromUrl(url);
2024-12-15 23:00:35 +01:00
if (manga is { } x)
ret.Add(x);
2024-12-14 22:02:32 +01:00
}
return ret.ToArray();
}
public override (Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?)?
GetMangaFromUrl(string url)
2024-12-14 22:02:32 +01:00
{
Regex publicationIdRex = new(@"https:\/\/weebcentral\.com\/series\/(\w*)\/(.*)");
string publicationId = publicationIdRex.Match(url).Groups[1].Value;
2024-12-14 22:02:32 +01:00
RequestResult requestResult = downloadClient.MakeRequest(url, RequestType.MangaInfo);
2024-12-14 22:02:32 +01:00
if ((int)requestResult.statusCode < 300 && (int)requestResult.statusCode >= 200 &&
requestResult.htmlDocument is not null)
return ParseSinglePublicationFromHtml(requestResult.htmlDocument, publicationId, url);
return null;
}
private (Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?) ParseSinglePublicationFromHtml(
HtmlDocument document, string publicationId, string websiteUrl)
2024-12-14 22:02:32 +01:00
{
HtmlNode? posterNode =
2024-12-14 22:02:32 +01:00
document.DocumentNode.SelectSingleNode("//section[@class='flex items-center justify-center']/picture/img");
string coverUrl = posterNode?.GetAttributeValue("src", "") ?? "";
2024-12-14 22:02:32 +01:00
HtmlNode? titleNode = document.DocumentNode.SelectSingleNode("//section/h1");
string sortName = titleNode?.InnerText ?? "Undefined";
2024-12-14 22:02:32 +01:00
HtmlNode[] authorsNodes =
document.DocumentNode.SelectNodes("//ul/li[strong/text() = 'Author(s): ']/span")?.ToArray() ?? [];
List<string> authorNames = authorsNodes.Select(n => n.InnerText).ToList();
List<Author> authors = authorNames.Select(n => new Author(n)).ToList();
2024-12-14 22:02:32 +01:00
HtmlNode[] genreNodes =
document.DocumentNode.SelectNodes("//ul/li[strong/text() = 'Tags(s): ']/span")?.ToArray() ?? [];
HashSet<string> tags = genreNodes.Select(n => n.InnerText).ToHashSet();
List<MangaTag> mangaTags = tags.Select(t => new MangaTag(t)).ToList();
2024-12-14 22:02:32 +01:00
HtmlNode? statusNode = document.DocumentNode.SelectSingleNode("//ul/li[strong/text() = 'Status: ']/a");
string status = statusNode?.InnerText ?? "";
MangaReleaseStatus releaseStatus = MangaReleaseStatus.Unreleased;
2024-12-14 22:02:32 +01:00
switch (status.ToLower())
{
case "cancelled": releaseStatus = MangaReleaseStatus.Cancelled; break;
case "hiatus": releaseStatus = MangaReleaseStatus.OnHiatus; break;
case "complete": releaseStatus = MangaReleaseStatus.Completed; break;
case "ongoing": releaseStatus = MangaReleaseStatus.Continuing; break;
}
HtmlNode? yearNode = document.DocumentNode.SelectSingleNode("//ul/li[strong/text() = 'Released: ']/span");
uint year = uint.Parse(yearNode?.InnerText ?? "0");
2024-12-14 22:02:32 +01:00
HtmlNode? descriptionNode = document.DocumentNode.SelectSingleNode("//ul/li[strong/text() = 'Description']/p");
string description = descriptionNode?.InnerText ?? "Undefined";
2024-12-14 22:02:32 +01:00
HtmlNode[] altTitleNodes = document.DocumentNode
.SelectNodes("//ul/li[strong/text() = 'Associated Name(s)']/ul/li")?.ToArray() ?? [];
2024-12-15 23:00:35 +01:00
Dictionary<string, string> altTitlesDict = new(), links = new();
for (int i = 0; i < altTitleNodes.Length; i++)
2024-12-15 23:00:35 +01:00
altTitlesDict.Add(i.ToString(), altTitleNodes[i].InnerText);
List<MangaAltTitle> altTitles = altTitlesDict.Select(a => new MangaAltTitle(a.Key, a.Value)).ToList();
2024-12-14 22:02:32 +01:00
string originalLanguage = "";
2024-12-14 22:02:32 +01:00
Manga manga = new(publicationId, sortName, description, websiteUrl, coverUrl, null, year,
originalLanguage, releaseStatus, -1,
this,
authors,
mangaTags,
2024-12-15 23:00:35 +01:00
[],
2024-12-16 19:25:22 +01:00
altTitles);
2024-12-15 23:00:35 +01:00
return (manga, authors, mangaTags, [], altTitles);
2024-12-14 22:02:32 +01:00
}
public override (Manga, List<Author>?, List<MangaTag>?, List<Link>?, List<MangaAltTitle>?)? GetMangaFromId(
string publicationId)
2024-12-14 22:02:32 +01:00
{
return GetMangaFromUrl($"https://weebcentral.com/series/{publicationId}");
}
private string ToFilteredString(string input)
{
return string.Join(' ', input.ToLower().Split(' ').Where(word => _filterWords.Contains(word) == false));
}
private SearchResult[] FilteredResults(string publicationTitle, SearchResult[] unfilteredSearchResults)
{
Dictionary<SearchResult, int> similarity = new();
foreach (SearchResult sr in unfilteredSearchResults)
2024-12-14 22:02:32 +01:00
{
List<int> scores = new();
string filteredPublicationString = ToFilteredString(publicationTitle);
string filteredSString = ToFilteredString(sr.s);
2024-12-14 22:02:32 +01:00
scores.Add(NeedlemanWunschStringUtil.CalculateSimilarity(filteredSString, filteredPublicationString));
foreach (string srA in sr.a)
2024-12-14 22:02:32 +01:00
{
string filteredAString = ToFilteredString(srA);
2024-12-14 22:02:32 +01:00
scores.Add(NeedlemanWunschStringUtil.CalculateSimilarity(filteredAString, filteredPublicationString));
}
similarity.Add(sr, scores.Sum() / scores.Count);
}
List<SearchResult> ret = similarity.OrderBy(s => s.Value).Take(10).Select(s => s.Key).ToList();
2024-12-14 22:02:32 +01:00
return ret.ToArray();
}
public override Chapter[] GetChapters(Manga manga, string language = "en")
{
string requestUrl = $"{_baseUrl}/series/{manga.ConnectorId}/full-chapter-list";
RequestResult requestResult =
2024-12-14 22:02:32 +01:00
downloadClient.MakeRequest(requestUrl, RequestType.Default);
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
return [];
2024-12-14 22:02:32 +01:00
//Return Chapters ordered by Chapter-Number
if (requestResult.htmlDocument is null)
return [];
List<Chapter> chapters = ParseChaptersFromHtml(manga, requestResult.htmlDocument);
2024-12-14 22:02:32 +01:00
return chapters.Order().ToArray();
}
private List<Chapter> ParseChaptersFromHtml(Manga manga, HtmlDocument document)
{
HtmlNode? chaptersWrapper = document.DocumentNode.SelectSingleNode("/html/body");
2024-12-14 22:02:32 +01:00
Regex chapterRex = new(@"(\d+(?:\.\d+)*)");
2024-12-14 22:02:32 +01:00
Regex idRex = new(@"https:\/\/weebcentral\.com\/chapters\/(\w*)");
List<Chapter> ret = chaptersWrapper.Descendants("a").Select(elem =>
2024-12-14 22:02:32 +01:00
{
string url = elem.GetAttributeValue("href", "") ?? "Undefined";
2024-12-14 22:02:32 +01:00
if (!url.StartsWith("https://") && !url.StartsWith("http://"))
return new Chapter(manga, "undefined", "-1");
2024-12-14 22:02:32 +01:00
Match idMatch = idRex.Match(url);
string? id = idMatch.Success ? idMatch.Groups[1].Value : null;
2024-12-14 22:02:32 +01:00
string chapterNode = elem.SelectSingleNode("span[@class='grow flex items-center gap-2']/span")?.InnerText ??
"Undefined";
2024-12-14 22:02:32 +01:00
Match chapterNumberMatch = chapterRex.Match(chapterNode);
2024-12-14 22:02:32 +01:00
if (!chapterNumberMatch.Success)
return new Chapter(manga, "undefined", "-1");
string chapterNumber = chapterNumberMatch.Groups[1].Value;
return new Chapter(manga, url, chapterNumber);
}).Where(elem => elem.ChapterNumber.CompareTo("-1") != 0 && elem.Url != "undefined").ToList();
2024-12-14 22:02:32 +01:00
ret.Reverse();
return ret;
}
internal override string[] GetChapterImageUrls(Chapter chapter)
{
RequestResult requestResult = downloadClient.MakeRequest(chapter.Url, RequestType.Default);
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300 ||
requestResult.htmlDocument is null) return [];
2024-12-14 22:02:32 +01:00
HtmlDocument? document = requestResult.htmlDocument;
2024-12-14 22:02:32 +01:00
HtmlNode[] imageNodes =
2024-12-14 22:02:32 +01:00
document.DocumentNode.SelectNodes($"//section[@hx-get='{chapter.Url}/images']/img")?.ToArray() ?? [];
string[] urls = imageNodes.Select(imgNode => imgNode.GetAttributeValue("src", "")).ToArray();
2024-12-14 22:02:32 +01:00
return urls;
}
private struct SearchResult
{
public string i { get; set; }
public string s { get; set; }
public string[] a { get; set; }
}
}