using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Threading; namespace UltraParadise.Linux { internal sealed class NexusMod { public int Id, Endorsements; public long Downloads; public string Name, Summary, Thumb; public bool Adult, Self; public Bitmap Image; } internal static class NexusMods { public const string Member = "casualexpie"; private const string MemberId = "94954933"; private const string GameDomain = "scavprototype"; public const string ProfileUrl = "https://www.nexusmods.com/users/" + MemberId + "?tab=user+files"; public const string BananaUrl = "https://gamebanana.com/members/6222538"; private const string Api = "https://api.nexusmods.com/v2/graphql"; private static string CacheFile => Path.Combine(Dirs.Cache, "nexus.json"); private static string ThumbDir => Path.Combine(Dirs.Cache, "thumbs"); public static string ModUrl(int id) => "https://www.nexusmods.com/" + GameDomain + "/mods/" + id; public static List Load(out DateTime when) { when = DateTime.MinValue; try { if (!File.Exists(CacheFile)) return null; when = File.GetLastWriteTimeUtc(CacheFile); return Parse(File.ReadAllText(CacheFile)); } catch (Exception) { return null; } } public static async Task> Fetch() { string q = "{ mods(filter:{ uploaderId:{ value:\"" + MemberId + "\" } }, sort:{ downloads:{ direction: DESC } }, count: 40) { nodes { modId name summary endorsements downloads thumbnailUrl status adultContent game { domainName } } } }"; string body = JsonSerializer.Serialize(new Dictionary { ["query"] = q }); using HttpRequestMessage req = new(HttpMethod.Post, Api) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; using HttpResponseMessage res = await Http.Client.SendAsync(req); res.EnsureSuccessStatusCode(); string json = await res.Content.ReadAsStringAsync(); List list = Parse(json); if (list == null) return null; try { Private.Dir(Dirs.Cache); File.WriteAllText(CacheFile, json); } catch (Exception) { } return list; } private static List Parse(string json) { using JsonDocument doc = JsonDocument.Parse(json); if (!doc.RootElement.TryGetProperty("data", out JsonElement data) || !data.TryGetProperty("mods", out JsonElement mods) || !mods.TryGetProperty("nodes", out JsonElement nodes) || nodes.ValueKind != JsonValueKind.Array) return null; List list = new(); foreach (JsonElement n in nodes.EnumerateArray()) { string S(JsonElement e, string k) => e.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; long N(string k) => n.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x) ? x : 0; if (S(n, "status") != "published") continue; if (!n.TryGetProperty("game", out JsonElement g) || S(g, "domainName") != GameDomain) continue; NexusMod m = new() { Id = (int)N("modId"), Name = S(n, "name") ?? "" }; if (m.Id <= 0 || m.Name.Length == 0) continue; m.Self = m.Id == Nexus.TrainerModId; m.Adult = n.TryGetProperty("adultContent", out JsonElement a) && a.ValueKind == JsonValueKind.True; m.Summary = (S(n, "summary") ?? "").Replace("\r", " ").Replace("\n", " "); m.Downloads = N("downloads"); m.Endorsements = (int)N("endorsements"); m.Thumb = m.Adult ? null : S(n, "thumbnailUrl"); list.Add(m); } return list; } public static async Task Thumb(string url) { if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out Uri u) || u.Scheme != "https" || !(u.Host.EndsWith(".nexusmods.com", StringComparison.OrdinalIgnoreCase) || u.Host.EndsWith(".thunderstore.io", StringComparison.OrdinalIgnoreCase))) return null; string file = Path.Combine(ThumbDir, Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(url))).ToLowerInvariant() + ".img"); byte[] bytes = null; try { if (File.Exists(file)) bytes = await File.ReadAllBytesAsync(file); } catch (Exception) { } if (bytes == null) { try { using HttpResponseMessage res = await Http.Client.GetAsync(u, HttpCompletionOption.ResponseHeadersRead); if (!res.IsSuccessStatusCode || res.Content.Headers.ContentLength > 4 * 1024 * 1024) return null; bytes = await res.Content.ReadAsByteArrayAsync(); if (bytes.Length > 4 * 1024 * 1024) return null; Private.Dir(Dirs.Cache); Private.Dir(ThumbDir); await File.WriteAllBytesAsync(file, bytes); } catch (Exception) { return null; } } try { using MemoryStream ms = new(bytes); return Bitmap.DecodeToWidth(ms, 240); } catch (Exception) { return null; } } public static string Big(long n) { if (n >= 1000000) return (n / 1000000.0).ToString("0.#", CultureInfo.InvariantCulture) + "M"; if (n >= 10000) return (n / 1000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; return n.ToString("#,0", CultureInfo.InvariantCulture); } } internal sealed partial class MainWindow { private readonly StackPanel aboutStats = new() { Orientation = Orientation.Horizontal, Spacing = 28 }; private readonly TextBlock aboutStatus = T("Loading my mods from Nexus...", 12, Ui.B(Ui.Dim), false, true); private readonly WrapPanel aboutGrid = new(); private readonly WrapPanel aboutTsGrid = new(); private readonly Border aboutRec = new() { Margin = new Thickness(0, 0, 12, 14) }; private const int RecommendedId = 885; private const string RecommendedTs = "SaveAnywhere"; private List aboutMods; private static TextBlock SubHead(string text) => T(string.Join(" ", text.ToCharArray()), 11, Ui.B(Ui.Dim), true); private Border ModCard(string name, string summary, string meta, bool adult, Bitmap image, string thumbUrl, Action keep, string url) { Grid card = new() { ColumnDefinitions = new ColumnDefinitions("104,*"), Width = 330, Height = 96 }; Border thumb = new() { Background = Ui.B(Ui.Thumb), ClipToBounds = true }; Image img = new() { Stretch = Stretch.UniformToFill }; if (adult) thumb.Child = new TextBlock { Text = "18+", FontSize = 18, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Bad), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; else thumb.Child = img; card.Children.Add(thumb); StackPanel txt = new() { Margin = new Thickness(10, 0, 0, 0), Spacing = 2 }; TextBlock nm = T(name, 13, Ui.B(Ui.Text), true); nm.TextTrimming = TextTrimming.CharacterEllipsis; txt.Children.Add(nm); TextBlock sum = T(summary ?? "", 12, Ui.B(Ui.Soft), false, true); sum.MaxLines = 2; sum.TextTrimming = TextTrimming.WordEllipsis; txt.Children.Add(sum); txt.Children.Add(T(meta, 12, Ui.B(Ui.Orange))); Grid.SetColumn(txt, 1); card.Children.Add(txt); Border box = new() { Child = card, Padding = new Thickness(8), Margin = new Thickness(0, 0, 12, 12), Background = Ui.B(Ui.Panel), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), }; box.PointerEntered += (_, _) => box.BorderBrush = Ui.B(Ui.Orange); box.PointerExited += (_, _) => box.BorderBrush = Ui.B(Ui.Line); box.PointerPressed += (_, e) => { if (e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) Game.Open(url); }; ToolTip.SetTip(box, name); if (image != null) img.Source = image; else if (thumbUrl != null && !adult) { _ = Task.Run(async () => { Bitmap b = await NexusMods.Thumb(thumbUrl); if (b != null) Dispatcher.UIThread.Post(() => { keep(b); img.Source = b; }); }); } return box; } private void ShowRecommended() { NexusMod n = aboutMods?.FirstOrDefault(m => m.Id == RecommendedId); TsPackage tp = null; tsMods?.TryGetValue(RecommendedTs, out tp); Grid card = new() { ColumnDefinitions = new ColumnDefinitions("170,*"), Height = 96 }; Border thumb = new() { Background = Ui.B(Ui.Thumb), ClipToBounds = true }; Image img = new() { Stretch = Stretch.UniformToFill, Source = n?.Image ?? tp?.Image }; thumb.Child = img; card.Children.Add(thumb); StackPanel txt = new() { Margin = new Thickness(12, 0, 0, 0), Spacing = 3 }; txt.Children.Add(T("Save Anywhere", 16, Ui.B(Ui.Bright), true)); TextBlock sum = T("Save your run anywhere, not just at the usual spots. Cloud saves, auto-save and save slots, plus share codes to send a run to a friend.", 12, Ui.B(Ui.Soft), false, true); sum.MaxLines = 2; sum.TextTrimming = TextTrimming.WordEllipsis; txt.Children.Add(sum); List meta = new(); if (n != null) meta.Add(NexusMods.Big(n.Downloads) + " on Nexus"); if (tp != null) meta.Add("v" + tp.Version + " on Thunderstore"); StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 6 }; row.Children.Add(T(string.Join(" · ", meta), 12, Ui.B(Ui.Orange))); Button nb = Btn("Nexus Mods", () => Game.Open(NexusMods.ModUrl(RecommendedId) + "?tab=files")); Button tb = Btn("Thunderstore", () => OpenTs(tp?.Url ?? Thunderstore.PageUrl(RecommendedTs))); nb.Margin = new Thickness(10, 0, 0, 0); row.Children.Add(nb); row.Children.Add(tb); txt.Children.Add(row); Grid.SetColumn(txt, 1); card.Children.Add(txt); aboutRec.Child = new Border { Child = card, Padding = new Thickness(10), Background = Ui.B(Ui.Panel), BorderBrush = Ui.B(Ui.Orange), BorderThickness = new Thickness(4, 1, 1, 1), }; if (img.Source == null) { string u = n?.Thumb ?? tp?.Icon; if (u != null) _ = Task.Run(async () => { Bitmap b = await NexusMods.Thumb(u); if (b != null) Dispatcher.UIThread.Post(() => img.Source = b); }); } } private void ShowTsAbout() { aboutTsGrid.Children.Clear(); if (tsMods != null) foreach (TsPackage p in tsMods.Values.Where(x => !string.Equals(x.Name, RecommendedTs, StringComparison.OrdinalIgnoreCase)).OrderByDescending(x => x.Downloads).ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase)) { TsPackage pp = p; string name = Mods.All.FirstOrDefault(k => string.Equals(k.Ts, p.Name, StringComparison.OrdinalIgnoreCase))?.Name ?? System.Text.RegularExpressions.Regex.Replace(p.Name, "(?<=[a-z])(?=[A-Z])", " "); aboutTsGrid.Children.Add(ModCard(name, p.Description, p.Downloads.ToString("#,0", CultureInfo.InvariantCulture) + " downloads · v" + p.Version, false, p.Image, p.Icon, b => pp.Image = b, p.Url)); } if (aboutTsGrid.Children.Count == 0) aboutTsGrid.Children.Add(T(tsMods == null ? "Loading..." : "Nothing to show yet.", 13, Ui.B(Ui.Dim))); ShowRecommended(); } private bool aboutLoading; private DateTime aboutLoaded = DateTime.MinValue; private Control AboutPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("300,*") }; StackPanel left = new() { Margin = new Thickness(0, 0, 22, 0), Spacing = 14 }; Border me = Section("ABOUT ME", out StackPanel mb); StackPanel who = new() { Orientation = Orientation.Horizontal, Spacing = 10 }; Bitmap tile = Program.Image("tile.png"); if (tile != null) { Image ti = new() { Source = tile, Width = 44, Height = 44 }; RenderOptions.SetBitmapInterpolationMode(ti, BitmapInterpolationMode.None); who.Children.Add(ti); } StackPanel nm = new() { VerticalAlignment = VerticalAlignment.Center }; nm.Children.Add(T(NexusMods.Member, 22, Ui.B(Ui.Bright), true)); nm.Children.Add(T("Modder for Casualties: Unknown", 12, Ui.B(Ui.Orange))); who.Children.Add(nm); mb.Children.Add(who); mb.Children.Add(T("Hi! I make mods for Casualties: Unknown, from cheats and quality-of-life fixes to a few silly ones. Thanks for using the trainer.\n\nIf you like it, an endorsement on Nexus really helps.", 13, Ui.B(Ui.Soft), false, true)); mb.Children.Add(aboutStats); WrapPanel lk = new(); Button nxb = Btn("All my mods on Nexus", () => Game.Open(NexusMods.ProfileUrl)); nxb.Margin = new Thickness(0, 0, 6, 6); lk.Children.Add(nxb); Button gbb = Btn("My GameBanana page", () => Game.Open(NexusMods.BananaUrl)); gbb.Margin = new Thickness(0, 0, 6, 6); lk.Children.Add(gbb); Button tsb = Btn("My Thunderstore page", () => Game.Open(Thunderstore.TeamUrl)); tsb.Margin = new Thickness(0, 0, 6, 6); lk.Children.Add(tsb); mb.Children.Add(lk); mb.Children.Add(aboutStatus); left.Children.Add(me); left.Children.Add(T("Only download this trainer from Nexus Mods or GameBanana (uploaded by casualexpie).\n\nOpen source: opensource.smellypawz.com\nCopyright (c) casualexpie.\nDon't reupload, sell or reuse it.", 12, Ui.B(Ui.Dim), false, true)); g.Children.Add(left); Border others = Section("CHECK OUT MY OTHER MODS", out StackPanel ob); ob.Children.Add(SubHead("★ RECOMMENDED")); ob.Children.Add(aboutRec); ob.Children.Add(SubHead("ON NEXUS MODS")); ob.Children.Add(aboutGrid); ob.Children.Add(SubHead("ON THUNDERSTORE")); ob.Children.Add(aboutTsGrid); Grid.SetColumn(others, 1); g.Children.Add(others); List cached = NexusMods.Load(out aboutLoaded); if (cached != null) ShowAbout(cached); tsMods ??= Thunderstore.Load(out _); ShowTsAbout(); return Scroll(g); } private async Task LoadAbout() { if (aboutLoading || (aboutMods != null && (DateTime.UtcNow - aboutLoaded).TotalHours < 6)) return; aboutLoading = true; try { List list = await NexusMods.Fetch(); if (list != null) { aboutLoaded = DateTime.UtcNow; ShowAbout(list); aboutStatus.Text = "Updated from Nexus just now."; } } catch (Exception) { aboutStatus.Text = aboutMods != null ? "Couldn't reach Nexus, so this is from last time." : "Couldn't reach Nexus Mods. Check your connection."; } finally { aboutLoading = false; } } private void ShowAbout(List list) { aboutMods = list; aboutStatus.Text = "From Nexus, " + aboutLoaded.ToLocalTime().ToString("d MMM HH:mm", CultureInfo.InvariantCulture) + "."; aboutStats.Children.Clear(); foreach (var (num, label) in new[] { (list.Count.ToString(CultureInfo.InvariantCulture), "mods"), (NexusMods.Big(list.Sum(m => m.Downloads)), "downloads"), (NexusMods.Big(list.Sum(m => (long)m.Endorsements)), "endorsements") }) { StackPanel s = new(); s.Children.Add(T(num, 18, Ui.B(Ui.Text), true)); s.Children.Add(T(label, 12, Ui.B(Ui.Dim))); aboutStats.Children.Add(s); } aboutGrid.Children.Clear(); foreach (NexusMod m in list.Where(x => !x.Self && x.Id != RecommendedId)) { NexusMod mm = m; aboutGrid.Children.Add(ModCard(m.Name, m.Summary, NexusMods.Big(m.Downloads) + " downloads · " + m.Endorsements + " endorsements", m.Adult, m.Image, m.Thumb, b => mm.Image = b, NexusMods.ModUrl(m.Id))); } if (aboutGrid.Children.Count == 0) aboutGrid.Children.Add(T("Nothing to show yet.", 13, Ui.B(Ui.Dim))); ShowRecommended(); } } }