Tranga/API/Schema/Jobs/DownloadNewChaptersJob.cs

33 lines
1.7 KiB
C#
Raw Normal View History

2024-12-14 21:53:29 +01:00
using System.ComponentModel.DataAnnotations;
using API.Schema.MangaConnectors;
namespace API.Schema.Jobs;
2025-01-09 01:34:03 +01:00
public class DownloadNewChaptersJob(ulong recurrenceMs, string mangaId, string? parentJobId = null, ICollection<string>? dependsOnJobsIds = null)
: Job(TokenGen.CreateToken(typeof(DownloadNewChaptersJob)), JobType.DownloadNewChaptersJob, recurrenceMs, parentJobId, dependsOnJobsIds)
2024-12-14 21:53:29 +01:00
{
[MaxLength(64)]
public string MangaId { get; init; } = mangaId;
2025-01-09 01:34:03 +01:00
public Manga? Manga { get; init; }
2024-12-14 21:53:29 +01:00
2024-12-17 17:24:25 +01:00
protected override IEnumerable<Job> RunInternal(PgsqlContext context)
2024-12-14 21:53:29 +01:00
{
/*
* For some reason, directly using Manga from above instead of finding it again causes DBContext to consider
* Manga as a new entity and Postgres throws a Duplicate PK exception.
* m.MangaConnector does not have this issue (IDK why).
*/
Manga m = context.Manga.Find(MangaId)!;
MangaConnector connector = context.MangaConnectors.Find(m.MangaConnectorId)!;
// This gets all chapters that are not downloaded
Chapter[] allNewChapters = connector.GetNewChapters(m);
// This filters out chapters that are not downloaded but already exist in the DB
string[] chapterIds = context.Chapters.Where(chapter => chapter.ParentMangaId == m.MangaId).Select(chapter => chapter.ChapterId).ToArray();
Chapter[] newChapters = allNewChapters.Where(chapter => !chapterIds.Contains(chapter.ChapterId)).ToArray();
2024-12-17 17:24:25 +01:00
context.Chapters.AddRangeAsync(newChapters).Wait();
2025-01-09 01:34:03 +01:00
context.SaveChangesAsync().Wait();
return allNewChapters.Select(chapter => new DownloadSingleChapterJob(chapter.ChapterId, this.JobId));
2024-12-14 21:53:29 +01:00
}
}