6 Commits
17 changed files with 1167 additions and 200 deletions
+63
View File
@@ -0,0 +1,63 @@
using System.Xml.Linq;
namespace AnimeAnnouncer.Torrents
{
public record NyaaRssItem(
String Title,
String Published,
String Category,
String CategoryID,
String Size,
String Link,
String Description,
String PostID);
/// <summary>
/// Reads Nyaa RSS feeds and downloads the .torrent files they link to.
/// </summary>
public class NyaaRssReader
{
private readonly HttpClient httpClient;
public NyaaRssReader(HttpClient? httpClient = null)
{
this.httpClient = httpClient ?? new HttpClient();
}
/// <summary>
/// Converts a Nyaa search URL into its RSS equivalent, if it isn't one already.
/// </summary>
public static String ToRssUrl(String url)
{
return url.Contains("rss") ? url : url + "&page=rss";
}
public async Task<List<NyaaRssItem>> ReadAsync(String url)
{
var response = await httpClient.GetStringAsync(ToRssUrl(url));
return Parse(response);
}
public static List<NyaaRssItem> Parse(String rssXml)
{
XDocument doc = XDocument.Parse(rssXml);
XNamespace nyaaNS = doc.Root!.GetNamespaceOfPrefix("nyaa") ?? XNamespace.None;
return (from item in doc.Descendants("channel").Elements("item")
select new NyaaRssItem(
Title: item.Element("title")?.Value ?? String.Empty,
Published: item.Element("pubDate")?.Value ?? String.Empty,
Category: item.Element(nyaaNS + "category")?.Value ?? String.Empty,
CategoryID: item.Element(nyaaNS + "categoryId")?.Value ?? String.Empty,
Size: item.Element(nyaaNS + "size")?.Value ?? String.Empty,
Link: item.Element("link")?.Value ?? String.Empty,
Description: item.Element("description")?.Value ?? String.Empty,
PostID: item.Element("guid")?.Value ?? String.Empty
)).ToList();
}
public Task<byte[]> DownloadTorrentAsync(NyaaRssItem item)
{
return httpClient.GetByteArrayAsync(item.Link);
}
}
}
@@ -0,0 +1,35 @@
using System.Text.RegularExpressions;
namespace AnimeAnnouncer.Torrents
{
public static class TorrentDirectoryNamer
{
/// <summary>
/// Turns a release title into a dotted directory name, stripping the episode number
/// (keeping the resolution) and any trailing parenthesised suffix.
/// e.g. "Show Name S01E05 1080p WEB (Group)" -> "Show.Name.S01.1080p.WEB"
/// </summary>
public static String FromTitle(String title)
{
String name = title.Trim();
name = Regex.Replace(name, @"E\d{2,3}.*?(\d{3,4}p)", " $1");
name = Regex.Replace(name, @"\s\(.*?\)$", "");
return name.Replace(" ", ".");
}
public static String PrepareForURI(String title)
{
var titlePart = Regex.Replace(title, @"[^\w\s]+", String.Empty);
titlePart = Regex.Replace(titlePart, @"\s+", "+");
return titlePart;
}
/// <summary>
/// Builds the full save path for a release title under <paramref name="destinationFolder"/>.
/// </summary>
public static String FromTitle(String title, String destinationFolder)
{
return destinationFolder + (destinationFolder.EndsWith("/") ? String.Empty : "/") + FromTitle(title);
}
}
}
@@ -0,0 +1,57 @@
using Transmission.API.RPC;
using Transmission.API.RPC.Arguments;
using Transmission.API.RPC.Entity;
namespace AnimeAnnouncer.Torrents
{
/// <summary>
/// Thin wrapper around the Transmission RPC client for adding torrents to the server.
/// </summary>
public class TransmissionService
{
public Client Client { get; }
private TransmissionService(Client client)
{
Client = client;
}
/// <summary>
/// Creates a client and verifies the server is reachable by requesting session information.
/// Throws <see cref="InvalidOperationException"/> if the server doesn't respond with a valid session.
/// </summary>
public static async Task<TransmissionService> ConnectAsync(String host, String? username, String? password)
{
var client = new Client(host, null, username, password);
var sessionInformation = await client.GetSessionInformationAsync();
if (sessionInformation == null || String.IsNullOrEmpty(sessionInformation.Version))
throw new InvalidOperationException($"An error occurred while receiving session information from the rpc server at {host}");
return new TransmissionService(client);
}
/// <summary>
/// Adds a .torrent file to the server, saving to <paramref name="saveLocation"/>, and applies a seed ratio limit.
/// </summary>
public async Task<NewTorrentInfo> AddNewTorrentFileToServerAsync(byte[] torrentFileData, String saveLocation, bool paused = true, double seedRatioLimit = 1.0)
{
NewTorrent newTorrent = new()
{
DownloadDirectory = saveLocation,
Paused = paused,
Metainfo = Convert.ToBase64String(torrentFileData)
};
var torrentInfo = await Client.TorrentAddAsync(newTorrent);
var seedSettings = new TorrentSettings()
{
SeedRatioLimit = seedRatioLimit,
SeedRatioMode = 1,
IDs = [torrentInfo.ID]
};
// TorrentSetAsync returns void in Transmission.API.RPC 2.1.2, so it can't be awaited
Client.TorrentSet(seedSettings);
return torrentInfo;
}
}
}
@@ -10,4 +10,21 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<!-- SDK container publishing (dotnet publish -t:PublishContainer). The Web SDK
includes Microsoft.NET.Build.Containers, so no Dockerfile is needed; the
base image is inferred from TargetFramework (aspnet:8.0). -->
<PropertyGroup Label="Container">
<ContainerRepository>animeannouncer-web</ContainerRepository>
<!-- Add a version alongside it at publish time:
dotnet publish ... -p:ContainerImageTags='"1.1.0;latest"' -->
<ContainerImageTags>latest</ContainerImageTags>
<!-- The aspnet base image ships a non-root 'app' user; 8080 is unprivileged. -->
<ContainerUser>app</ContainerUser>
</PropertyGroup>
<ItemGroup>
<!-- Matches ASPNETCORE_HTTP_PORTS, which the aspnet:8.0 image defaults to 8080. -->
<ContainerPort Include="8080" Type="tcp" />
</ItemGroup>
</Project> </Project>
+163 -64
View File
@@ -1,17 +1,17 @@
@page @page
@model IndexModel @model IndexModel
@{ @{
ViewData["Title"] = "Airing Soon Anime"; ViewData["Title"] = "Airing Soon Anime";
} }
<div class="container-fluid airing-container"> <div class="airing-container">
<div class="d-flex flex-wrap align-items-center justify-content-between mb-2"> <div class="d-flex flex-wrap align-items-center justify-content-between mb-2">
<h1 class="display-5 mb-0 d-flex align-items-center flex-wrap"> <h1 class="display-5 mb-0 d-flex align-items-center flex-wrap">
<span>🗓️ Airing Soon Anime</span> <span>🗓️ Airing Soon Anime</span>
<span class="badge rounded-pill bg-dark text-white ms-2 fs-6">@(Model.AiringShows == null ? "No data" : (Model.AiringShows.Count + (Model.AiringShows.Count == 1 ? " show" : " shows")))</span> <span class="badge rounded-pill bg-dark text-white ms-2 fs-6">@(Model.AiringShows == null ? "No data" : (Model.AiringShows.Count + (Model.AiringShows.Count == 1 ? " show" : " shows")))</span>
</h1> </h1>
</div> </div>
<p class="lead text-secondary mb-4">Anime with an upcoming or recent latest episode, fetched from the TMDB cache. Sorted by air date (<strong>newest first</strong>).</p> <p class="lead text-secondary mb-4">Anime with an upcoming or recent latest episode, drawn from the TMDB and AniList caches. Sorted by air date (<strong>soonest first</strong>).</p>
@if (!string.IsNullOrEmpty(Model.ErrorMessage)) @if (!string.IsNullOrEmpty(Model.ErrorMessage))
{ {
@@ -32,93 +32,192 @@
} }
else else
{ {
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4 row-cols-xl-5 row-cols-xxl-6 g-4"> <div class="airing-list">
@foreach (var show in Model.AiringShows) @foreach (var show in Model.AiringShows)
{ {
<div class="col"> <article id="show-@show.ShowID" class="airing-row @(show.IsFuture ? "is-upcoming" : "is-aired")">
<div class="card h-100 anime-card @(show.IsFuture ? "border-danger" : "")"> @if (!string.IsNullOrWhiteSpace(show.HeroImageUrl))
<div class="anime-poster-container"> {
<div class="airing-backdrop" style="background-image: url('@show.HeroImageUrl');" aria-hidden="true"></div>
}
<div class="airing-scrim" aria-hidden="true"></div>
<div class="airing-content">
<div class="airing-poster">
@if (!string.IsNullOrWhiteSpace(show.PosterUrl)) @if (!string.IsNullOrWhiteSpace(show.PosterUrl))
{ {
<img src="@show.PosterUrl" class="anime-poster" alt="@show.Title" title="@show.Title" loading="lazy" /> <img src="@show.PosterUrl" alt="@show.Title poster" title="@show.Title" loading="lazy" />
} }
else else
{ {
<div class="anime-poster d-flex align-items-center justify-content-center text-secondary"> <div class="airing-poster-placeholder"><span>🗂️</span></div>
<span class="display-4">🗂️</span> }
@if (show.LatestSeasonNumber.HasValue && show.LatestSeasonNumber > 0)
{
<span class="airing-poster-tag">Season @show.LatestSeasonNumber</span>
}
</div>
<div class="airing-body">
<header class="airing-header">
<div class="airing-titles">
<h2 class="airing-title">@show.Title</h2>
@if (show.AlternateTitles.Count > 0)
{
<p class="airing-alt-titles">@string.Join(" · ", show.AlternateTitles)</p>
}
</div>
<div class="airing-scores">
@if (show.VoteAverage.HasValue && show.VoteAverage > 0)
{
<span class="score-chip score-tmdb" title="TMDB user score">
<span class="score-value">@string.Format("{0:0.0}", show.VoteAverage)</span>
<span class="score-source">TMDB</span>
</span>
}
@if (show.AnilistScore.HasValue && show.AnilistScore > 0)
{
<span class="score-chip score-anilist" title="AniList average score">
<span class="score-value">@string.Format("{0:0.0}", show.AnilistScore)</span>
<span class="score-source">AniList</span>
</span>
}
</div>
</header>
<div class="airing-meta">
@if (show.LatestEpisodeNumber > 0)
{
<span class="meta-chip">
@if (show.TotalEpisodes.HasValue && show.TotalEpisodes > 0)
{
<text>Episode @show.LatestEpisodeNumber of @show.TotalEpisodes</text>
}
else
{
<text>Episode @show.LatestEpisodeNumber</text>
}
</span>
}
@if (show.LatestOrdinalEpisodeNumber.HasValue && show.LatestOrdinalEpisodeNumber > 0)
{
<span class="meta-chip">@show.LatestOrdinalEpisodeNumber episodes overall</span>
}
@if (!string.IsNullOrWhiteSpace(show.AnilistStatus))
{
<span class="meta-chip">@show.AnilistStatus</span>
}
@if (show.SeasonYear.HasValue)
{
<span class="meta-chip">@show.SeasonYear</span>
}
@if (show.IsFinaleNext && show.IsFuture)
{
<span class="meta-chip meta-chip-finale">🏁 Season finale</span>
}
</div>
@if (show.Genres.Count > 0 || show.Tags.Count > 0)
{
<div class="airing-taxonomy">
@foreach (var genre in show.Genres)
{
<span class="genre-chip">@genre</span>
}
@foreach (var tag in show.VisibleTags)
{
<span class="tag-chip">#@tag</span>
}
@if (show.OverflowTags.Count > 0)
{
<details class="tag-overflow">
<summary class="tag-chip tag-more">+@show.OverflowTags.Count more</summary>
@foreach (var tag in show.OverflowTags)
{
<span class="tag-chip">#@tag</span>
}
</details>
}
</div> </div>
} }
@if (show.VoteAverage.HasValue && show.VoteAverage > 0) @if (show.EpisodeProgressPercent.HasValue)
{ {
<span class="position-absolute top-0 start-0 badge rounded-pill bg-warning text-dark m-2 shadow-sm">⭐ @string.Format("{0:0.0}", show.VoteAverage)</span> <div class="airing-progress" title="@show.LatestEpisodeNumber of @show.TotalEpisodes episodes aired">
<div class="airing-progress-bar" style="width: @(show.EpisodeProgressPercent)%;"></div>
</div>
} }
@if (!string.IsNullOrWhiteSpace(show.Overview))
{
<p class="airing-overview">
@if (show.OverviewIsSeasonSpecific && show.LatestSeasonNumber > 0)
{
<span class="overview-label">Season @show.LatestSeasonNumber —</span>
}
@show.Overview
</p>
}
else
{
<p class="airing-overview text-secondary fst-italic">No overview available.</p>
}
<footer class="airing-footer">
<a href="https://www.themoviedb.org/tv/@show.ShowID" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-outline-light">TMDB</a>
@if (!string.IsNullOrWhiteSpace(show.AnilistUrl))
{
<a href="@show.AnilistUrl" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-outline-info">AniList</a>
}
@if (show.Download)
{
<span class="btn btn-sm btn-success disabled" aria-disabled="true">✓ Marked for download</span>
}
else
{
<form method="post" asp-page-handler="Download" class="d-inline">
<input type="hidden" name="showId" value="@show.ShowID" />
<button type="submit" class="btn btn-sm btn-outline-success">⬇ Download</button>
</form>
}
@if (show.SecondaryImages.Count > 0)
{
<div class="airing-gallery">
@foreach (var image in show.SecondaryImages)
{
<a href="@image.Url" target="_blank" rel="noopener noreferrer"
class="gallery-thumb" title="@image.Label (@image.Source)">
<img src="@image.Url" alt="@show.Title — @image.Label" loading="lazy" />
</a>
}
</div>
}
</footer>
</div>
<aside class="airing-countdown">
@if (show.EffectiveLastAirDate.HasValue) @if (show.EffectiveLastAirDate.HasValue)
{ {
@if (show.IsFuture) @if (show.IsFuture)
{ {
<span class="position-absolute top-0 end-0 badge rounded-pill bg-danger text-white m-2 shadow-sm">Airs in @Math.Max(show.DaysUntil, 1)d</span> <span class="countdown-number">@Math.Max(show.DaysUntil, 1)</span>
<span class="countdown-unit">@(Math.Max(show.DaysUntil, 1) == 1 ? "day" : "days") away</span>
} }
else else
{ {
<span class="position-absolute top-0 end-0 badge rounded-pill bg-secondary text-white m-2 shadow-sm">Aired @Math.Abs(show.DaysUntil)d ago</span> <span class="countdown-number">@Math.Abs(show.DaysUntil)</span>
<span class="countdown-unit">@(Math.Abs(show.DaysUntil) == 1 ? "day" : "days") ago</span>
} }
} <span class="countdown-date" title="@show.AirDateLongFormatted">@show.AirDateFormatted</span>
</div>
<div class="card-body d-flex flex-column">
<h5 class="card-title text-truncate" title="@show.Title">@show.Title</h5>
<div class="show-meta mb-2 d-flex flex-wrap gap-1">
@if (show.LatestSeasonNumber.HasValue && show.LatestSeasonNumber > 0)
{
<span class="badge rounded-pill bg-light text-dark border">Season @show.LatestSeasonNumber</span>
}
@if (show.LatestEpisodeNumber > 0)
{
@if (show.LastEpisodeNumber.HasValue && show.LastEpisodeNumber > 0)
{
<span class="badge rounded-pill bg-light text-dark border">Ep @show.LatestEpisodeNumber / @show.LastEpisodeNumber</span>
}
else
{
<span class="badge rounded-pill bg-light text-dark border">Ep @show.LatestEpisodeNumber</span>
}
}
@if (show.LatestOrdinalEpisodeNumber.HasValue && show.LatestOrdinalEpisodeNumber > 0)
{
<span class="badge rounded-pill bg-light text-dark border">Total: @show.LatestOrdinalEpisodeNumber</span>
}
</div>
<div class="show-dates mb-2">
@if (show.EffectiveLastAirDate.HasValue)
{
<small class="text-primary fw-semibold">📅 Last air date: @show.AirDateFormatted</small>
}
else
{
<small class="text-secondary">📅 Last air date: @show.AirDateFormatted</small>
}
</div>
</div>
<div class="card-footer bg-transparent border-top-0 pt-0">
@if (!string.IsNullOrWhiteSpace(show.Overview))
{
<p class="show-overview text-muted" title="@show.Overview">@show.Overview</p>
} }
else else
{ {
<p class="show-overview text-secondary fst-italic">No overview available.</p> <span class="countdown-unit">Air date unknown</span>
} }
<div class="d-grid mt-2"> </aside>
<a href="https://www.themoviedb.org/tv/@show.ShowID" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-outline-primary">View on TMDB</a>
</div>
</div>
</div> </div>
</div> </article>
} }
</div> </div>
} }
+211 -16
View File
@@ -1,4 +1,7 @@
using System.Net;
using System.Text.RegularExpressions;
using AnimeAnnouncer.Cache; using AnimeAnnouncer.Cache;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AnimeAnnouncer.Web.Pages; namespace AnimeAnnouncer.Web.Pages;
@@ -43,17 +46,34 @@ public class IndexModel : PageModel
TMDBCacheItem? cacheItem = null; TMDBCacheItem? cacheItem = null;
try try
{ {
cacheItem = await _tmdbCache.GetCacheItem($"ShowCache-{airingItem.Title}"); cacheItem = await _tmdbCache.GetCacheItem<TMDBCacheItem>($"ShowCache-{airingItem.Title}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, "Failed to retrieve cache item for title: {Title}", airingItem.Title); _logger.LogWarning(ex, "Failed to retrieve cache item for title: {Title}", airingItem.Title);
} }
// The announcer stores Anilist details under a parallel key using the same
// title, so the two caches line up one-to-one when Anilist was consulted.
AnilistCacheItem? anilistItem = null;
try
{
anilistItem = await _tmdbCache.GetCacheItem<AnilistCacheItem>($"AnilistCache-{airingItem.Title}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to retrieve Anilist cache item for title: {Title}", airingItem.Title);
}
// With no details from either source there is nothing worth displaying.
if (cacheItem == null && anilistItem == null)
continue;
viewModels.Add(new AiringShowViewModel viewModels.Add(new AiringShowViewModel
{ {
AiringSoon = airingItem, AiringSoon = airingItem,
CachedDetails = cacheItem CachedDetails = cacheItem,
AnilistDetails = anilistItem
}); });
} }
@@ -68,7 +88,7 @@ public class IndexModel : PageModel
}).ToList(); }).ToList();
AiringShows = displayable AiringShows = displayable
.Where(x => x.EffectiveLastAirDate.HasValue && x.EffectiveLastAirDate.Value > DateTime.Now) .Where(x => x.EffectiveLastAirDate.HasValue && x.EffectiveLastAirDate.Value.Date >= DateTime.Now.Date)
.OrderBy(x => x.EffectiveLastAirDate) .OrderBy(x => x.EffectiveLastAirDate)
.ThenBy(x => x.Title) .ThenBy(x => x.Title)
.ToList(); .ToList();
@@ -80,13 +100,43 @@ public class IndexModel : PageModel
} }
} }
public async Task<IActionResult> OnPostDownloadAsync(int showId)
{
if (_tmdbCache == null)
return StatusCode(StatusCodes.Status503ServiceUnavailable);
try
{
if (!await _tmdbCache.SetDownload(showId, true))
_logger.LogWarning("Download requested for show {ShowID}, which is not in the airing list", showId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to flag show {ShowID} for download", showId);
}
// Post/redirect/get, landing back on the row that was clicked.
return RedirectToPage(null, null, null, $"show-{showId}");
}
public class ShowImage
{
public required string Url { get; set; }
public required string Label { get; set; }
public required string Source { get; set; }
}
public class AiringShowViewModel public class AiringShowViewModel
{ {
private static readonly Regex HtmlTagPattern = new("<[^>]+>", RegexOptions.Compiled);
public required AiringSoonItem AiringSoon { get; set; } public required AiringSoonItem AiringSoon { get; set; }
public TMDBCacheItem? CachedDetails { get; set; } public TMDBCacheItem? CachedDetails { get; set; }
public AnilistCacheItem? AnilistDetails { get; set; }
public string Title => AiringSoon.Title; public string Title => AiringSoon.Title;
public int ShowID => AiringSoon.ShowID; public int ShowID => AiringSoon.ShowID;
public bool Download => AiringSoon.Download;
public DateTime? EffectiveLastAirDate => AiringSoon.LastAirDate ?? CachedDetails?.LastAirDate; public DateTime? EffectiveLastAirDate => AiringSoon.LastAirDate ?? CachedDetails?.LastAirDate;
public int LatestEpisodeNumber => AiringSoon.LatestEpisodeNumber > 0 public int LatestEpisodeNumber => AiringSoon.LatestEpisodeNumber > 0
? AiringSoon.LatestEpisodeNumber ? AiringSoon.LatestEpisodeNumber
@@ -95,25 +145,152 @@ public class IndexModel : PageModel
public int? LatestSeasonNumber => CachedDetails?.LatestSeasonNumber; public int? LatestSeasonNumber => CachedDetails?.LatestSeasonNumber;
public int? LatestOrdinalEpisodeNumber => CachedDetails?.LatestOrdinalEpisodeNumber; public int? LatestOrdinalEpisodeNumber => CachedDetails?.LatestOrdinalEpisodeNumber;
public double? VoteAverage => CachedDetails?.VoteAverage; public double? VoteAverage => CachedDetails?.VoteAverage;
public string? Overview => !string.IsNullOrWhiteSpace(CachedDetails?.LatestSeasonOverview)
? CachedDetails.LatestSeasonOverview
: CachedDetails?.Overview;
public string? PosterUrl // --- Anilist ---------------------------------------------------------
public bool HasAnilist => AnilistDetails != null;
public int? AnilistShowID => AnilistDetails?.ShowID;
public string? AnilistUrl => AnilistShowID.HasValue ? $"https://anilist.co/anime/{AnilistShowID}" : null;
/// <summary>Anilist's 0-100 score, rescaled to the 0-10 range TMDB uses.</summary>
public double? AnilistScore => AnilistDetails?.AverageScore.HasValue == true
? AnilistDetails.AverageScore!.Value / 10.0
: null;
public string? AnilistStatus => string.IsNullOrWhiteSpace(AnilistDetails?.Status)
? null
// Anilist statuses arrive as enum names like RELEASING / NOT_YET_RELEASED.
: string.Join(' ', AnilistDetails.Status.Split('_', StringSplitOptions.RemoveEmptyEntries)
.Select(word => char.ToUpperInvariant(word[0]) + word[1..].ToLowerInvariant()));
public int? SeasonYear => AnilistDetails?.SeasonYear;
/// <summary>Total episode count, preferring Anilist which the announcer treats as more reliable.</summary>
public int? TotalEpisodes => AnilistDetails?.Episodes ?? (LastEpisodeNumber > 0 ? LastEpisodeNumber : null);
/// <summary>Alternate titles worth showing, i.e. anything that is not just the display title again.</summary>
public List<string> AlternateTitles
{ {
get get
{ {
if (!string.IsNullOrWhiteSpace(CachedDetails?.LatestSeasonPosterPath)) var candidates = new[] { AnilistDetails?.RomajiTitle, AnilistDetails?.NativeTitle, AnilistDetails?.EnglishTitle };
return CachedDetails.LatestSeasonPosterPath; return candidates
if (!string.IsNullOrWhiteSpace(CachedDetails?.PosterPath)) .Where(t => !string.IsNullOrWhiteSpace(t))
return CachedDetails.PosterPath; .Select(t => t!.Trim())
if (!string.IsNullOrWhiteSpace(CachedDetails?.AnilistPosterPath)) .Where(t => !string.Equals(t, Title, StringComparison.OrdinalIgnoreCase))
return CachedDetails.AnilistPosterPath; .Distinct(StringComparer.OrdinalIgnoreCase)
return null; .ToList();
} }
} }
public string? BackdropUrl => CachedDetails?.BackdropPath; // --- Genres & tags ---------------------------------------------------
/// <summary>How many tags are shown before the rest are tucked behind a "more" toggle.</summary>
public const int VisibleTagCount = 10;
/// <summary>
/// Genres from both sources, AniList first. TMDB's "Animation" genre is dropped since every
/// show on this page is anime, so it carries no information.
/// </summary>
public List<string> Genres => MergeDistinct(AnilistDetails?.Genres, CachedDetails?.Genres)
.Where(g => !string.Equals(g, "Animation", StringComparison.OrdinalIgnoreCase))
.ToList();
/// <summary>AniList tags followed by TMDB keywords, minus anything already listed as a genre.</summary>
public List<string> Tags
{
get
{
var genres = new HashSet<string>(Genres, StringComparer.OrdinalIgnoreCase);
return MergeDistinct(AnilistDetails?.Tags, CachedDetails?.Keywords)
.Where(t => !genres.Contains(t))
.ToList();
}
}
public List<string> VisibleTags => Tags.Take(VisibleTagCount).ToList();
public List<string> OverflowTags => Tags.Skip(VisibleTagCount).ToList();
private static IEnumerable<string> MergeDistinct(params IEnumerable<string>?[] sources) =>
sources
.Where(s => s != null)
.SelectMany(s => s!)
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase);
/// <summary>Anilist descriptions are HTML fragments; flatten them to plain text for display.</summary>
public string? AnilistDescription
{
get
{
if (string.IsNullOrWhiteSpace(AnilistDetails?.Description))
return null;
var text = AnilistDetails.Description
.Replace("<br>", " ", StringComparison.OrdinalIgnoreCase)
.Replace("<br/>", " ", StringComparison.OrdinalIgnoreCase)
.Replace("<br />", " ", StringComparison.OrdinalIgnoreCase);
text = WebUtility.HtmlDecode(HtmlTagPattern.Replace(text, string.Empty));
text = Regex.Replace(text, @"\s{2,}", " ").Trim();
return string.IsNullOrWhiteSpace(text) ? null : text;
}
}
public string? Overview => !string.IsNullOrWhiteSpace(CachedDetails?.LatestSeasonOverview)
? CachedDetails.LatestSeasonOverview
: (!string.IsNullOrWhiteSpace(CachedDetails?.Overview) ? CachedDetails.Overview : AnilistDescription);
/// <summary>True when <see cref="Overview"/> describes the current season rather than the series.</summary>
public bool OverviewIsSeasonSpecific => !string.IsNullOrWhiteSpace(CachedDetails?.LatestSeasonOverview);
// --- Artwork ---------------------------------------------------------
public string? SeasonPosterUrl => Clean(CachedDetails?.LatestSeasonPosterPath);
public string? ShowPosterUrl => Clean(CachedDetails?.PosterPath);
public string? BackdropUrl => Clean(CachedDetails?.BackdropPath);
public string? AnilistCoverUrl => Clean(AnilistDetails?.CoverImageUrl);
public string? AnilistBannerUrl => Clean(AnilistDetails?.BannerImageUrl);
/// <summary>The tall artwork shown alongside the entry; the season's own poster wins when present.</summary>
public string? PosterUrl => SeasonPosterUrl ?? ShowPosterUrl ?? AnilistCoverUrl;
/// <summary>The wide artwork used as the row background.</summary>
public string? HeroImageUrl => BackdropUrl ?? AnilistBannerUrl;
/// <summary>Every distinct piece of artwork, for the secondary thumbnail strip.</summary>
public List<ShowImage> Gallery
{
get
{
var images = new List<ShowImage>();
void Add(string? url, string label, string source)
{
if (string.IsNullOrWhiteSpace(url))
return;
if (images.Any(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase)))
return;
images.Add(new ShowImage { Url = url, Label = label, Source = source });
}
// The primary poster is already displayed beside the row, so start after it.
Add(SeasonPosterUrl, $"Season {LatestSeasonNumber} poster", "TMDB");
Add(ShowPosterUrl, "Series poster", "TMDB");
Add(AnilistCoverUrl, "Cover art", "AniList");
Add(BackdropUrl, "Backdrop", "TMDB");
Add(AnilistBannerUrl, "Banner", "AniList");
return images;
}
}
/// <summary>Gallery entries other than the one already shown as the main poster.</summary>
public List<ShowImage> SecondaryImages =>
Gallery.Where(i => !string.Equals(i.Url, PosterUrl, StringComparison.OrdinalIgnoreCase)).ToList();
// --- Air dates -------------------------------------------------------
public DateTime AirReferenceNow => DateTime.Now; public DateTime AirReferenceNow => DateTime.Now;
@@ -145,6 +322,24 @@ public class IndexModel : PageModel
return date.HasValue ? date.Value.ToString("MM/dd/yyyy") : "Unknown"; return date.HasValue ? date.Value.ToString("MM/dd/yyyy") : "Unknown";
} }
} }
public string? AirDateLongFormatted => EffectiveLastAirDate?.ToString("dddd, MMMM d, yyyy");
/// <summary>How far into the season the latest aired episode sits, as a percentage.</summary>
public int? EpisodeProgressPercent
{
get
{
var total = TotalEpisodes;
if (!total.HasValue || total.Value <= 0 || LatestEpisodeNumber <= 0)
return null;
return (int)Math.Round(Math.Clamp(LatestEpisodeNumber / (double)total.Value, 0, 1) * 100);
}
}
/// <summary>True when the upcoming episode is the last one of the season.</summary>
public bool IsFinaleNext => TotalEpisodes.HasValue && LatestEpisodeNumber > 0 && LatestEpisodeNumber >= TotalEpisodes.Value;
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
} }
} }
+395 -30
View File
@@ -41,55 +41,420 @@ a:hover {
color: #e9ecef; color: #e9ecef;
} }
/* --- Anime airing-soon cards --- */ /* --- Airing-soon rows -------------------------------------------------
.anime-card { Each show gets one full-width horizontal row: the TMDB backdrop (or the
AniList banner as a fallback) fills the row behind a scrim, the season
poster anchors the left edge, and the remaining artwork appears as a
thumbnail strip in the footer. */
.airing-list {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.airing-row {
position: relative;
overflow: hidden;
border-radius: 1rem;
background-color: #1a1a1a;
border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.45);
transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
}
.airing-row:hover {
transform: translateY(-3px);
box-shadow: 0 0.9rem 1.8rem rgba(0, 0, 0, 0.55);
border-color: rgba(255, 255, 255, 0.16);
}
.airing-row.is-upcoming {
border-left: 4px solid #ff6b6b;
}
.airing-row.is-aired {
border-left: 4px solid rgba(255, 255, 255, 0.18);
}
.airing-backdrop {
position: absolute;
inset: 0;
background-size: cover;
background-position: center 25%;
opacity: 0.6;
transform: scale(1.02);
transition: opacity 0.3s ease, transform 0.4s ease;
}
.airing-row:hover .airing-backdrop {
opacity: 0.8;
transform: scale(1.05);
}
/* Keeps the text readable regardless of how bright the backdrop is. */
.airing-scrim {
position: absolute;
inset: 0;
background:
linear-gradient(90deg, rgba(18, 18, 18, 0.96) 0%, rgba(18, 18, 18, 0.86) 40%, rgba(18, 18, 18, 0.35) 100%),
linear-gradient(0deg, rgba(18, 18, 18, 0.7) 0%, rgba(18, 18, 18, 0.2) 65%);
}
.airing-content {
position: relative;
display: flex;
gap: 1.5rem;
padding: 1.5rem;
}
/* --- Poster --- */
.airing-poster {
position: relative;
flex: 0 0 170px;
aspect-ratio: 2 / 3;
border-radius: 0.75rem; border-radius: 0.75rem;
overflow: hidden; overflow: hidden;
transition: transform 0.2s ease, box-shadow 0.2s ease;
background-color: #1e1e1e;
border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.anime-card:hover {
transform: translateY(-4px);
box-shadow: 0 0.75rem 1.5rem rgba(0, 0, 0, 0.45);
}
.anime-poster-container {
position: relative;
height: 320px;
background-color: #2a2a2a; background-color: #2a2a2a;
overflow: hidden; box-shadow: 0 6px 18px rgba(0, 0, 0, 0.6);
} }
.anime-poster { .airing-poster img {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: cover;
display: block; display: block;
transition: transform 0.3s ease;
} }
.anime-card:hover .anime-poster { .airing-poster-placeholder {
transform: scale(1.03); display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 3rem;
color: #6c757d;
} }
.show-overview { .airing-poster-tag {
position: absolute;
left: 0;
right: 0;
bottom: 0;
padding: 0.3rem 0.5rem;
text-align: center;
font-size: 0.78rem;
font-weight: 600;
letter-spacing: 0.02em;
color: #f8f9fa;
background: rgba(0, 0, 0, 0.72);
backdrop-filter: blur(2px);
}
/* --- Body --- */
.airing-body {
flex: 1 1 auto;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.airing-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.airing-titles {
min-width: 0;
}
.airing-title {
margin: 0;
font-size: clamp(1.35rem, 1.1rem + 0.9vw, 2.1rem);
font-weight: 700;
line-height: 1.15;
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.8);
}
.airing-alt-titles {
margin: 0.25rem 0 0;
font-size: 0.85rem;
color: #adb5bd;
}
.airing-scores {
display: flex;
gap: 0.5rem;
flex-shrink: 0;
}
.score-chip {
display: flex;
flex-direction: column;
align-items: center;
min-width: 3.6rem;
padding: 0.3rem 0.5rem;
border-radius: 0.6rem;
background: rgba(0, 0, 0, 0.55);
border: 1px solid rgba(255, 255, 255, 0.18);
backdrop-filter: blur(4px);
}
.score-value {
font-size: 1.15rem;
font-weight: 700;
line-height: 1.1;
}
.score-source {
font-size: 0.62rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #adb5bd;
}
.score-tmdb .score-value {
color: #ffd43b;
}
.score-anilist .score-value {
color: #02a9ff;
}
/* --- Metadata --- */
.airing-meta {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.meta-chip {
padding: 0.2rem 0.65rem;
border-radius: 999px;
font-size: 0.8rem;
color: #e9ecef;
background: rgba(0, 0, 0, 0.5);
border: 1px solid rgba(255, 255, 255, 0.16);
backdrop-filter: blur(4px);
}
.meta-chip-finale {
color: #ffd43b;
border-color: rgba(255, 212, 59, 0.5);
background: rgba(255, 212, 59, 0.12);
}
/* --- Genres & tags --- */
.airing-taxonomy {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.35rem;
}
.genre-chip {
padding: 0.15rem 0.6rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 600;
color: #d0bfff;
background: rgba(151, 117, 250, 0.18);
border: 1px solid rgba(151, 117, 250, 0.45);
backdrop-filter: blur(4px);
}
.tag-chip {
padding: 0.1rem 0.5rem;
border-radius: 4px;
font-size: 0.72rem;
color: #ced4da;
background: rgba(0, 0, 0, 0.35);
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* The overflow list flows inline with the other chips once opened. */
.tag-overflow {
display: contents;
}
.tag-overflow > summary {
list-style: none;
cursor: pointer;
}
.tag-overflow > summary::-webkit-details-marker {
display: none;
}
.tag-more {
color: #74c0fc;
border-style: dashed;
}
.tag-overflow[open] > .tag-more {
display: none;
}
.airing-progress {
height: 6px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.12);
overflow: hidden;
}
.airing-progress-bar {
height: 100%;
border-radius: 999px;
background: linear-gradient(90deg, #4dabf7, #02a9ff);
}
.airing-overview {
margin: 0;
font-size: 0.95rem;
line-height: 1.55;
color: #dee2e6;
/* Full-width rows fit most synopses; only the longest ones get clipped. */
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 4; -webkit-line-clamp: 6;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis;
line-height: 1.45;
font-size: 0.875rem;
min-height: 5.1em;
margin-bottom: 0.5rem;
white-space: normal;
word-break: normal;
overflow-wrap: break-word; overflow-wrap: break-word;
} }
.overview-label {
font-weight: 600;
color: #adb5bd;
}
.airing-footer {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: auto;
padding-top: 0.5rem;
}
.airing-gallery {
display: flex;
gap: 0.4rem;
margin-left: auto;
flex-wrap: wrap;
}
.gallery-thumb {
display: block;
height: 46px;
border-radius: 0.35rem;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.18);
opacity: 0.75;
transition: opacity 0.2s ease, transform 0.2s ease;
}
.gallery-thumb:hover {
opacity: 1;
transform: translateY(-2px);
}
.gallery-thumb img {
height: 46px;
width: auto;
display: block;
}
/* --- Countdown --- */
.airing-countdown {
flex: 0 0 8rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding-left: 1rem;
border-left: 1px solid rgba(255, 255, 255, 0.1);
}
.countdown-number {
font-size: 3rem;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
}
.is-upcoming .countdown-number {
color: #ff8787;
}
.is-aired .countdown-number {
color: #adb5bd;
}
.countdown-unit {
font-size: 0.85rem;
color: #ced4da;
}
.countdown-date {
margin-top: 0.35rem;
font-size: 0.78rem;
color: #adb5bd;
}
/* --- Narrower viewports --- */
@media (max-width: 991.98px) {
.airing-poster {
flex-basis: 140px;
}
.countdown-number {
font-size: 2.25rem;
}
}
@media (max-width: 767.98px) {
.airing-content {
flex-wrap: wrap;
padding: 1rem;
gap: 1rem;
}
.airing-poster {
flex-basis: 110px;
align-self: flex-start;
}
.airing-body {
flex-basis: 0;
}
/* The countdown drops below the row rather than squeezing the synopsis. */
.airing-countdown {
order: 3;
flex: 0 0 100%;
flex-direction: row;
justify-content: flex-start;
gap: 0.5rem;
padding-left: 0;
padding-top: 0.75rem;
border-left: none;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.countdown-number {
font-size: 1.5rem;
}
.airing-header {
flex-direction: column;
}
.airing-overview {
-webkit-line-clamp: 10;
}
}
/* --- Wide / ultra-wide / 4K display support --- /* --- Wide / ultra-wide / 4K display support ---
Bootstrap 5's ".container" tops out at max-width: 1320px starting at its Bootstrap 5's ".container" tops out at max-width: 1320px starting at its
largest built-in breakpoint (1400px) and never grows beyond that, so on largest built-in breakpoint (1400px) and never grows beyond that, so on
+14
View File
@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MassTorrentAdd", "MassTorre
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnimeAnnouncer.Web", "AnimeAnnouncer.Web\AnimeAnnouncer.Web.csproj", "{DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnimeAnnouncer.Web", "AnimeAnnouncer.Web\AnimeAnnouncer.Web.csproj", "{DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnimeAnnouncer.Torrents", "AnimeAnnouncer.Torrents\AnimeAnnouncer.Torrents.csproj", "{901424DF-F8CD-449B-9517-73CA42D61B54}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -55,6 +57,18 @@ Global
{DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x64.Build.0 = Release|Any CPU {DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x64.Build.0 = Release|Any CPU
{DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x86.ActiveCfg = Release|Any CPU {DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x86.ActiveCfg = Release|Any CPU
{DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x86.Build.0 = Release|Any CPU {DD4F134D-B455-4A8C-8DDE-AA0ED735DA42}.Release|x86.Build.0 = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|Any CPU.Build.0 = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|x64.ActiveCfg = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|x64.Build.0 = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|x86.ActiveCfg = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Debug|x86.Build.0 = Debug|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|Any CPU.ActiveCfg = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|Any CPU.Build.0 = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|x64.ActiveCfg = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|x64.Build.0 = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|x86.ActiveCfg = Release|Any CPU
{901424DF-F8CD-449B-9517-73CA42D61B54}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
+6
View File
@@ -38,6 +38,12 @@ public class Anilist
return result; return result;
} }
public async Task<List<String>> GetMediaTags(int mediaId)
{
var results = await client.GetMediaTagsAsync(mediaId);
return results.Select(p => p.Name).ToList();
}
private async Task Authenticate() private async Task Authenticate()
{ {
Boolean success = await client.TryAuthenticateAsync(Token); Boolean success = await client.TryAuthenticateAsync(Token);
+3
View File
@@ -27,4 +27,7 @@
<HintPath>..\Libraries\TMDbLib.dll</HintPath> <HintPath>..\Libraries\TMDbLib.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AnimeAnnouncer.Torrents\AnimeAnnouncer.Torrents.csproj" />
</ItemGroup>
</Project> </Project>
+1
View File
@@ -7,5 +7,6 @@ namespace AnimeAnnouncer.Cache
public int ShowID { get; set; } public int ShowID { get; set; }
public DateTime? LastAirDate { get; set; } public DateTime? LastAirDate { get; set; }
public int LatestEpisodeNumber { get; set; } public int LatestEpisodeNumber { get; set; }
public bool Download { get; set; }
} }
} }
+45
View File
@@ -0,0 +1,45 @@
using Kavita.AniListNet.Objects;
namespace AnimeAnnouncer.Cache
{
public class AnilistCacheItem
{
public required String Title { get; set; }
public int ShowID { get; set; }
public string? EnglishTitle { get; set; }
public string? RomajiTitle { get; set; }
public string? NativeTitle { get; set; }
public int? Episodes { get; set; }
public string? Status { get; set; }
public int? SeasonYear { get; set; }
public string? Description { get; set; }
public string? BannerImageUrl { get; set; }
public string? CoverImageUrl { get; set; }
public int? AverageScore { get; set; }
public List<String> Genres { get; set; }
public List<String> Tags { get; set; }
public DateTime? Updated { get; set; }
public static AnilistCacheItem FromMedia(Media media, List<String> tags)
{
return new AnilistCacheItem
{
Title = media.Title.EnglishTitle ?? media.Title.RomajiTitle,
ShowID = media.Id,
EnglishTitle = media.Title.EnglishTitle,
RomajiTitle = media.Title.RomajiTitle,
NativeTitle = media.Title.NativeTitle,
Episodes = media.Episodes,
Status = media.Status?.ToString(),
SeasonYear = media.SeasonYear,
Description = media.Description,
BannerImageUrl = media.BannerImageUrl?.ToString(),
CoverImageUrl = media.Cover?.ExtraLargeImageUrl?.ToString(),
AverageScore = media.AverageScore,
Genres = media.Genres.ToList(),
Tags = tags
};
}
}
}
+18 -5
View File
@@ -17,22 +17,22 @@ public class TMDBCache
CacheExpiration = TimeSpan.FromDays(3); CacheExpiration = TimeSpan.FromDays(3);
redis = ConnectionMultiplexer.Connect(redisConnectionString); redis = ConnectionMultiplexer.Connect(redisConnectionString);
} }
public async Task SetCacheItem(String key, TMDBCacheItem item) public async Task SetCacheItem<T>(String key, T item)
{ {
var db = redis.GetDatabase(); var db = redis.GetDatabase();
String jsonItem = JsonSerializer.Serialize(item); String jsonItem = JsonSerializer.Serialize(item);
await db.StringSetAsync(key, jsonItem, CacheExpiration); await db.StringSetAsync(key, jsonItem, CacheExpiration);
} }
public async Task<TMDBCacheItem> GetCacheItem(String key) public async Task<T?> GetCacheItem<T>(String key)
{ {
var db = redis.GetDatabase(); var db = redis.GetDatabase();
String jsonItem = await db.StringGetAsync(key); String? jsonItem = await db.StringGetAsync(key);
if (!String.IsNullOrEmpty(jsonItem)) if (!String.IsNullOrEmpty(jsonItem))
return JsonSerializer.Deserialize<TMDBCacheItem>(jsonItem); return JsonSerializer.Deserialize<T>(jsonItem);
else else
return null; return default;
} }
public async Task RemoveCacheItem(String key) public async Task RemoveCacheItem(String key)
@@ -60,6 +60,19 @@ public class TMDBCache
else else
return null; return null;
} }
/// <summary>Sets the Download flag on one airing list entry. Returns false when the show is not in the list.</summary>
public async Task<bool> SetDownload(int showID, bool download)
{
var list = await GetAiringList();
var item = list?.FirstOrDefault(s => s.ShowID == showID);
if (item == null)
return false;
item.Download = download;
await SetAiringSoon(list!);
return true;
}
public async Task<bool> KeyExists(String key) public async Task<bool> KeyExists(String key)
{ {
var db = redis.GetDatabase(); var db = redis.GetDatabase();
+5 -1
View File
@@ -21,7 +21,11 @@ namespace AnimeAnnouncer.Cache
public int? LatestEpisodeNumber { get; set; } public int? LatestEpisodeNumber { get; set; }
public Boolean? AnilistPopulated { get; set; } public Boolean? AnilistPopulated { get; set; }
public String? AnilistPosterPath { get; set; }
public DateTime? Updated { get; set; }
public List<String> Genres { get; set; }
public List<String> Keywords { get; set; }
} }
} }
+97 -19
View File
@@ -4,12 +4,14 @@ using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using AnimeAnnouncer.Cache; using AnimeAnnouncer.Cache;
using AnimeAnnouncer.RSS; using AnimeAnnouncer.RSS;
using AnimeAnnouncer.Torrents;
using Mastonet; using Mastonet;
using Mastonet.Entities; using Mastonet.Entities;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using TMDbLib.Client; using TMDbLib.Client;
using TMDbLib.Objects.Authentication; using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.TvShows;
namespace AnimeAnnouncer namespace AnimeAnnouncer
{ {
@@ -23,6 +25,9 @@ namespace AnimeAnnouncer
private static Anilist? anilistClient; private static Anilist? anilistClient;
private static List<AiringSoonItem> airingSoonList; private static List<AiringSoonItem> airingSoonList;
private static TransmissionService transmissionService;
private static String destinationFolder;
static void Main(string[] args) static void Main(string[] args)
{ {
Console.WriteLine("Starting..."); Console.WriteLine("Starting...");
@@ -49,7 +54,7 @@ namespace AnimeAnnouncer
Console.WriteLine("Using cache"); Console.WriteLine("Using cache");
} }
tmdbCache.CacheExpiration = TimeSpan.FromDays(7); tmdbCache.CacheExpiration = TimeSpan.FromDays(8);
String mastodonInstance = config["MastodonInstance"]; String mastodonInstance = config["MastodonInstance"];
@@ -64,6 +69,19 @@ namespace AnimeAnnouncer
if (!String.IsNullOrEmpty(anilistToken)) if (!String.IsNullOrEmpty(anilistToken))
anilistClient = new Anilist(anilistToken); anilistClient = new Anilist(anilistToken);
String? transmissionHost = config["transmissionURI"];
String? transmissionUsername = config["transmissionUsername"];
String? transmissionPassword = config["transmissionPassword"];
destinationFolder = config["destinationFolder"];
if (transmissionHost != null && transmissionUsername != null && transmissionPassword != null &&
destinationFolder != null)
{
Console.WriteLine("Connecting to transmission");
transmissionService = TransmissionService.ConnectAsync(transmissionHost, transmissionUsername, transmissionPassword).Result;
}
airingSoonList = tmdbCache.GetAiringList().Result; airingSoonList = tmdbCache.GetAiringList().Result;
if(airingSoonList == null) if(airingSoonList == null)
@@ -146,10 +164,13 @@ namespace AnimeAnnouncer
TMDBCacheItem? cachedShow = null; TMDBCacheItem? cachedShow = null;
latestEpisodeNumber = int.Parse(episode);
try try
{ {
cachedShow = await tmdbCache.GetCacheItem($"ShowCache-{title}"); cachedShow = await tmdbCache.GetCacheItem<TMDBCacheItem>($"ShowCache-{title}");
if(cachedShow != null)
if(cachedShow != null && (cachedShow.Updated.HasValue && DateTime.Now.Subtract(cachedShow.Updated.Value).Days < 6))
{ {
Console.WriteLine("Cache hit"); Console.WriteLine("Cache hit");
latestSeasonNumber = cachedShow.LatestSeasonNumber; latestSeasonNumber = cachedShow.LatestSeasonNumber;
@@ -180,7 +201,7 @@ namespace AnimeAnnouncer
//supposedShowId = searchResults.Results.First().Id; //supposedShowId = searchResults.Results.First().Id;
supposedShowId = searchResults.Results.OrderBy(r => ComputeLevenshteinDistance(title, r.Name)).First().Id; supposedShowId = searchResults.Results.OrderBy(r => ComputeLevenshteinDistance(title, r.Name)).First().Id;
var showResult = await tmdbClient.GetTvShowAsync(supposedShowId); var showResult = await tmdbClient.GetTvShowAsync(supposedShowId, TvShowMethods.Keywords);
var latestSeason = showResult.Seasons.Where(s => s.AirDate.HasValue && s.AirDate.Value < DateTime.Now).OrderByDescending(s => s.SeasonNumber).FirstOrDefault(); var latestSeason = showResult.Seasons.Where(s => s.AirDate.HasValue && s.AirDate.Value < DateTime.Now).OrderByDescending(s => s.SeasonNumber).FirstOrDefault();
@@ -194,7 +215,7 @@ namespace AnimeAnnouncer
lastEpisodeNumber = latestSeason.EpisodeCount; lastEpisodeNumber = latestSeason.EpisodeCount;
latestEpisodeNumber = int.Parse(episode);
//if nearing the end of a season, confirm it's marked with season finale //if nearing the end of a season, confirm it's marked with season finale
@@ -224,21 +245,33 @@ namespace AnimeAnnouncer
{ {
try try
{ {
Console.WriteLine("Looking up Anilist title " + title); AnilistCacheItem? anilistCacheItem = await tmdbCache.GetCacheItem<AnilistCacheItem>($"AnilistCache-{title}");
var anilistMedia = await anilistClient.RetrieveAiringShowInformation(title); if (anilistCacheItem == null)
if (anilistMedia != null)
{ {
if (anilistMedia.Episodes.HasValue && anilistMedia.Episodes != lastEpisodeNumber) Console.WriteLine("Looking up Anilist title " + title);
var anilistMedia = await anilistClient.RetrieveAiringShowInformation(title);
if (anilistMedia != null)
{
var tags = await anilistClient.GetMediaTags(anilistMedia.Id);
anilistCacheItem = AnilistCacheItem.FromMedia(anilistMedia, tags);
anilistCacheItem.Updated = DateTime.Now;
_ = tmdbCache.SetCacheItem($"AnilistCache-{title}", anilistCacheItem);
}
else
Console.WriteLine("0 anilist results found");
}
if (anilistCacheItem != null)
{
if (anilistCacheItem.Episodes.HasValue && anilistCacheItem.Episodes != lastEpisodeNumber)
{ {
Console.WriteLine( Console.WriteLine(
$"Overriding episode count of {lastEpisodeNumber} using Anilist's showID {anilistMedia.Id} titled {anilistMedia.Title.EnglishTitle} with {anilistMedia.Episodes} episodes."); $"Overriding episode count of {lastEpisodeNumber} using Anilist's showID {anilistCacheItem.ShowID} titled {anilistCacheItem.EnglishTitle} with {anilistCacheItem.Episodes} episodes.");
lastEpisodeNumber = anilistMedia.Episodes.Value; lastEpisodeNumber = anilistCacheItem.Episodes.Value;
} }
anilistPosterPath = anilistMedia.BannerImageUrl?.ToString(); anilistPosterPath = anilistCacheItem.BannerImageUrl;
} }
else
Console.WriteLine("0 anilist results found");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -276,7 +309,9 @@ namespace AnimeAnnouncer
LastAirDate = lastAirDate, LastAirDate = lastAirDate,
LatestEpisodeNumber = latestEpisodeNumber, LatestEpisodeNumber = latestEpisodeNumber,
AnilistPopulated = anilistPosterPath != null, AnilistPopulated = anilistPosterPath != null,
AnilistPosterPath = anilistPosterPath Updated = DateTime.Now,
Keywords = showResult.Keywords != null ? showResult.Keywords.Results.Select(p => p.Name).ToList() : new List<string>(),
Genres = showResult.Genres != null ? showResult.Genres.Select(p => p.Name).ToList() : new List<string>(),
}; };
_ = tmdbCache.SetCacheItem($"ShowCache-{title}", cachedShow); _ = tmdbCache.SetCacheItem($"ShowCache-{title}", cachedShow);
Console.WriteLine($"{title} Added to cache"); Console.WriteLine($"{title} Added to cache");
@@ -297,7 +332,7 @@ namespace AnimeAnnouncer
{ {
var titleSeason = int.Parse(season); var titleSeason = int.Parse(season);
bool seasonOverride = false; bool seasonOverride = false;
if(latestSeasonNumber ==1 && titleSeason > 1 && lastEpisodeNumber > 3) if(latestSeasonNumber < titleSeason && titleSeason > 1 && lastEpisodeNumber > 3)
{ //Check episode groups to see if this is a single-season default show { //Check episode groups to see if this is a single-season default show
var showResult = await tmdbClient.GetTvShowAsync(supposedShowId, TMDbLib.Objects.TvShows.TvShowMethods.EpisodeGroups); var showResult = await tmdbClient.GetTvShowAsync(supposedShowId, TMDbLib.Objects.TvShows.TvShowMethods.EpisodeGroups);
var seasonEpisodeGroup = showResult.EpisodeGroups.Results.FirstOrDefault(eg => eg.Name == "Seasons"); var seasonEpisodeGroup = showResult.EpisodeGroups.Results.FirstOrDefault(eg => eg.Name == "Seasons");
@@ -382,7 +417,14 @@ namespace AnimeAnnouncer
try try
{ {
_ = tmdbCache.SetPair($"ShowAnnounced-{supposedShowId}", latestSeasonNumber.ToString()); _ = tmdbCache.SetPair($"ShowAnnounced-{supposedShowId}", latestSeasonNumber.ToString());
PostStatus(cachedShow); _ = PostStatus(cachedShow);
var existingAiringItem = airingSoonList.FirstOrDefault(s => s.ShowID == cachedShow.ShowID);
if (existingAiringItem is { Download: true })
{
Console.WriteLine($"Attempting to queue {existingAiringItem.Title} in the torrent client");
await AddToTorrentClient(cachedShow);
}
} }
catch(Exception ex) catch(Exception ex)
{ {
@@ -393,6 +435,29 @@ namespace AnimeAnnouncer
Console.WriteLine($"Choosing {title} as a finished season!"); Console.WriteLine($"Choosing {title} as a finished season!");
} }
private static async Task AddToTorrentClient(TMDBCacheItem cacheItem)
{
var reader = new NyaaRssReader();
var titleParts = TorrentDirectoryNamer.PrepareForURI(cacheItem.Title);
var seasonNumber = $"S{cacheItem.LatestSeasonNumber:D2}";
var url = $"https://nyaa.si/?f=0&c=0_0&q={titleParts}+{seasonNumber}+CR+VARYG+DUAL";
var items = await reader.ReadAsync(url);
if (items.Count != cacheItem.LastEpisodeNumber)
{
Console.WriteLine($"{cacheItem.Title} had {items.Count} results but only {cacheItem.LastEpisodeNumber} episodes. Aborting.");
return;
}
var folderName = TorrentDirectoryNamer.FromTitle(items.First().Title, destinationFolder);
Console.WriteLine($"Adding {folderName} to transmission");
foreach (var item in items)
{
var torrentData = await reader.DownloadTorrentAsync(item);
await transmissionService.AddNewTorrentFileToServerAsync(torrentData, folderName);
}
}
private static async Task CreateAiringMonthPost() private static async Task CreateAiringMonthPost()
{ {
@@ -455,7 +520,7 @@ namespace AnimeAnnouncer
*/ */
} }
private static async void PostStatus(TMDBCacheItem cachedShow) private static async Task PostStatus(TMDBCacheItem cachedShow)
{ {
//get poster //get poster
String? posterUrl = cachedShow.LatestSeasonPosterPath ?? cachedShow.PosterPath; String? posterUrl = cachedShow.LatestSeasonPosterPath ?? cachedShow.PosterPath;
@@ -507,14 +572,27 @@ namespace AnimeAnnouncer
} }
else else
{ {
if(existingAiringItem.LatestEpisodeNumber >= cachedShow.LatestEpisodeNumber) if(existingAiringItem.LatestEpisodeNumber >= cachedShow.LatestEpisodeNumber && existingAiringItem.LastAirDate == airingSoonItem.LastAirDate)
{ {
Console.WriteLine($"Not updating {cachedShow.Title} airdate due to episode number not incrementing"); Console.WriteLine($"Not updating {cachedShow.Title} airdate due to episode number not incrementing");
return; return;
} }
airingSoonItem.Download = existingAiringItem.Download;
airingSoonList.RemoveAll(s => s.ShowID == cachedShow.ShowID); airingSoonList.RemoveAll(s => s.ShowID == cachedShow.ShowID);
airingSoonList.Add(airingSoonItem); airingSoonList.Add(airingSoonItem);
} }
// The web page can flag shows for download directly in the cache, so carry those
// flags over rather than overwriting them with this process's in-memory copy.
var cachedList = await tmdbCache.GetAiringList();
if (cachedList != null)
{
foreach (var cached in cachedList.Where(c => c.Download))
{
var local = airingSoonList.FirstOrDefault(s => s.ShowID == cached.ShowID);
if (local != null)
local.Download = true;
}
}
airingSoonList.Sort((showOne, showTwo) => showOne.LastAirDate.Value.CompareTo(showTwo.LastAirDate.Value)); airingSoonList.Sort((showOne, showTwo) => showOne.LastAirDate.Value.CompareTo(showTwo.LastAirDate.Value));
_ = tmdbCache.SetAiringSoon(airingSoonList); _ = tmdbCache.SetAiringSoon(airingSoonList);
Console.WriteLine($"Updated airing soon list, setting {cachedShow.Title} Season {cachedShow.LatestSeasonNumber} to end on {cachedShow.LastAirDate ?? DateTime.MaxValue}"); Console.WriteLine($"Updated airing soon list, setting {cachedShow.Title} Season {cachedShow.LatestSeasonNumber} to end on {cachedShow.LastAirDate ?? DateTime.MaxValue}");
+4 -1
View File
@@ -16,7 +16,6 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Transmission.API.RPC" Version="2.1.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -25,4 +24,8 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AnimeAnnouncer.Torrents\AnimeAnnouncer.Torrents.csproj" />
</ItemGroup>
</Project> </Project>
+32 -63
View File
@@ -1,15 +1,11 @@
using Microsoft.Extensions.Configuration; using AnimeAnnouncer.Torrents;
using System.Xml.Linq; using Microsoft.Extensions.Configuration;
using Transmission.API.RPC;
namespace MassTorrentAdd namespace MassTorrentAdd
{ {
internal class Program internal class Program
{ {
static String watchFolder, transmissionHost, transmissionUsername, transmissionPassword, transmissionDownloadFolder, destinationFolder; static async Task Main(string[] args)
static Transmission.API.RPC.Client transmissionClient;
static void Main(string[] args)
{ {
if(args.Length == 0) if(args.Length == 0)
{ {
@@ -17,60 +13,53 @@ namespace MassTorrentAdd
return; return;
} }
String url = args[0]; String url = args[0];
if (!url.Contains("rss"))
url = url + "&page=rss";
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) .SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true); .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build(); IConfigurationRoot configuration = builder.Build();
transmissionHost = configuration.GetValue<String>("transmissionURI"); String transmissionHost = configuration.GetValue<String>("transmissionURI")!;
transmissionUsername = configuration.GetValue<String>("transmissionUsername"); String? transmissionUsername = configuration.GetValue<String>("transmissionUsername");
transmissionPassword = configuration.GetValue<String>("transmissionPassword"); String? transmissionPassword = configuration.GetValue<String>("transmissionPassword");
destinationFolder = configuration.GetValue<String>("destinationFolder"); String destinationFolder = configuration.GetValue<String>("destinationFolder")!;
Console.WriteLine($"Using transmission server {transmissionHost}"); Console.WriteLine($"Using transmission server {transmissionHost}");
transmissionClient = new Transmission.API.RPC.Client(transmissionHost, null, transmissionUsername, transmissionPassword); TransmissionService transmission;
var sessionInformation = transmissionClient.GetSessionInformation(); try
if (sessionInformation == null || String.IsNullOrEmpty(sessionInformation.Version))
{ {
Console.WriteLine("An error occurred while receiving session information from the rpc server"); transmission = await TransmissionService.ConnectAsync(transmissionHost, transmissionUsername, transmissionPassword);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return; return;
} }
var nyaa = new NyaaRssReader();
HttpClient httpClient = new HttpClient(); List<NyaaRssItem> items;
var response = httpClient.GetStringAsync(url).Result; try
if(response == null)
{ {
Console.WriteLine("An error occurred while contacting Nyaa for a response"); items = await nyaa.ReadAsync(url);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while contacting Nyaa for a response: {ex.Message}");
return; return;
} }
XDocument doc = XDocument.Parse(response); if (items.Count == 0)
XNamespace nyaaNS = doc.Root.GetNamespaceOfPrefix("nyaa"); {
var items = from item in doc.Descendants("channel").Elements("item") Console.WriteLine("No items found in the feed");
select new return;
{ }
Title = item.Element("title").Value,
Published = item.Element("pubDate").Value,
Category = item.Element(nyaaNS + "category").Value,
CategoryID = item.Element(nyaaNS + "categoryId").Value,
Size = item.Element(nyaaNS + "size").Value,
Link = item.Element("link").Value,
Description = item.Element("description").Value,
PostID = item.Element("guid").Value,
};
Console.WriteLine("Downloading .."); Console.WriteLine("Downloading ..");
foreach ( var item in items ) foreach ( var item in items )
{ {
Console.WriteLine($"{item.Title}"); Console.WriteLine($"{item.Title}");
} }
String transmissionDirectoryName = items.First().Title.Trim(); String transmissionDirectoryName = TorrentDirectoryNamer.FromTitle(items.First().Title, destinationFolder);
transmissionDirectoryName = System.Text.RegularExpressions.Regex.Replace(transmissionDirectoryName, @"E\d{2,3}.*?(\d{3,4}p)", " $1"); Console.WriteLine($"{items.Count} item(s) to {transmissionDirectoryName}");
transmissionDirectoryName = System.Text.RegularExpressions.Regex.Replace(transmissionDirectoryName, @"\s\(.*?\)$", "");
transmissionDirectoryName = destinationFolder + (destinationFolder.EndsWith("/") ? String.Empty : "/") + transmissionDirectoryName.Replace(" ", ".");
Console.WriteLine($"{items.Count()} item(s) to {transmissionDirectoryName}");
Console.WriteLine("Continue?"); Console.WriteLine("Continue?");
if(Console.ReadKey().KeyChar != 'y') if(Console.ReadKey().KeyChar != 'y')
@@ -80,30 +69,10 @@ namespace MassTorrentAdd
} }
foreach (var item in items) foreach (var item in items)
{ {
var torrentData = httpClient.GetByteArrayAsync(item.Link).Result; var torrentData = await nyaa.DownloadTorrentAsync(item);
AddNewTorrentFileToServer(torrentData, transmissionDirectoryName); await transmission.AddNewTorrentFileToServerAsync(torrentData, transmissionDirectoryName);
} }
Console.WriteLine("Completed"); Console.WriteLine("Completed");
} }
private static void AddNewTorrentFileToServer(byte[] torrentFileData, String saveLocation)
{
Transmission.API.RPC.Entity.NewTorrent newTorrent = new()
{
DownloadDirectory = saveLocation,
Paused = true,
Metainfo = Convert.ToBase64String(torrentFileData)
};
var torrentInfo = transmissionClient.TorrentAdd(newTorrent);
var seedSettings = new Transmission.API.RPC.Arguments.TorrentSettings()
{
SeedRatioLimit = 1.0,
SeedRatioMode = 1,
IDs = [torrentInfo.ID]
};
transmissionClient.TorrentSet(seedSettings);
//transmissionClient.TorrentVerify(new object[] { torrentInfo.ID });
}
} }
} }