casualexpiesource

cu-trainer/Ultra Paradise Linux/app/About.cs

344 lines · 17.8 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Globalization;
4using System.IO;
5using System.Linq;
6using System.Net.Http;
7using System.Security.Cryptography;
8using System.Text;
9using System.Text.Json;
10using System.Threading.Tasks;
11using Avalonia;
12using Avalonia.Controls;
13using Avalonia.Controls.Primitives;
14using Avalonia.Input;
15using Avalonia.Layout;
16using Avalonia.Media;
17using Avalonia.Media.Imaging;
18using Avalonia.Threading;
19
20namespace UltraParadise.Linux
21{
22 internal sealed class NexusMod
23 {
24 public int Id, Endorsements;
25 public long Downloads;
26 public string Name, Summary, Thumb;
27 public bool Adult, Self;
28 public Bitmap Image;
29 }
30
31 internal static class NexusMods
32 {
33 public const string Member = "casualexpie";
34 private const string MemberId = "94954933";
35 private const string GameDomain = "scavprototype";
36 public const string ProfileUrl = "https://www.nexusmods.com/users/" + MemberId + "?tab=user+files";
37 public const string BananaUrl = "https://gamebanana.com/members/6222538";
38 private const string Api = "https://api.nexusmods.com/v2/graphql";
39 private static string CacheFile => Path.Combine(Dirs.Cache, "nexus.json");
40 private static string ThumbDir => Path.Combine(Dirs.Cache, "thumbs");
41
42 public static string ModUrl(int id) => "https://www.nexusmods.com/" + GameDomain + "/mods/" + id;
43
44 public static List<NexusMod> Load(out DateTime when)
45 {
46 when = DateTime.MinValue;
47 try
48 {
49 if (!File.Exists(CacheFile)) return null;
50 when = File.GetLastWriteTimeUtc(CacheFile);
51 return Parse(File.ReadAllText(CacheFile));
52 }
53 catch (Exception) { return null; }
54 }
55
56 public static async Task<List<NexusMod>> Fetch()
57 {
58 string q = "{ mods(filter:{ uploaderId:{ value:\"" + MemberId + "\" } }, sort:{ downloads:{ direction: DESC } }, count: 40) { nodes { modId name summary endorsements downloads thumbnailUrl status adultContent game { domainName } } } }";
59 string body = JsonSerializer.Serialize(new Dictionary<string, string> { ["query"] = q });
60 using HttpRequestMessage req = new(HttpMethod.Post, Api) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
61 using HttpResponseMessage res = await Http.Client.SendAsync(req);
62 res.EnsureSuccessStatusCode();
63 string json = await res.Content.ReadAsStringAsync();
64 List<NexusMod> list = Parse(json);
65 if (list == null) return null;
66 try { Private.Dir(Dirs.Cache); File.WriteAllText(CacheFile, json); } catch (Exception) { }
67 return list;
68 }
69
70 private static List<NexusMod> Parse(string json)
71 {
72 using JsonDocument doc = JsonDocument.Parse(json);
73 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;
74 List<NexusMod> list = new();
75 foreach (JsonElement n in nodes.EnumerateArray())
76 {
77 string S(JsonElement e, string k) => e.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
78 long N(string k) => n.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x) ? x : 0;
79 if (S(n, "status") != "published") continue;
80 if (!n.TryGetProperty("game", out JsonElement g) || S(g, "domainName") != GameDomain) continue;
81 NexusMod m = new() { Id = (int)N("modId"), Name = S(n, "name") ?? "" };
82 if (m.Id <= 0 || m.Name.Length == 0) continue;
83 m.Self = m.Id == Nexus.TrainerModId;
84 m.Adult = n.TryGetProperty("adultContent", out JsonElement a) && a.ValueKind == JsonValueKind.True;
85 m.Summary = (S(n, "summary") ?? "").Replace("\r", " ").Replace("\n", " ");
86 m.Downloads = N("downloads");
87 m.Endorsements = (int)N("endorsements");
88 m.Thumb = m.Adult ? null : S(n, "thumbnailUrl");
89 list.Add(m);
90 }
91 return list;
92 }
93
94 public static async Task<Bitmap> Thumb(string url)
95 {
96 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;
97 string file = Path.Combine(ThumbDir, Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(url))).ToLowerInvariant() + ".img");
98 byte[] bytes = null;
99 try { if (File.Exists(file)) bytes = await File.ReadAllBytesAsync(file); } catch (Exception) { }
100 if (bytes == null)
101 {
102 try
103 {
104 using HttpResponseMessage res = await Http.Client.GetAsync(u, HttpCompletionOption.ResponseHeadersRead);
105 if (!res.IsSuccessStatusCode || res.Content.Headers.ContentLength > 4 * 1024 * 1024) return null;
106 bytes = await res.Content.ReadAsByteArrayAsync();
107 if (bytes.Length > 4 * 1024 * 1024) return null;
108 Private.Dir(Dirs.Cache);
109 Private.Dir(ThumbDir);
110 await File.WriteAllBytesAsync(file, bytes);
111 }
112 catch (Exception) { return null; }
113 }
114 try
115 {
116 using MemoryStream ms = new(bytes);
117 return Bitmap.DecodeToWidth(ms, 240);
118 }
119 catch (Exception) { return null; }
120 }
121
122 public static string Big(long n)
123 {
124 if (n >= 1000000) return (n / 1000000.0).ToString("0.#", CultureInfo.InvariantCulture) + "M";
125 if (n >= 10000) return (n / 1000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k";
126 return n.ToString("#,0", CultureInfo.InvariantCulture);
127 }
128 }
129
130 internal sealed partial class MainWindow
131 {
132 private readonly StackPanel aboutStats = new() { Orientation = Orientation.Horizontal, Spacing = 28 };
133 private readonly TextBlock aboutStatus = T("Loading my mods from Nexus...", 12, Ui.B(Ui.Dim), false, true);
134 private readonly WrapPanel aboutGrid = new();
135 private readonly WrapPanel aboutTsGrid = new();
136 private readonly Border aboutRec = new() { Margin = new Thickness(0, 0, 12, 14) };
137 private const int RecommendedId = 885;
138 private const string RecommendedTs = "SaveAnywhere";
139 private List<NexusMod> aboutMods;
140
141 private static TextBlock SubHead(string text) => T(string.Join(" ", text.ToCharArray()), 11, Ui.B(Ui.Dim), true);
142
143 private Border ModCard(string name, string summary, string meta, bool adult, Bitmap image, string thumbUrl, Action<Bitmap> keep, string url)
144 {
145 Grid card = new() { ColumnDefinitions = new ColumnDefinitions("104,*"), Width = 330, Height = 96 };
146 Border thumb = new() { Background = Ui.B(Ui.Thumb), ClipToBounds = true };
147 Image img = new() { Stretch = Stretch.UniformToFill };
148 if (adult) thumb.Child = new TextBlock { Text = "18+", FontSize = 18, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Bad), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
149 else thumb.Child = img;
150 card.Children.Add(thumb);
151 StackPanel txt = new() { Margin = new Thickness(10, 0, 0, 0), Spacing = 2 };
152 TextBlock nm = T(name, 13, Ui.B(Ui.Text), true);
153 nm.TextTrimming = TextTrimming.CharacterEllipsis;
154 txt.Children.Add(nm);
155 TextBlock sum = T(summary ?? "", 12, Ui.B(Ui.Soft), false, true);
156 sum.MaxLines = 2;
157 sum.TextTrimming = TextTrimming.WordEllipsis;
158 txt.Children.Add(sum);
159 txt.Children.Add(T(meta, 12, Ui.B(Ui.Orange)));
160 Grid.SetColumn(txt, 1);
161 card.Children.Add(txt);
162 Border box = new()
163 {
164 Child = card,
165 Padding = new Thickness(8),
166 Margin = new Thickness(0, 0, 12, 12),
167 Background = Ui.B(Ui.Panel),
168 BorderBrush = Ui.B(Ui.Line),
169 BorderThickness = new Thickness(1),
170 Cursor = new Cursor(StandardCursorType.Hand),
171 };
172 box.PointerEntered += (_, _) => box.BorderBrush = Ui.B(Ui.Orange);
173 box.PointerExited += (_, _) => box.BorderBrush = Ui.B(Ui.Line);
174 box.PointerPressed += (_, e) => { if (e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) Game.Open(url); };
175 ToolTip.SetTip(box, name);
176 if (image != null) img.Source = image;
177 else if (thumbUrl != null && !adult)
178 {
179 _ = Task.Run(async () =>
180 {
181 Bitmap b = await NexusMods.Thumb(thumbUrl);
182 if (b != null) Dispatcher.UIThread.Post(() => { keep(b); img.Source = b; });
183 });
184 }
185 return box;
186 }
187
188 private void ShowRecommended()
189 {
190 NexusMod n = aboutMods?.FirstOrDefault(m => m.Id == RecommendedId);
191 TsPackage tp = null;
192 tsMods?.TryGetValue(RecommendedTs, out tp);
193 Grid card = new() { ColumnDefinitions = new ColumnDefinitions("170,*"), Height = 96 };
194 Border thumb = new() { Background = Ui.B(Ui.Thumb), ClipToBounds = true };
195 Image img = new() { Stretch = Stretch.UniformToFill, Source = n?.Image ?? tp?.Image };
196 thumb.Child = img;
197 card.Children.Add(thumb);
198 StackPanel txt = new() { Margin = new Thickness(12, 0, 0, 0), Spacing = 3 };
199 txt.Children.Add(T("Save Anywhere", 16, Ui.B(Ui.Bright), true));
200 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);
201 sum.MaxLines = 2;
202 sum.TextTrimming = TextTrimming.WordEllipsis;
203 txt.Children.Add(sum);
204 List<string> meta = new();
205 if (n != null) meta.Add(NexusMods.Big(n.Downloads) + " on Nexus");
206 if (tp != null) meta.Add("v" + tp.Version + " on Thunderstore");
207 StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 6 };
208 row.Children.Add(T(string.Join(" · ", meta), 12, Ui.B(Ui.Orange)));
209 Button nb = Btn("Nexus Mods", () => Game.Open(NexusMods.ModUrl(RecommendedId) + "?tab=files"));
210 Button tb = Btn("Thunderstore", () => OpenTs(tp?.Url ?? Thunderstore.PageUrl(RecommendedTs)));
211 nb.Margin = new Thickness(10, 0, 0, 0);
212 row.Children.Add(nb);
213 row.Children.Add(tb);
214 txt.Children.Add(row);
215 Grid.SetColumn(txt, 1);
216 card.Children.Add(txt);
217 aboutRec.Child = new Border
218 {
219 Child = card,
220 Padding = new Thickness(10),
221 Background = Ui.B(Ui.Panel),
222 BorderBrush = Ui.B(Ui.Orange),
223 BorderThickness = new Thickness(4, 1, 1, 1),
224 };
225 if (img.Source == null)
226 {
227 string u = n?.Thumb ?? tp?.Icon;
228 if (u != null)
229 _ = Task.Run(async () =>
230 {
231 Bitmap b = await NexusMods.Thumb(u);
232 if (b != null) Dispatcher.UIThread.Post(() => img.Source = b);
233 });
234 }
235 }
236
237 private void ShowTsAbout()
238 {
239 aboutTsGrid.Children.Clear();
240 if (tsMods != null)
241 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))
242 {
243 TsPackage pp = p;
244 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])", " ");
245 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));
246 }
247 if (aboutTsGrid.Children.Count == 0) aboutTsGrid.Children.Add(T(tsMods == null ? "Loading..." : "Nothing to show yet.", 13, Ui.B(Ui.Dim)));
248 ShowRecommended();
249 }
250 private bool aboutLoading;
251 private DateTime aboutLoaded = DateTime.MinValue;
252
253 private Control AboutPage()
254 {
255 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("300,*") };
256 StackPanel left = new() { Margin = new Thickness(0, 0, 22, 0), Spacing = 14 };
257 Border me = Section("ABOUT ME", out StackPanel mb);
258 StackPanel who = new() { Orientation = Orientation.Horizontal, Spacing = 10 };
259 Bitmap tile = Program.Image("tile.png");
260 if (tile != null)
261 {
262 Image ti = new() { Source = tile, Width = 44, Height = 44 };
263 RenderOptions.SetBitmapInterpolationMode(ti, BitmapInterpolationMode.None);
264 who.Children.Add(ti);
265 }
266 StackPanel nm = new() { VerticalAlignment = VerticalAlignment.Center };
267 nm.Children.Add(T(NexusMods.Member, 22, Ui.B(Ui.Bright), true));
268 nm.Children.Add(T("Modder for Casualties: Unknown", 12, Ui.B(Ui.Orange)));
269 who.Children.Add(nm);
270 mb.Children.Add(who);
271 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));
272 mb.Children.Add(aboutStats);
273 WrapPanel lk = new();
274 Button nxb = Btn("All my mods on Nexus", () => Game.Open(NexusMods.ProfileUrl));
275 nxb.Margin = new Thickness(0, 0, 6, 6);
276 lk.Children.Add(nxb);
277 Button gbb = Btn("My GameBanana page", () => Game.Open(NexusMods.BananaUrl));
278 gbb.Margin = new Thickness(0, 0, 6, 6);
279 lk.Children.Add(gbb);
280 Button tsb = Btn("My Thunderstore page", () => Game.Open(Thunderstore.TeamUrl));
281 tsb.Margin = new Thickness(0, 0, 6, 6);
282 lk.Children.Add(tsb);
283 mb.Children.Add(lk);
284 mb.Children.Add(aboutStatus);
285 left.Children.Add(me);
286 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));
287 g.Children.Add(left);
288
289 Border others = Section("CHECK OUT MY OTHER MODS", out StackPanel ob);
290 ob.Children.Add(SubHead("★ RECOMMENDED"));
291 ob.Children.Add(aboutRec);
292 ob.Children.Add(SubHead("ON NEXUS MODS"));
293 ob.Children.Add(aboutGrid);
294 ob.Children.Add(SubHead("ON THUNDERSTORE"));
295 ob.Children.Add(aboutTsGrid);
296 Grid.SetColumn(others, 1);
297 g.Children.Add(others);
298
299 List<NexusMod> cached = NexusMods.Load(out aboutLoaded);
300 if (cached != null) ShowAbout(cached);
301 tsMods ??= Thunderstore.Load(out _);
302 ShowTsAbout();
303 return Scroll(g);
304 }
305
306 private async Task LoadAbout()
307 {
308 if (aboutLoading || (aboutMods != null && (DateTime.UtcNow - aboutLoaded).TotalHours < 6)) return;
309 aboutLoading = true;
310 try
311 {
312 List<NexusMod> list = await NexusMods.Fetch();
313 if (list != null) { aboutLoaded = DateTime.UtcNow; ShowAbout(list); aboutStatus.Text = "Updated from Nexus just now."; }
314 }
315 catch (Exception)
316 {
317 aboutStatus.Text = aboutMods != null ? "Couldn't reach Nexus, so this is from last time." : "Couldn't reach Nexus Mods. Check your connection.";
318 }
319 finally { aboutLoading = false; }
320 }
321
322 private void ShowAbout(List<NexusMod> list)
323 {
324 aboutMods = list;
325 aboutStatus.Text = "From Nexus, " + aboutLoaded.ToLocalTime().ToString("d MMM HH:mm", CultureInfo.InvariantCulture) + ".";
326 aboutStats.Children.Clear();
327 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") })
328 {
329 StackPanel s = new();
330 s.Children.Add(T(num, 18, Ui.B(Ui.Text), true));
331 s.Children.Add(T(label, 12, Ui.B(Ui.Dim)));
332 aboutStats.Children.Add(s);
333 }
334 aboutGrid.Children.Clear();
335 foreach (NexusMod m in list.Where(x => !x.Self && x.Id != RecommendedId))
336 {
337 NexusMod mm = m;
338 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)));
339 }
340 if (aboutGrid.Children.Count == 0) aboutGrid.Children.Add(T("Nothing to show yet.", 13, Ui.B(Ui.Dim)));
341 ShowRecommended();
342 }
343 }
344}