diff --git a/README.md b/README.md index 331387c..260e78d 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,14 @@ an old one next to it is left alone, you can delete it. The table with the players who failed the most mechanics comes from the encounter (trigger) id of the log. Encounters without a definition (strikes, fractals, new content) show the three mechanics the players triggered most. +#### Statistics of one boss over several weeks + +`rta parse boss [--cm] [--from yyyyMMdd] [--to yyyyMMdd] [--phases 70,40,10] [-k] [-r]` loads every log of one boss from your dps.report +uploads (the name only has to contain the text, e.g. `Cairn`; bosses dps.report does not know by name are listed as "DPS.Report", use their id then: `28106` or `0x6DCA`), builds `boss--stats.html` (a stand-alone statistics page: boss health left per try and day, days, where the wipes end, players, latest tries) and `boss-.html` (the timeline, open the +Boss tab) in your `outputPath` and prints tries, kills, fastest kill, best wipe and one line per day. The list of uploads and the logs are cached in the log folder of rta (`dpsreport-cache`), so a later +run only reads the new uploads and loads the new logs (`--refresh` reads the whole list again). +`--phases` takes the boss health (percent left) where a new phase starts; the statistics then draw the phases as bands in the chart and show how far every day got. + #### dps.report upload Please use the dps.report upload with care and do not spam it with all logs that you have. diff --git a/raidTimeline.App.Tests/BossSummaryTests.cs b/raidTimeline.App.Tests/BossSummaryTests.cs new file mode 100644 index 0000000..c927b9b --- /dev/null +++ b/raidTimeline.App.Tests/BossSummaryTests.cs @@ -0,0 +1,42 @@ +using raidTimeline.App.Services; +using raidTimeline.Models.Models; +using Xunit; + +namespace raidTimeline.App.Tests; + +public sealed class BossSummaryTests +{ + private static RaidModel Try(DateTime start, int seconds, bool killed, double hpLeft) => + new("log") + { + EncounterName = "Cairn", + OccurenceStart = start, + OccurenceEnd = start.AddSeconds(seconds), + Killed = killed, + HpLeft = { hpLeft } + }; + + [Fact] + public void Create_SummarizesTriesKillsAndDays() + { + var lines = BossSummary.Create(new[] + { + Try(new DateTime(2026, 11, 2, 20, 0, 0), 120, false, 55.5), + Try(new DateTime(2026, 11, 2, 20, 10, 0), 200, false, 12), + Try(new DateTime(2026, 11, 9, 20, 0, 0), 180, true, 0), + Try(new DateTime(2026, 11, 9, 20, 10, 0), 150, true, 0) + }); + + Assert.Contains("Cairn: 4 tries on 2 days, 2 kills (02.11.2026 - 09.11.2026)", lines); + Assert.Contains("Fastest kill: 2:30 on 09.11.2026", lines); + Assert.Contains("Best wipe: 12% boss health left on 02.11.2026, after 3:20", lines); + Assert.Contains(lines, l => l.StartsWith("02.11.2026") && l.EndsWith("12% left")); + Assert.Contains(lines, l => l.StartsWith("09.11.2026") && l.EndsWith("kill")); + } + + [Fact] + public void Create_NoLogs_SaysSo() + { + Assert.Equal(new[] { "No logs found." }, BossSummary.Create(Array.Empty())); + } +} diff --git a/raidTimeline.App/Commands/ParserCommands.cs b/raidTimeline.App/Commands/ParserCommands.cs index aad06e5..a9299ca 100644 --- a/raidTimeline.App/Commands/ParserCommands.cs +++ b/raidTimeline.App/Commands/ParserCommands.cs @@ -6,6 +6,25 @@ namespace raidTimeline.App.Commands; internal static class ParserCommands { + private static IReadOnlyList? ParsePhases(string? phases) + { + if (string.IsNullOrWhiteSpace(phases)) return null; + + var values = phases.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(p => double.TryParse(p.TrimEnd('%'), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out var v) && v is > 0 and < 100 ? v : double.NaN) + .ToList(); + if (values.Count == 0 || values.Any(double.IsNaN)) + { + throw new ArgumentException("--phases needs percentages between 0 and 100, e.g. 70,40,10."); + } + + return values.Distinct().OrderByDescending(v => v).ToList(); + } + + private static DateOnly? ParseDay(string? day) => + day == null ? null : DateOnly.ParseExact(day, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); + internal static CoconaApp RegisterParserCommands(this CoconaApp app) { app.AddSubCommand("parse", command => @@ -51,6 +70,37 @@ bool filter }) .WithDescription("Parses local log files with Elite Insights and keeps watching for new logs."); + command.AddCommand("boss", + ([FromService] IParserService parserService, + CoconaAppContext context, + [Argument(Description = "Part of the boss name (e.g. \"Cairn\") or the boss id (e.g. 28106 or 0x6DCA).")] + string boss, + [Option('c', Description = "Only logs of the challenge mode.")] + bool cm, + [Day][Option("from", + Description = "First day (format: yyyyMMdd). Default is all days.")] + string? from, + [Day][Option("to", + Description = "Last day (format: yyyyMMdd). Default is all days.")] + string? to, + [Option('r', Description = "Creates the timeline in reverse date order.")] + bool reverse, + [Option('k', Description = "Only uses the logs that killed the boss.")] + bool killOnly, + [Option("refresh", Description = "Reads the whole list of uploads from dps.report again instead of only the new ones.")] + bool refresh, + [Option("phases", Description = "Boss health in percent where a new phase starts, comma separated, e.g. 70,40,10. Shown in the statistics.")] + string? phases + ) => + { + parserService.ParseBossFromDpsReport(boss, cm, ParseDay(from), ParseDay(to), killOnly, + reverse, refresh, ParsePhases(phases), context.CancellationToken); + }) + .WithDescription( + "Loads all logs of one boss (e.g. every try at a challenge mode over weeks) from dps.report " + + "and creates a statistics page (boss--stats.html) and a timeline (boss-.html). " + + "Uploads and logs are kept locally, so later runs only load the new ones."); + command.AddCommand("report", ([FromService] IParserService parserService, CoconaAppContext context, diff --git a/raidTimeline.App/Services/BossSummary.cs b/raidTimeline.App/Services/BossSummary.cs new file mode 100644 index 0000000..4c7af1c --- /dev/null +++ b/raidTimeline.App/Services/BossSummary.cs @@ -0,0 +1,62 @@ +using System.Globalization; +using raidTimeline.Models.Models; + +namespace raidTimeline.App.Services; + +/// A short text summary of all tries at one boss, printed after the timeline was built. +internal static class BossSummary +{ + internal static IReadOnlyList Create(IReadOnlyCollection models) + { + var ci = CultureInfo.InvariantCulture; + var lines = new List(); + var tries = models.OrderBy(m => m.OccurenceStart).ToList(); + + if (tries.Count == 0) + { + lines.Add("No logs found."); + return lines; + } + + var kills = tries.Where(m => m.Killed).ToList(); + lines.Add($"{tries[0].EncounterName}: {tries.Count} tries on {tries.Select(m => m.OccurenceStart.Date).Distinct().Count()} days, " + + $"{kills.Count} kill{(kills.Count == 1 ? "" : "s")} ({tries[0].OccurenceStart:dd.MM.yyyy} - {tries[^1].OccurenceStart:dd.MM.yyyy})"); + + if (kills.Count > 0) + { + var fastest = kills.MinBy(Duration)!; + lines.Add($"Fastest kill: {Format(Duration(fastest))} on {fastest.OccurenceStart:dd.MM.yyyy}"); + } + + var wipes = tries.Where(m => !m.Killed && m.HpLeft.Count > 0).ToList(); + if (wipes.Count > 0) + { + var best = wipes.MinBy(HpLeft)!; + lines.Add($"Best wipe: {HpLeft(best).ToString("0.##", ci)}% boss health left on {best.OccurenceStart:dd.MM.yyyy}, " + + $"after {Format(Duration(best))}"); + } + + lines.Add(string.Empty); + lines.Add("Day Tries Kills Best try"); + foreach (var day in tries.GroupBy(m => m.OccurenceStart.Date).OrderBy(g => g.Key)) + { + var dayKills = day.Count(m => m.Killed); + var bestTry = day.Any(m => m.Killed) + ? "kill" + : day.Where(m => m.HpLeft.Count > 0).Select(HpLeft).DefaultIfEmpty(double.NaN).Min() is var hp && + !double.IsNaN(hp) + ? $"{hp.ToString("0.##", ci)}% left" + : "-"; + lines.Add($"{day.Key:dd.MM.yyyy} {day.Count(),5} {dayKills,5} {bestTry}"); + } + + return lines; + } + + /// Health left of the boss; for several targets the one with the most left decides. + private static double HpLeft(RaidModel model) => model.HpLeft.Max(); + + private static TimeSpan Duration(RaidModel model) => model.OccurenceEnd - model.OccurenceStart; + + private static string Format(TimeSpan time) => $"{(int)time.TotalMinutes}:{time.Seconds:00}"; +} diff --git a/raidTimeline.App/Services/Interfaces/IParserService.cs b/raidTimeline.App/Services/Interfaces/IParserService.cs index ccbf694..fa24e64 100644 --- a/raidTimeline.App/Services/Interfaces/IParserService.cs +++ b/raidTimeline.App/Services/Interfaces/IParserService.cs @@ -8,6 +8,8 @@ void ParseLogsFromDisk(string? day, bool reverse, bool killOnly, bool filter, IEncounterService encounterService, CancellationToken cancellationToken, bool htmlOnly = false); void ParseLogsFromDiskLive(bool reverse, bool killOnly, bool filter, CancellationToken cancellationToken); + void ParseBossFromDpsReport(string boss, bool challengeMode, DateOnly? from, DateOnly? to, bool killOnly, + bool reverse, bool refresh, IReadOnlyList? phases, CancellationToken cancellationToken); void ParseLogsFromDpsReport(string? day, bool reverse, bool killOnly, bool filter, CancellationToken cancellationToken); } \ No newline at end of file diff --git a/raidTimeline.App/Services/ParserService.cs b/raidTimeline.App/Services/ParserService.cs index eb655ba..6c7ba7b 100644 --- a/raidTimeline.App/Services/ParserService.cs +++ b/raidTimeline.App/Services/ParserService.cs @@ -2,6 +2,7 @@ using raidTimeline.App.Helpers; using raidTimeline.App.Services.Interfaces; using raidTimeline.Database.Interfaces; +using raidTimeline.Logic.DpsReport; using raidTimeline.Logic.Interfaces; using raidTimeline.Models.Models; @@ -13,10 +14,14 @@ internal class ParserService : IParserService private readonly ConfigurationHelper _configurationHelper; private readonly IEliteInsightsService _eliteInsightsService; + private readonly AppPaths _paths; + public ParserService(ITimelineCreator timelineCreator, ConfigurationHelper configurationHelper, - IEliteInsightsService eliteInsightsService) + IEliteInsightsService eliteInsightsService, + AppPaths paths) { + _paths = paths; _timelineCreator = timelineCreator; _configurationHelper = configurationHelper; _eliteInsightsService = eliteInsightsService; @@ -218,6 +223,65 @@ private IList ParseNewModels(IList models, bool reverse, b return models; } + public void ParseBossFromDpsReport(string boss, bool challengeMode, DateOnly? from, DateOnly? to, bool killOnly, + bool reverse, bool refresh, IReadOnlyList? phases, CancellationToken cancellationToken) + { + var cmText = challengeMode ? " CM" : ""; + Spinner.Start($"Loading the logs of {boss}{cmText} from dps.report", spinner => + { + if (string.IsNullOrWhiteSpace(_configurationHelper.Configuration.DpsReportToken)) + { + spinner.Fail("There is no dpsReportToken in your settings (see rta config edit)."); + return; + } + + IList models; + try + { + var filter = new DpsReportFilter(from, to, boss, challengeMode); + models = _timelineCreator.ParseFilesFromWeb(_configurationHelper.Configuration.DpsReportToken, filter, + Path.Combine(_paths.LogDirectory, "dpsreport-cache"), + (done, total) => spinner.Text = $"Loading the logs of {boss}{cmText} from dps.report: {done}/{total}", + cancellationToken, refresh); + } + catch (HttpRequestException e) + { + spinner.Fail($"dps.report could not be reached: {e.Message}"); + return; + } + + if (cancellationToken.IsCancellationRequested) + { + spinner.Info("Log parsing canceled."); + return; + } + + if (killOnly) models = models.Where(model => model.Killed).ToList(); + + if (models.Count == 0) + { + spinner.Warn($"No logs of {boss}{cmText} found."); + return; + } + + var slug = new string($"{boss}{cmText}".ToLowerInvariant() + .Select(c => char.IsLetterOrDigit(c) ? c : '-').ToArray()).Trim('-'); + var fileName = $"boss-{slug}.html"; + var statsFileName = $"boss-{slug}-stats.html"; + + spinner.Text = "Creating timeline and statistics"; + var outputPath = _configurationHelper.Configuration.OutputPath; + _timelineCreator.BuildTimelineFile(outputPath, fileName, models, reverse, cancellationToken); + _timelineCreator.BuildBossStatisticsFile(outputPath, statsFileName, models, phases, cancellationToken); + + spinner.Succeed($"{models.Count} logs"); + Console.WriteLine($"Statistics: {Path.Combine(outputPath, statsFileName)}"); + Console.WriteLine($"Timeline: {Path.Combine(outputPath, fileName)}"); + Console.WriteLine(); + Console.WriteLine(string.Join(Environment.NewLine, BossSummary.Create(models.ToList()))); + }); + } + public void ParseLogsFromDpsReport(string? day, bool reverse, bool killOnly, bool filter, CancellationToken cancellationToken) { diff --git a/raidTimeline.Logic.Tests/LogDownloaderTests.cs b/raidTimeline.Logic.Tests/LogDownloaderTests.cs index 84b69a2..bf158c7 100644 --- a/raidTimeline.Logic.Tests/LogDownloaderTests.cs +++ b/raidTimeline.Logic.Tests/LogDownloaderTests.cs @@ -110,6 +110,156 @@ await Assert.ThrowsAsync( () => Create(handler).DownloadLogsForOneDayAsync(Token, Day(LogTime), default)); } + private static object Upload(string id, DateTimeOffset time, string boss, bool isCm, DateTimeOffset? uploaded = null) => + new + { + id, + permalink = BaseUrl + id, + encounterTime = time.ToUnixTimeSeconds(), + uploadTime = (uploaded ?? time).ToUnixTimeSeconds(), + encounter = new { boss, isCm } + }; + + [Fact] + public async Task DownloadLogs_BossAndCmFilter_OnlyLoadsMatchingLogs() + { + var handler = new StubHandler() + .WithUploadList(Token, 1, 1, + Upload("cm", LogTime, "Cairn the Indomitable", true), + Upload("normal", LogTime, "Cairn the Indomitable", false), + Upload("other", LogTime, "Samarog", true)) + .WithLog("cm"); + + var models = await Create(handler).DownloadLogsAsync(Token, new DpsReportFilter(Boss: "cairn", ChallengeModeOnly: true), + null, null, default); + + Assert.Equal(new[] { BaseUrl + "cm" }, models.Select(m => m.LogUrl)); + Assert.DoesNotContain(handler.Requests, r => r.Contains("normal") || r.Contains("other")); + } + + [Fact] + public async Task DownloadLogs_DateRange_StopsAtPagesBeforeTheRange() + { + var from = DateOnly.FromDateTime(LogTime.AddDays(-7).LocalDateTime); + var handler = new StubHandler() + .WithUploadList(Token, 1, 3, Upload("new", LogTime, "Cairn", true)) + .WithUploadList(Token, 2, 3, Upload("old", LogTime.AddDays(-30), "Cairn", true)) + .WithLog("new"); + + var models = await Create(handler).DownloadLogsAsync(Token, new DpsReportFilter(From: from), null, null, default); + + Assert.Equal(new[] { BaseUrl + "new" }, models.Select(m => m.LogUrl)); + Assert.Equal(2, handler.Requests.Count(r => r.Contains("getUploads"))); + } + + [Fact] + public async Task DownloadLogs_LaterPagesReportZeroPages_StillReadsAllPages() + { + var handler = new StubHandler() + .WithUploadList(Token, 1, 3, Upload("p1", LogTime, "Cairn", true)) + .WithUploadList(Token, 2, 3, Upload("p2", LogTime, "Cairn", true)) + .WithUploadList(Token, 3, 3, Upload("p3", LogTime, "Cairn", true)) + .WithLog("p1").WithLog("p2").WithLog("p3"); + + var models = await Create(handler).DownloadLogsAsync(Token, new DpsReportFilter(), null, null, default); + + Assert.Equal(3, models.Count); + } + + [Theory] + [InlineData("28106")] + [InlineData("0x6DCA")] + public async Task DownloadLogs_BossById_MatchesUnnamedBosses(string boss) + { + var unnamed = new + { + id = "new", permalink = BaseUrl + "new", encounterTime = LogTime.ToUnixTimeSeconds(), + uploadTime = LogTime.ToUnixTimeSeconds(), encounter = new { boss = "DPS.Report", bossId = 28106, isCm = true } + }; + var handler = new StubHandler() + .WithUploadList(Token, 1, 1, unnamed, Upload("other", LogTime, "Cairn", true)) + .WithLog("new"); + + var models = await Create(handler).DownloadLogsAsync(Token, new DpsReportFilter(Boss: boss), null, null, default); + + Assert.Equal(new[] { BaseUrl + "new" }, models.Select(m => m.LogUrl)); + } + + [Fact] + public async Task DownloadLogs_UploadIndex_SecondRunOnlyReadsUntilTheFirstKnownUpload() + { + var folder = Path.Combine(Path.GetTempPath(), "rta-index-" + Guid.NewGuid().ToString("N")); + try + { + var first = new StubHandler() + .WithUploadList(Token, 1, 2, Upload("b", LogTime, "Cairn", true)) + .WithUploadList(Token, 2, 2, Upload("a", LogTime.AddHours(-1), "Cairn", true)) + .WithLog("a").WithLog("b"); + await Create(first).DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default); + + // page 2 does not exist anymore: reading it would fail, but the second run stops at the known "b" + var second = new StubHandler() + .WithUploadList(Token, 1, 2, Upload("c", LogTime.AddHours(1), "Cairn", true), Upload("b", LogTime, "Cairn", true)) + .WithLog("c"); + var models = await Create(second).DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default); + + Assert.Equal(new[] { BaseUrl + "a", BaseUrl + "b", BaseUrl + "c" }, models.Select(m => m.LogUrl)); + Assert.Single(second.Requests, r => r.Contains("getUploads")); + + // --refresh reads everything again (and fails here, as page 2 is gone) + await Assert.ThrowsAsync(() => + Create(second).DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default, refresh: true)); + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, true); + } + } + + [Fact] + public async Task DownloadLogs_UploadIndex_OfAnotherTokenIsIgnored() + { + var folder = Path.Combine(Path.GetTempPath(), "rta-index-" + Guid.NewGuid().ToString("N")); + try + { + var handler = new StubHandler() + .WithUploadList(Token, 1, 1, Upload("a", LogTime, "Cairn", true)).WithLog("a") + .WithUploadList("other", 1, 1, Upload("x", LogTime, "Cairn", true)).WithLog("x"); + await Create(handler).DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default); + + var models = await Create(handler).DownloadLogsAsync("other", new DpsReportFilter(), folder, null, default); + + Assert.Equal(new[] { BaseUrl + "x" }, models.Select(m => m.LogUrl)); + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, true); + } + } + + [Fact] + public async Task DownloadLogs_Cache_LoadsEachLogOnlyOnce() + { + var folder = Path.Combine(Path.GetTempPath(), "rta-cache-" + Guid.NewGuid().ToString("N")); + try + { + var handler = new StubHandler() + .WithUploadList(Token, 1, 1, Upload("one", LogTime, "Vale Guardian", false)) + .WithLog("one"); + var downloader = Create(handler); + + await downloader.DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default); + var models = await downloader.DownloadLogsAsync(Token, new DpsReportFilter(), folder, null, default); + + Assert.Single(models); + Assert.Equal(1, handler.Requests.Count(r => r.Contains("getJson"))); + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, true); + } + } + private static LogDownloader Create(StubHandler handler) => new(new HttpClient(handler)); /// Stands in for dps.report so tests never touch the network. Unknown urls return 404. @@ -135,6 +285,13 @@ internal StubHandler WithUploads(string token, int page, int pages, return this; } + internal StubHandler WithUploadList(string token, int page, int pages, params object[] uploads) + { + _responses[$"{BaseUrl}getUploads?userToken={Uri.EscapeDataString(token)}&page={page}"] = + JsonConvert.SerializeObject(new { pages = page == 1 ? pages : 0, uploads }); // like dps.report: only page 1 knows the count + return this; + } + internal StubHandler WithLog(string id) => WithJson(id, File.ReadAllText(TestFiles.ValeGuardianLog)); internal StubHandler WithJson(string id, string json) diff --git a/raidTimeline.Logic/DpsReport/DpsReportFilter.cs b/raidTimeline.Logic/DpsReport/DpsReportFilter.cs new file mode 100644 index 0000000..de241a0 --- /dev/null +++ b/raidTimeline.Logic/DpsReport/DpsReportFilter.cs @@ -0,0 +1,59 @@ +#nullable enable +using System; +using Newtonsoft.Json.Linq; + +namespace raidTimeline.Logic.DpsReport; + +/// Selects the logs of dps.report that are downloaded, using only the metadata of the upload list. +/// First day (local time, inclusive), null for no limit. +/// Last day (local time, inclusive), null for no limit. +/// Part of the boss name (case insensitive) or the boss id, null for all bosses. +/// Only logs of challenge mode encounters. +public sealed record DpsReportFilter(DateOnly? From = null, DateOnly? To = null, string? Boss = null, + bool ChallengeModeOnly = false) +{ + internal bool Matches(JToken upload) + { + var encounter = upload["encounter"]; + + if (ChallengeModeOnly && encounter?["isCm"]?.Type != JTokenType.Boolean) return false; + if (ChallengeModeOnly && !encounter!["isCm"]!.Value()) return false; + + if (!string.IsNullOrWhiteSpace(Boss)) + { + var wanted = Boss.Trim(); + if (TryParseBossId(wanted, out var bossId)) + { + // dps.report does not know the name of new bosses ("DPS.Report"), only the id + if (encounter?["bossId"]?.Value() != bossId) return false; + } + else + { + var name = encounter?["boss"]?.Value(); + if (name == null || !name.Contains(wanted, StringComparison.OrdinalIgnoreCase)) return false; + } + } + + var time = upload["encounterTime"]?.Value(); + if (time == null) return From == null && To == null; + + var day = DateOnly.FromDateTime(DateTimeOffset.FromUnixTimeSeconds(time.Value).LocalDateTime); + return (From == null || day >= From) && (To == null || day <= To); + } + + /// A boss can be given by id, decimal (28106) or hexadecimal as in the arcdps.ini (0x6DCA). + private static bool TryParseBossId(string text, out int id) => + text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? int.TryParse(text.AsSpan(2), System.Globalization.NumberStyles.HexNumber, null, out id) + : int.TryParse(text, out id); + + /// The upload list is sorted by upload time, newest first, and a log is never uploaded before it was + /// played: when an upload is older than , so is everything on the later pages. + internal bool IsBeforeRange(JToken upload) + { + var time = upload["uploadTime"]?.Value(); + if (From == null || time == null) return false; + + return DateOnly.FromDateTime(DateTimeOffset.FromUnixTimeSeconds(time.Value).LocalDateTime) < From; + } +} diff --git a/raidTimeline.Logic/DpsReport/LogDownloader.cs b/raidTimeline.Logic/DpsReport/LogDownloader.cs index 6a4f22a..1f07533 100644 --- a/raidTimeline.Logic/DpsReport/LogDownloader.cs +++ b/raidTimeline.Logic/DpsReport/LogDownloader.cs @@ -1,6 +1,9 @@ #nullable enable using System; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -63,6 +66,183 @@ internal async Task> DownloadLogsForOneDayAsync(string token, st return models; } + /// + /// Loads all logs of a user that match the filter (e.g. every try at one boss over several weeks). + /// Only the upload list is used to select the logs; the json of a log is downloaded once and kept in + /// (when given), so running it again only loads the new logs. + /// + /// Called with (done, total) while the logs are loaded. + internal async Task> DownloadLogsAsync(string token, DpsReportFilter filter, + string? cacheFolder, Action? progress, CancellationToken cancellationToken, bool refresh = false) + { + var uploads = await FetchUploadsAsync(token, filter, cacheFolder, refresh, cancellationToken); + var models = new List(); + + if (cacheFolder != null) Directory.CreateDirectory(cacheFolder); + + for (var i = 0; i < uploads.Count && !cancellationToken.IsCancellationRequested; i++) + { + progress?.Invoke(i, uploads.Count); + var permalink = uploads[i]["permalink"]!.Value()!; + var cacheFile = cacheFolder == null ? null : Path.Combine(cacheFolder, CacheName(uploads[i], permalink)); + + string json; + if (cacheFile != null && File.Exists(cacheFile)) + { + json = await File.ReadAllTextAsync(cacheFile, cancellationToken); + } + else + { + _logger?.LogTrace("Loading log {Permalink}", permalink); + json = await GetStringAsync($"{BaseUrl}getJson?permalink={Uri.EscapeDataString(permalink)}", + cancellationToken); + if (cacheFile != null) await File.WriteAllTextAsync(cacheFile, json, cancellationToken); + } + + var model = EiJsonParser.ParseJson(json, permalink, permalink, _logger); + if (model == null) + { + _logger?.LogWarning("Log {Permalink} could not be parsed", permalink); + continue; + } + + models.Add(model); + } + + progress?.Invoke(uploads.Count, uploads.Count); + return models; + } + + private static string CacheName(JToken upload, string permalink) + { + var name = upload["id"]?.Value() ?? permalink.Substring(permalink.LastIndexOf('/') + 1); + foreach (var c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_'); + return name + ".json"; + } + + private const string IndexFileName = "uploads-index.json"; + + /// + /// Lists the uploads that match the filter. With a cache folder the (slimmed down) list of all uploads is kept + /// there; the next run reads pages only until it meets an upload it already knows (the list is newest first). + /// + private async Task> FetchUploadsAsync(string token, DpsReportFilter filter, string? cacheFolder, + bool refresh, CancellationToken cancellationToken) + { + var useIndex = cacheFolder != null; + var known = useIndex && !refresh ? LoadIndex(cacheFolder!, token) : new List(); + var knownIds = known.Select(IdOf).ToHashSet(); + + var fresh = new List(); + var page = 1; + var maxPage = 1; + var reachedKnown = false; + + while (page <= maxPage && !reachedKnown && !cancellationToken.IsCancellationRequested) + { + var url = $"{BaseUrl}getUploads?userToken={Uri.EscapeDataString(token)}&page={page++}"; + var json = JObject.Parse(await GetStringAsync(url, cancellationToken)); + // dps.report only tells the number of pages on the first page, later pages say 0 + maxPage = Math.Max(maxPage, json["pages"]?.Value() ?? 0); + + var uploads = (json["uploads"] ?? new JArray()).ToList(); + foreach (var upload in uploads) + { + if (knownIds.Contains(IdOf(upload))) reachedKnown = true; + else fresh.Add(useIndex ? Slim(upload) : upload); + } + + // Without an index nothing needs to be read that is older than the range. With one the list has to be + // complete, otherwise the next run would think everything older is known. + if (!useIndex && uploads.Count > 0 && uploads.All(filter.IsBeforeRange)) break; + } + + if (cancellationToken.IsCancellationRequested) return new List(); + + var all = fresh.Concat(known).ToList(); + if (useIndex && fresh.Count > 0) SaveIndex(cacheFolder!, token, all); + + // oldest first, the timeline sorts by time anyway + return all.Where(filter.Matches).OrderBy(u => u["encounterTime"]?.Value() ?? 0).ToList(); + } + + private static string IdOf(JToken upload) => + upload["id"]?.Value() ?? upload["permalink"]?.Value() ?? string.Empty; + + /// Only what the filter and the summary need, the full upload list is several megabytes. + private static JToken Slim(JToken upload) => new JObject + { + ["id"] = upload["id"], + ["permalink"] = upload["permalink"], + ["encounterTime"] = upload["encounterTime"], + ["uploadTime"] = upload["uploadTime"], + ["encounter"] = new JObject + { + ["boss"] = upload["encounter"]?["boss"], + ["bossId"] = upload["encounter"]?["bossId"], + ["isCm"] = upload["encounter"]?["isCm"], + ["success"] = upload["encounter"]?["success"] + } + }; + + /// The index belongs to one token; the token itself is not written, only a hash of it. + private static string TokenHash(string token) => + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(token))); + + private List LoadIndex(string cacheFolder, string token) + { + var path = Path.Combine(cacheFolder, IndexFileName); + try + { + if (!File.Exists(path)) return new List(); + + var index = JObject.Parse(File.ReadAllText(path)); + return index["token"]?.Value() == TokenHash(token) + ? (index["uploads"] ?? new JArray()).ToList() + : new List(); + } + catch (Exception e) when (e is IOException or Newtonsoft.Json.JsonException) + { + _logger?.LogWarning("The upload index could not be read, reading all uploads again: {Message}", e.Message); + return new List(); + } + } + + private void SaveIndex(string cacheFolder, string token, List uploads) + { + try + { + Directory.CreateDirectory(cacheFolder); + var path = Path.Combine(cacheFolder, IndexFileName); + var temporary = path + ".tmp"; + File.WriteAllText(temporary, + new JObject { ["token"] = TokenHash(token), ["uploads"] = new JArray(uploads) }.ToString(Newtonsoft.Json.Formatting.None)); + File.Move(temporary, path, overwrite: true); + } + catch (IOException e) + { + _logger?.LogWarning("The upload index could not be saved: {Message}", e.Message); + } + } + + /// dps.report limits the requests; when it says so, wait and try again. + private async Task GetStringAsync(string url, CancellationToken cancellationToken) + { + for (var attempt = 1;; attempt++) + { + using var response = await _httpClient.GetAsync(url, cancellationToken); + if (response.StatusCode != HttpStatusCode.TooManyRequests || attempt >= 6) + { + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStringAsync(cancellationToken); + } + + var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(5 * attempt); + _logger?.LogWarning("dps.report asked to slow down, waiting {Seconds}s", wait.TotalSeconds); + await Task.Delay(wait, cancellationToken); + } + } + private async Task> FetchPermalinksForOneDayAsync(string day, string token, CancellationToken cancellationToken) { @@ -78,7 +258,8 @@ private async Task> FetchPermalinksForOneDayAsync(string day, strin var content = await _httpClient.GetStringAsync(url, cancellationToken); var json = JObject.Parse(content); - maxPage = json["pages"]?.Value() ?? 0; + // dps.report only tells the number of pages on the first page, later pages say 0 + maxPage = Math.Max(maxPage, json["pages"]?.Value() ?? 0); foreach (var upload in json["uploads"] ?? new JArray()) { diff --git a/raidTimeline.Logic/Interfaces/ITimelineCreator.cs b/raidTimeline.Logic/Interfaces/ITimelineCreator.cs index 7aa56d5..8e96b9a 100644 --- a/raidTimeline.Logic/Interfaces/ITimelineCreator.cs +++ b/raidTimeline.Logic/Interfaces/ITimelineCreator.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +#nullable enable +using System; +using raidTimeline.Logic.DpsReport; +using System.Collections.Generic; using System.Threading; using raidTimeline.Models.Models; @@ -21,8 +24,21 @@ public interface ITimelineCreator /// The day that shall be parsed. /// Cancellation token for stopping the parsing. /// List of parsed raid models. - IList ParseFileFromWeb(string token, string day, + IList ParseFileFromWeb(string token, string day, CancellationToken cancellationToken = new()); + + /// + /// Parse the Elite Insights logs from dps.report that match a filter (boss, challenge mode, time range). + /// + /// The dps.report token for the user. + /// Selects the logs. + /// Folder where the downloaded json files are kept, so they are only loaded once. + /// Null to not keep them. + /// Called with (done, total) while the logs are loaded. + /// Cancellation token for stopping the parsing. + /// List of parsed raid models, oldest first. + IList ParseFilesFromWeb(string token, DpsReportFilter filter, string? cacheFolder, + Action? progress = null, CancellationToken cancellationToken = new(), bool refresh = false); /// /// Parse all Elite Insights json files in a defined path, but ignores already parsed ones. @@ -46,5 +62,17 @@ IList ParseFilesFromDiskWhileWatching(string path, string outputFileN /// Cancellation token for stopping the parsing. void BuildTimelineFile(string path, string outputFileName, IEnumerable models, bool reverse = false, CancellationToken cancellationToken = new()); + + /// + /// Creates a stand-alone html page with the statistics of the tries at one boss. + /// + /// The path where the file should be saved. + /// The filename which shall be used. + /// The tries at one boss. + /// Boss health (percent left) where a new phase starts, e.g. 70, 40, 10. Null for none. + /// Cancellation token. + void BuildBossStatisticsFile(string path, string outputFileName, IEnumerable models, + IReadOnlyList? phases = null, + CancellationToken cancellationToken = new()); } } \ No newline at end of file diff --git a/raidTimeline.Logic/TimelineCreator.cs b/raidTimeline.Logic/TimelineCreator.cs index f8c80f8..6480000 100644 --- a/raidTimeline.Logic/TimelineCreator.cs +++ b/raidTimeline.Logic/TimelineCreator.cs @@ -111,6 +111,22 @@ public void BuildTimelineFile(string path, string outputFileName, IEnumerable>> Done"); } +#nullable enable + /// + /// Creates a stand-alone html page with the statistics of the tries at one boss (progress per try and day, + /// wipes, players). Meant for the logs of a single encounter over several days. + /// + public void BuildBossStatisticsFile(string path, string outputFileName, IEnumerable models, + IReadOnlyList? phases = null, + CancellationToken cancellationToken = new()) + { + if (cancellationToken.IsCancellationRequested) return; + + var json = TimelineDataBuilder.Build(models.ToList(), false, phases); + WriteHtmlFile(Path.Combine(path, outputFileName), json, "bossstats.html"); + } +#nullable restore + /// /// Parse Elite Insights logs of one day from dps.report. /// @@ -125,10 +141,21 @@ public IList ParseFileFromWeb(string token, string day, return downloader.DownloadLogsForOneDay(token, day, cancellationToken); } - private static void WriteHtmlFile(string htmlFilePath, string json) +#nullable enable + public IList ParseFilesFromWeb(string token, DpsReportFilter filter, string? cacheFolder, + Action? progress = null, CancellationToken cancellationToken = new(), bool refresh = false) + { + var downloader = new LogDownloader(); + return downloader.DownloadLogsAsync(token, filter, cacheFolder, progress, cancellationToken, refresh) + .GetAwaiter().GetResult(); + } + +#nullable restore + + private static void WriteHtmlFile(string htmlFilePath, string json, string templateName = "template.html") { var assembly = Assembly.GetExecutingAssembly(); - var resourceName = assembly.GetManifestResourceNames().Single(name => name.EndsWith("template.html")); + var resourceName = assembly.GetManifestResourceNames().Single(name => name.EndsWith(templateName)); string html; using (var stream = assembly.GetManifestResourceStream(resourceName)!) diff --git a/raidTimeline.Logic/TimelineDataBuilder.cs b/raidTimeline.Logic/TimelineDataBuilder.cs index c3127b0..f90835e 100644 --- a/raidTimeline.Logic/TimelineDataBuilder.cs +++ b/raidTimeline.Logic/TimelineDataBuilder.cs @@ -1,7 +1,9 @@ +#nullable enable using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Json; +using System.Text.Json.Serialization; using raidTimeline.Models.Models; namespace raidTimeline.Logic @@ -23,10 +25,10 @@ internal static class TimelineDataBuilder /// The encounters, in any order. /// Whether the page lists the newest raid day first. - internal static string Build(IEnumerable models, bool newestFirst) + internal static string Build(IEnumerable models, bool newestFirst, IReadOnlyList? phases = null) { var logs = models.OrderBy(model => model.OccurenceStart).Select(ToLog).ToList(); - return JsonSerializer.Serialize(new TimelineData(newestFirst, logs), Options); + return JsonSerializer.Serialize(new TimelineData(newestFirst, logs, phases), Options); } private static LogData ToLog(RaidModel model) => new( @@ -57,7 +59,8 @@ internal static string Build(IEnumerable models, bool newestFirst) player.CombinedMechanics, player.Buffs.Select(buff => new BuffData(buff.Id, buff.Name, buff.Icon, buff.Stacking, buff.Value, buff.Stacks)).ToList()); - private sealed record TimelineData(bool NewestFirst, IReadOnlyList Logs); + private sealed record TimelineData(bool NewestFirst, IReadOnlyList Logs, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? Phases); private sealed record LogData( string Name, string Icon, int Id, bool Killed, string Start, string End, string Url, diff --git a/raidTimeline.Logic/bossstats.html b/raidTimeline.Logic/bossstats.html new file mode 100644 index 0000000..f527860 --- /dev/null +++ b/raidTimeline.Logic/bossstats.html @@ -0,0 +1,236 @@ + + + + +Boss statistics + + + + +
+ + + + diff --git a/raidTimeline.Logic/raidTimeline.Logic.csproj b/raidTimeline.Logic/raidTimeline.Logic.csproj index 1610b82..c3791ed 100644 --- a/raidTimeline.Logic/raidTimeline.Logic.csproj +++ b/raidTimeline.Logic/raidTimeline.Logic.csproj @@ -16,6 +16,7 @@ + Never