using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using UltraParadise.Shared; namespace UltraParadise.Linux { internal static class Dirs { public static string Home => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); public static string Config { get { if (OperatingSystem.IsMacOS()) return Path.Combine(Home, "Library", "Application Support", "UltraParadise"); string x = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); return Path.Combine(string.IsNullOrEmpty(x) ? Path.Combine(Home, ".config") : x, "UltraParadise"); } } public static string Cache { get { if (OperatingSystem.IsMacOS()) return Path.Combine(Home, "Library", "Caches", "UltraParadise"); string x = Environment.GetEnvironmentVariable("XDG_CACHE_HOME"); return Path.Combine(string.IsNullOrEmpty(x) ? Path.Combine(Home, ".cache") : x, "UltraParadise"); } } } internal static class Private { private const UnixFileMode DirMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; private const UnixFileMode FileMode_ = UnixFileMode.UserRead | UnixFileMode.UserWrite; public static void Dir(string d) { if (OperatingSystem.IsWindows()) { Directory.CreateDirectory(d); return; } if (!Directory.Exists(d)) Directory.CreateDirectory(d, DirMode); else File.SetUnixFileMode(d, DirMode); } public static void Write(string f, byte[] data) { if (OperatingSystem.IsWindows()) { File.WriteAllBytes(f, data); return; } if (File.Exists(f) || new FileInfo(f).LinkTarget != null) File.Delete(f); using FileStream fs = new(f, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = FileMode_ }); fs.Write(data, 0, data.Length); } } internal static class Settings { private static readonly Dictionary d = new(); private static string File => Path.Combine(Dirs.Config, "settings.ini"); public static void Load() { try { if (!System.IO.File.Exists(File)) return; foreach (string line in System.IO.File.ReadAllLines(File)) { int eq = line.IndexOf('='); if (eq > 0) d[line[..eq].Trim()] = line[(eq + 1)..].Trim(); } } catch (Exception) { } } public static string Get(string k, string def) => d.TryGetValue(k, out string v) ? v : def; public static bool On(string k, bool def) => Get(k, def ? "1" : "0") == "1"; public static IEnumerable Keys() => d.Keys.ToList(); public static void Set(string k, string v) { if (v == null) d.Remove(k); else d[k] = v; try { Directory.CreateDirectory(Dirs.Config); System.IO.File.WriteAllLines(File, d.OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => x.Key + "=" + x.Value)); } catch (Exception) { } } } internal static class Http { public static readonly HttpClient Client = Make(); private static HttpClient Make() { HttpClient c = new(new SocketsHttpHandler { AllowAutoRedirect = true, MaxAutomaticRedirections = 5, ConnectTimeout = TimeSpan.FromSeconds(15) }); c.Timeout = TimeSpan.FromSeconds(60); c.DefaultRequestHeaders.UserAgent.ParseAdd("UltraParadiseCUTrainer-Linux/" + Program.Version); return c; } public static string Sha(string file) { using SHA256 h = SHA256.Create(); using FileStream fs = System.IO.File.OpenRead(file); return Convert.ToHexString(h.ComputeHash(fs)).ToLowerInvariant(); } public static string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant(); public static async Task Download(string url, string file, long max, long exact, Action progress) { string err = null; for (int attempt = 1; attempt <= 3; attempt++) { err = await DownloadOnce(url, file, max, exact, progress); if (err == null) return null; if (err.StartsWith("the download was bigger", StringComparison.Ordinal) || err.StartsWith("the server said 4", StringComparison.Ordinal)) return err; if (attempt < 3) await Task.Delay(2000 * attempt); } return err + " (tried 3 times)"; } private static async Task DownloadOnce(string url, string file, long max, long exact, Action progress) { using CancellationTokenSource cts = new(); try { cts.CancelAfter(TimeSpan.FromSeconds(90)); using HttpResponseMessage res = await Client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token); if (res.StatusCode != HttpStatusCode.OK) return "the server said " + (int)res.StatusCode; await using Stream s = await res.Content.ReadAsStreamAsync(cts.Token); await using FileStream fs = new(file, FileMode.Create, FileAccess.Write); byte[] buf = new byte[65536]; long total = 0, size = exact > 0 ? exact : res.Content.Headers.ContentLength ?? 0; int n, last = -1; while (true) { cts.CancelAfter(TimeSpan.FromSeconds(20)); n = await s.ReadAsync(buf, cts.Token); if (n <= 0) break; total += n; if (total > max || (exact > 0 && total > exact)) return "the download was bigger than expected"; await fs.WriteAsync(buf.AsMemory(0, n)); if (size > 0 && progress != null) { int pc = (int)(total * 100 / size); if (pc != last) { last = pc; progress(pc); } } } if (exact > 0 && total != exact) return "the download was cut short"; return null; } catch (OperationCanceledException) { return "the download stalled"; } catch (HttpRequestException e) { return "the connection dropped (" + e.Message + ")"; } catch (IOException e) { return "the connection dropped (" + e.Message + ")"; } } } internal sealed class LinkServer { public const string CodeVersion = "L1"; private TcpListener listener; private readonly string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); private readonly object gate = new(); private TcpClient client; private Stream stream; public int Port { get; private set; } public volatile bool IsConnected; public volatile string GameCode; public event Action Line; public event Action Connected, Disconnected; private string linkFile; public void Start() { listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); Port = ((IPEndPoint)listener.LocalEndpoint).Port; Thread t = new(AcceptLoop) { IsBackground = true, Name = "link accept" }; t.Start(); } public void WriteLinkFile(string gameDir) { try { string dir = Path.Combine(gameDir, "UltraParadise"); string f = Path.Combine(dir, "link.txt"); string want = Port + " " + token; if (f == linkFile && System.IO.File.Exists(f) && System.IO.File.ReadAllText(f).Trim() == want) return; if (!Directory.Exists(gameDir)) return; Private.Dir(dir); string tmp = f + ".tmp"; Private.Write(tmp, Encoding.ASCII.GetBytes(want)); System.IO.File.Move(tmp, f, true); if (linkFile != null && linkFile != f) RemoveLinkFile(); linkFile = f; } catch (Exception) { } } public void RemoveLinkFile() { try { if (linkFile != null && System.IO.File.Exists(linkFile)) System.IO.File.Delete(linkFile); } catch (Exception) { } } private void AcceptLoop() { while (true) { TcpClient c; try { c = listener.AcceptTcpClient(); } catch (Exception) { return; } Thread t = new(() => Session(c)) { IsBackground = true, Name = "link session" }; t.Start(); } } private static string ReadLine(Stream s, int max) { MemoryStream ms = new(); while (true) { int b = s.ReadByte(); if (b < 0) return ms.Length > 0 ? Encoding.UTF8.GetString(ms.ToArray()) : null; if (b == '\n') return Encoding.UTF8.GetString(ms.ToArray()).TrimEnd('\r'); if (ms.Length >= max) throw new IOException("line too long"); ms.WriteByte((byte)b); } } private void Session(TcpClient c) { bool mine = false; try { c.NoDelay = true; c.ReceiveTimeout = 5000; Stream s = new BufferedStream(c.GetStream(), 65536); string hello = ReadLine(s, 256); string[] p = hello == null ? Array.Empty() : hello.Split(' '); if (p.Length < 3 || p[0] != "HELLO" || !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p[1]), Encoding.ASCII.GetBytes(token))) return; c.ReceiveTimeout = 0; lock (gate) { try { client?.Close(); } catch (Exception) { } client = c; stream = c.GetStream(); mine = true; } GameCode = p[2]; Raw("OK"); IsConnected = true; Connected?.Invoke(); while (true) { string line = ReadLine(s, 16 * 1024 * 1024); if (line == null) break; if (line.Length > 70000 && !line.StartsWith("SFX ", StringComparison.Ordinal) && !line.StartsWith("MICON ", StringComparison.Ordinal) && !line.StartsWith("MOODLES ", StringComparison.Ordinal) && !line.StartsWith("DLOG ", StringComparison.Ordinal) && !line.StartsWith("DSNAP ", StringComparison.Ordinal) && !line.StartsWith("DSYS ", StringComparison.Ordinal) && !line.StartsWith("MODS ", StringComparison.Ordinal) && !line.StartsWith("MUSICLIST ", StringComparison.Ordinal)) continue; Line?.Invoke(line); } } catch (Exception) { } finally { bool drop = false; lock (gate) { if (mine && client == c) { client = null; stream = null; drop = true; } } try { c.Close(); } catch (Exception) { } if (drop) { IsConnected = false; Disconnected?.Invoke(); } } } private void Raw(string s) { lock (gate) { if (stream == null) return; try { byte[] b = Encoding.UTF8.GetBytes(s.Replace('\n', ' ').Replace('\r', ' ') + "\n"); stream.Write(b, 0, b.Length); } catch (Exception) { try { client?.Close(); } catch (Exception) { } } } } public event Action Sent; public void Send(string s) { if (!IsConnected) return; Raw(s); try { Sent?.Invoke(s); } catch (Exception) { } } } internal sealed class VNode { public string Key, Value; public List Kids; public VNode Child(string key) => Kids?.FirstOrDefault(k => string.Equals(k.Key, key, StringComparison.OrdinalIgnoreCase)); public VNode Ensure(string key) { VNode n = Child(key); if (n != null && n.Kids != null) return n; if (n != null) Kids.Remove(n); n = new VNode { Key = key, Kids = new List() }; Kids.Add(n); return n; } public void SetValue(string key, string value) { VNode n = Child(key); if (n == null || n.Kids != null) { if (n != null) Kids.Remove(n); n = new VNode { Key = key }; Kids.Add(n); } n.Value = value; } } internal static class Vdf { public static VNode Parse(string text) { int i = 0; VNode root = new() { Key = "", Kids = new List() }; Stack st = new(); st.Push(root); string pendingKey = null; while (true) { string tok = Next(text, ref i, out bool quoted); if (tok == null) break; if (!quoted && tok == "{") { if (pendingKey == null) throw new FormatException("unexpected {"); VNode n = new() { Key = pendingKey, Kids = new List() }; st.Peek().Kids.Add(n); st.Push(n); pendingKey = null; } else if (!quoted && tok == "}") { if (st.Count <= 1) throw new FormatException("unexpected }"); st.Pop(); } else if (pendingKey == null) pendingKey = tok; else { st.Peek().Kids.Add(new VNode { Key = pendingKey, Value = tok }); pendingKey = null; } } if (st.Count != 1) throw new FormatException("unbalanced braces"); return root; } private static string Next(string t, ref int i, out bool quoted) { quoted = false; while (i < t.Length) { char c = t[i]; if (char.IsWhiteSpace(c)) { i++; continue; } if (c == '/' && i + 1 < t.Length && t[i + 1] == '/') { while (i < t.Length && t[i] != '\n') i++; continue; } break; } if (i >= t.Length) return null; if (t[i] == '{' || t[i] == '}') return t[i++].ToString(); StringBuilder sb = new(); if (t[i] == '"') { quoted = true; i++; while (i < t.Length && t[i] != '"') { if (t[i] == '\\' && i + 1 < t.Length) { char e = t[i + 1]; sb.Append(e == 'n' ? '\n' : e == 't' ? '\t' : e); i += 2; continue; } sb.Append(t[i++]); } if (i >= t.Length) throw new FormatException("unterminated string"); i++; return sb.ToString(); } while (i < t.Length && !char.IsWhiteSpace(t[i]) && t[i] != '{' && t[i] != '}' && t[i] != '"') sb.Append(t[i++]); return sb.ToString(); } private static string Q(string s) => "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\t", "\\t") + "\""; public static string Write(VNode root) { StringBuilder sb = new(); foreach (VNode k in root.Kids) Write(sb, k, 0); return sb.ToString(); } private static void Write(StringBuilder sb, VNode n, int depth) { string ind = new('\t', depth); if (n.Kids == null) { sb.Append(ind).Append(Q(n.Key)).Append("\t\t").Append(Q(n.Value ?? "")).Append('\n'); return; } sb.Append(ind).Append(Q(n.Key)).Append('\n').Append(ind).Append("{\n"); foreach (VNode k in n.Kids) Write(sb, k, depth + 1); sb.Append(ind).Append("}\n"); } } internal static class Game { public const string AppId = "4576490"; public const string Exe = "CasualtiesUnknown.exe"; public const string Overrides = "WINEDLLOVERRIDES=\"winhttp,version=n,b\""; public const string LaunchOption = Overrides + " %command%"; public const string BepVersion = "5.4.23.6"; private const string BepZipUrl = "https://github.com/BepInEx/BepInEx/releases/download/v5.4.23.6/BepInEx_win_x64_5.4.23.6.zip"; private const string BepSha = "6c57a714a892efb4e9e1fef63d608a3391f30ec984031c465404e4ee381a0755"; public const string PluginFolder = "UltraParadise"; public const string PluginFile = "UltraParadise.CUTrainer.dll"; public static string Current; public static bool IsGameDir(string d) => !string.IsNullOrEmpty(d) && File.Exists(Path.Combine(d, Exe)); public static List SteamRoots() { List c = new(); string h = Dirs.Home; if (OperatingSystem.IsWindows()) { c.Add(@"C:\Program Files (x86)\Steam"); c.Add(@"C:\Program Files\Steam"); } else { c.Add(Path.Combine(h, ".steam", "steam")); c.Add(Path.Combine(h, ".steam", "root")); c.Add(Path.Combine(h, ".local", "share", "Steam")); c.Add(Path.Combine(h, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam")); c.Add(Path.Combine(h, ".var", "app", "com.valvesoftware.Steam", "data", "Steam")); c.Add(Path.Combine(h, "snap", "steam", "common", ".local", "share", "Steam")); } List o = new(); HashSet seen = new(StringComparer.Ordinal); foreach (string p in c) { try { if (!Directory.Exists(p)) continue; string real = Real(p); if (seen.Add(real)) o.Add(real); } catch (Exception) { } } return o; } private static string Real(string p) { try { FileSystemInfo t = new DirectoryInfo(p).ResolveLinkTarget(true); return Path.GetFullPath(t != null ? t.FullName : p).TrimEnd('/', '\\'); } catch (Exception) { return Path.GetFullPath(p).TrimEnd('/', '\\'); } } public static List Libraries() { List libs = new(); HashSet seen = new(StringComparer.Ordinal); foreach (string root in SteamRoots()) { if (seen.Add(root)) libs.Add(root); try { string f = Path.Combine(root, "steamapps", "libraryfolders.vdf"); if (!File.Exists(f)) continue; VNode v = Vdf.Parse(File.ReadAllText(f)); VNode lf = v.Child("libraryfolders") ?? v; foreach (VNode n in lf.Kids ?? new List()) { string p = n.Kids != null ? n.Child("path")?.Value : n.Value; if (string.IsNullOrEmpty(p) || !Directory.Exists(p)) continue; string real = Real(p); if (seen.Add(real)) libs.Add(real); } } catch (Exception) { } } return libs; } public static string Find() { if (Mac.On) return Mac.Find(); foreach (string lib in Libraries()) { try { string acf = Path.Combine(lib, "steamapps", "appmanifest_" + AppId + ".acf"); if (File.Exists(acf)) { string dir = Vdf.Parse(File.ReadAllText(acf)).Child("AppState")?.Child("installdir")?.Value; if (!string.IsNullOrEmpty(dir)) { string d = Path.Combine(lib, "steamapps", "common", dir); if (IsGameDir(d)) return d; } } string guess = Path.Combine(lib, "steamapps", "common", "Casualties Unknown"); if (IsGameDir(guess)) return guess; } catch (Exception) { } } return null; } public static bool BepInstalled(string d) => IsGameDir(d) && File.Exists(Path.Combine(d, "BepInEx", "core", "BepInEx.dll")) && File.Exists(Path.Combine(d, "winhttp.dll")); public static bool BepRan(string d) => File.Exists(Path.Combine(d, "BepInEx", "LogOutput.log")); public static string PluginPath(string d) => Path.Combine(d, "BepInEx", "plugins", PluginFolder, PluginFile); public const string UpDll = "UltraPara.dll"; public const string UpStub = "version.dll"; private static bool StubOurs(string stub) { try { byte[] b = File.ReadAllBytes(stub); byte[] mark = Encoding.Unicode.GetBytes("UltraPara"); return b.AsSpan().IndexOf(mark) >= 0; } catch (Exception) { return false; } } public static string PluginState(string d) { if (!IsGameDir(d)) return "nogame"; string dll = Path.Combine(d, UpDll), stub = Path.Combine(d, UpStub); if (File.Exists(stub) && !StubOurs(stub)) return "foreign"; if (!File.Exists(dll) || !File.Exists(stub)) return "missing"; try { return Http.Sha(dll) == UltraParaInfo.DllSha && Http.Sha(stub) == UltraParaInfo.StubSha ? "ok" : "old"; } catch (Exception) { return "old"; } } public static string LoaderLog(string d) { try { string f = Path.Combine(d, "UltraParadise", "UltraPara.log"); if (!File.Exists(f)) return null; using FileStream fs = new(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); using StreamReader r = new(fs); string[] lines = r.ReadToEnd().Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries); return lines.Length > 0 ? lines[^1] : null; } catch (Exception) { return null; } } private static byte[] ZipEntry(ZipArchive z, string name, string sha) { ZipArchiveEntry e = z.GetEntry(name) ?? throw new InvalidDataException(name + " is missing from the download"); using Stream s = e.Open(); using MemoryStream ms = new(); s.CopyTo(ms); byte[] b = ms.ToArray(); if (Http.Sha(b) != sha) throw new InvalidDataException(name + " didn't match its fingerprint"); return b; } public static async Task InstallPlugin(string d, Action progress = null) { if (!IsGameDir(d)) return "the game folder wasn't found"; if (GameRunning()) return "close the game first"; string st = PluginState(d); if (st == "foreign") return "your game folder already has a version.dll from another program or mod. Move it out of the game folder, then try again"; try { string cacheDir = Path.Combine(Dirs.Cache, "ultrapara"); Directory.CreateDirectory(cacheDir); string zip = Path.Combine(cacheDir, UltraParaInfo.ZipName); if (!File.Exists(zip) || Http.Sha(zip) != UltraParaInfo.ZipSha) { string tmp = zip + ".part"; string err = await Http.Download("https://updates.smellypawz.com/v1/download?app=ultrapara&version=" + UltraParaInfo.Version, tmp, 30L * 1024 * 1024, 0, progress); if (err != null) { try { File.Delete(tmp); } catch (Exception) { } return "couldn't download UltraPara.dll from the update server (" + err + "). You can also get it from updates.smellypawz.com and put UltraPara.dll and version.dll in the game folder yourself"; } if (Http.Sha(tmp) != UltraParaInfo.ZipSha) { File.Delete(tmp); return "the download didn't match the fingerprint built into the trainer, so nothing was installed"; } File.Move(tmp, zip, true); } byte[] dll, stub; using (ZipArchive z = ZipFile.OpenRead(zip)) { dll = ZipEntry(z, UpDll, UltraParaInfo.DllSha); stub = ZipEntry(z, UpStub, UltraParaInfo.StubSha); } foreach ((string name, byte[] b) in new[] { (UpDll, dll), (UpStub, stub) }) { string p = Path.Combine(d, name); File.WriteAllBytes(p + ".new", b); File.Move(p + ".new", p, true); } string old = Path.GetDirectoryName(PluginPath(d)); if (Directory.Exists(old)) Directory.Delete(old, true); return PluginState(d) == "ok" ? null : "UltraPara.dll was written but doesn't check out. Try again"; } catch (Exception e) { return e.Message; } } public static string RemovePlugin(string d) { if (GameRunning()) return "close the game first"; try { string dll = Path.Combine(d, UpDll), stub = Path.Combine(d, UpStub); if (File.Exists(stub) && StubOurs(stub)) File.Delete(stub); if (File.Exists(dll)) File.Delete(dll); string dir = Path.GetDirectoryName(PluginPath(d)); if (Directory.Exists(dir)) Directory.Delete(dir, true); return null; } catch (Exception e) { return e.Message; } } public static string OtherCheats(string d) { try { string pl = Path.Combine(d, "BepInEx", "plugins"); if (!Directory.Exists(pl)) return null; foreach (string f in Directory.EnumerateFiles(pl, "*.dll", SearchOption.AllDirectories)) if (string.Equals(Path.GetFileName(f), "CUCheats.dll", StringComparison.OrdinalIgnoreCase)) return f; } catch (Exception) { } return null; } public static async Task InstallBepInEx(string d, Action progress) { if (!IsGameDir(d)) return "the game folder wasn't found"; if (GameRunning()) return "close the game first"; string dir = Path.Combine(Dirs.Cache, "download"); Directory.CreateDirectory(dir); string zip = Path.Combine(dir, "BepInEx_win_x64_" + BepVersion + ".zip"); try { string err = await Http.Download(BepZipUrl, zip, 20L * 1024 * 1024, 0, progress); if (err != null) return "couldn't download BepInEx: " + err; if (Http.Sha(zip) != BepSha) return "the BepInEx download didn't match its official fingerprint, so nothing was installed"; string root = Path.GetFullPath(d).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; using (ZipArchive a = ZipFile.OpenRead(zip)) { foreach (ZipArchiveEntry e in a.Entries) { string name = e.FullName.Replace('\\', '/'); if (name.Length == 0) continue; string dest = Path.GetFullPath(Path.Combine(d, name)); if (!dest.StartsWith(root, StringComparison.Ordinal)) return "the BepInEx download had an unsafe path in it"; if (name.EndsWith('/')) { Directory.CreateDirectory(dest); continue; } Directory.CreateDirectory(Path.GetDirectoryName(dest)); e.ExtractToFile(dest, true); } } Directory.CreateDirectory(Path.Combine(d, "BepInEx", "plugins")); return BepInstalled(d) ? null : "BepInEx didn't end up in the game folder"; } catch (Exception e) { return e.Message; } finally { try { File.Delete(zip); } catch (Exception) { } } } private static IEnumerable<(int pid, string comm, string cmd)> Procs() { if (OperatingSystem.IsWindows()) yield break; string[] dirs; try { dirs = Directory.GetDirectories("/proc"); } catch (Exception) { yield break; } foreach (string p in dirs) { if (!int.TryParse(Path.GetFileName(p), out int pid)) continue; string comm = "", cmd = ""; try { comm = File.ReadAllText(Path.Combine(p, "comm")).Trim(); } catch (Exception) { } try { cmd = File.ReadAllText(Path.Combine(p, "cmdline")).Replace('\0', ' '); } catch (Exception) { } yield return (pid, comm, cmd); } } public static bool GameRunning() { if (OperatingSystem.IsWindows()) return Process.GetProcessesByName("CasualtiesUnknown").Length > 0; if (Mac.On) return Mac.GameRunning(); foreach (var p in Procs()) if (p.cmd.Contains(Exe, StringComparison.OrdinalIgnoreCase) && !p.cmd.Contains("UltraParadise", StringComparison.Ordinal)) return true; return false; } public static bool SteamRunning() { if (OperatingSystem.IsWindows()) return Process.GetProcessesByName("steam").Length > 0; foreach (var p in Procs()) if (p.comm == "steam" || p.cmd.Contains("/ubuntu12_32/steam ", StringComparison.Ordinal) || p.cmd.EndsWith("/ubuntu12_32/steam", StringComparison.Ordinal)) return true; return false; } public static List LocalConfigs() { List o = new(); foreach (string root in SteamRoots()) { string ud = Path.Combine(root, "userdata"); if (!Directory.Exists(ud)) continue; try { foreach (string u in Directory.GetDirectories(ud)) { string f = Path.Combine(u, "config", "localconfig.vdf"); if (File.Exists(f)) o.Add(f); } } catch (Exception) { } } return o; } private static VNode AppNode(VNode root, bool create) { VNode n = root.Child("UserLocalConfigStore"); if (n == null) return null; foreach (string k in new[] { "Software", "Valve", "Steam", "apps", AppId }) { VNode c = n.Child(k); if (c == null || c.Kids == null) { if (!create) return null; c = n.Ensure(k); } n = c; } return n; } public static bool HasOverride(string opts) => opts != null && System.Text.RegularExpressions.Regex.IsMatch(opts, "WINEDLLOVERRIDES=\"[^\"]*\\bversion\\b[^\"]*=n,b", System.Text.RegularExpressions.RegexOptions.IgnoreCase); public static string LaunchOptionState() { if (Mac.On) return Current == null ? "unknown" : Mac.OverrideState(Current); List files = LocalConfigs(); if (files.Count == 0) return "unknown"; bool any = false; foreach (string f in files) { try { VNode a = AppNode(Vdf.Parse(File.ReadAllText(f)), false); if (HasOverride(a?.Child("LaunchOptions")?.Value)) return "set"; any = true; } catch (Exception) { } } return any ? "unset" : "unknown"; } public static string SetLaunchOption() { if (Mac.On) return Current == null ? "find the game first" : Mac.SetOverride(Current); if (SteamRunning()) return "Steam is running. Quit Steam fully (Steam menu > Exit), then try again. Or paste the line into the game's Properties > Launch Options yourself."; List files = LocalConfigs(); if (files.Count == 0) return "couldn't find Steam's settings. Paste the line into the game's Properties > Launch Options yourself."; int done = 0; string last = null; foreach (string f in files) { try { string text = File.ReadAllText(f); VNode root = Vdf.Parse(text); VNode a = AppNode(root, true); if (a == null) continue; string cur = a.Child("LaunchOptions")?.Value ?? ""; if (HasOverride(cur)) { done++; continue; } string v; if (cur.Trim().Length == 0) v = LaunchOption; else if (System.Text.RegularExpressions.Regex.IsMatch(cur, "WINEDLLOVERRIDES=\"[^\"]*\"")) v = System.Text.RegularExpressions.Regex.Replace(cur.Trim(), "WINEDLLOVERRIDES=\"[^\"]*\"", Overrides); else if (cur.Contains("%command%", StringComparison.Ordinal)) v = Overrides + " " + cur.Trim(); else v = LaunchOption + " " + cur.Trim(); a.SetValue("LaunchOptions", v); string bak = f + ".ultraparadise.bak"; if (!File.Exists(bak)) File.Copy(f, bak); string tmp = f + ".tmp"; File.WriteAllText(tmp, Vdf.Write(root)); Vdf.Parse(File.ReadAllText(tmp)); File.Move(tmp, f, true); done++; } catch (Exception e) { last = e.Message; } } if (done == 0) return "couldn't change Steam's settings" + (last != null ? " (" + last + ")" : "") + ". Paste the line into the game's Properties > Launch Options yourself."; return null; } public static string Which(string exe) { foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(':').Concat(new[] { "/usr/bin", "/usr/local/bin", "/bin", "/usr/games", "/opt/homebrew/bin" })) { if (dir.Length == 0) continue; string f = Path.Combine(dir, exe); if (File.Exists(f)) return f; } return null; } private static async Task Try(string exe, params string[] args) { try { ProcessStartInfo si = new(exe) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; foreach (string a in args) si.ArgumentList.Add(a); Process p = Process.Start(si); if (p == null) return false; _ = p.StandardOutput.ReadToEndAsync(); _ = p.StandardError.ReadToEndAsync(); Task done = p.WaitForExitAsync(); if (await Task.WhenAny(done, Task.Delay(4000)) != done) return true; return p.ExitCode == 0; } catch (Exception) { return false; } } public static async Task Start() { if (Mac.On) return Current == null ? "find the game first" : await Mac.Start(Current); string url = "steam://rungameid/" + AppId; if (OperatingSystem.IsWindows()) { try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); return null; } catch (Exception e) { return e.Message; } } string steam = Which("steam"); if (steam != null && await Try(steam, "-applaunch", AppId)) return null; string flatpak = Which("flatpak"); if (flatpak != null && Directory.Exists(Path.Combine(Dirs.Home, ".var", "app", "com.valvesoftware.Steam")) && await Try(flatpak, "run", "com.valvesoftware.Steam", "-applaunch", AppId)) return null; string snap = Which("snap"); if (snap != null && Directory.Exists(Path.Combine(Dirs.Home, "snap", "steam")) && await Try(snap, "run", "steam", "-applaunch", AppId)) return null; string xdg = Which("xdg-open"); if (xdg != null && await Try(xdg, url)) return null; string gio = Which("gio"); if (gio != null && await Try(gio, "open", url)) return null; return "couldn't ask Steam to start the game. Start it from your Steam library instead."; } public static void Open(string target) { try { if (OperatingSystem.IsWindows()) Process.Start(new ProcessStartInfo(target) { UseShellExecute = true }); else { ProcessStartInfo si = new(Mac.On ? "/usr/bin/open" : "xdg-open") { UseShellExecute = false }; si.ArgumentList.Add(target); Process.Start(si); } } catch (Exception) { } } } internal static class Nexus { private const string MemberId = "94954933"; private const string GameDomain = "scavprototype"; public const int TrainerModId = 1203; public static string PageUrl => "https://www.nexusmods.com/" + GameDomain + "/mods/" + TrainerModId; public static async Task HashListed(string hash) { if (hash == null || !Regex.IsMatch(hash, "^[0-9a-f]{64}$")) return -1; string q = "{ mods(filter:{ uploaderId:{ value:\"" + MemberId + "\" } }, count: 60) { nodes { modId description status game { domainName } } } }"; string body = JsonSerializer.Serialize(new Dictionary { ["query"] = q }); using HttpRequestMessage req = new(HttpMethod.Post, "https://api.nexusmods.com/v2/graphql") { Content = new StringContent(body, Encoding.UTF8, "application/json") }; using HttpResponseMessage res = await Http.Client.SendAsync(req); if (!res.IsSuccessStatusCode) return 0; using JsonDocument doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync()); if (!doc.RootElement.TryGetProperty("data", out JsonElement data) || !data.TryGetProperty("mods", out JsonElement mods) || !mods.TryGetProperty("nodes", out JsonElement nodes)) return 0; bool page = false; foreach (JsonElement n in nodes.EnumerateArray()) { if (!n.TryGetProperty("modId", out JsonElement id) || id.ValueKind != JsonValueKind.Number || id.GetInt32() != TrainerModId) continue; if (!n.TryGetProperty("game", out JsonElement g) || !g.TryGetProperty("domainName", out JsonElement dn) || dn.GetString() != GameDomain) continue; if (!n.TryGetProperty("status", out JsonElement st) || st.GetString() != "published") continue; page = true; string desc = n.TryGetProperty("description", out JsonElement de) ? de.GetString() ?? "" : ""; if (desc.ToLowerInvariant().Contains(hash)) return 1; } return page ? -1 : 0; } } internal sealed class UpdateInfo { public string Version, Sha, Notes; public long Size; public VtResult Vt; public bool VtClean => Vt != null && Vt.Clean; public bool VtFlagged => Vt != null && Vt.Status == "done" && Vt.Flagged > 0; public string VtLine => Vt != null ? Vt.Line : "VirusTotal: couldn't get a result right now."; } internal sealed class VtResult { public string Status = "unknown", Link, Sha; public int Flagged, Total, Malicious, Suspicious, Undetected, Harmless; public long Scanned; public string Detail => Status != "done" ? "Engine breakdown: not ready yet." : "Malicious " + Malicious + " \u00b7 Suspicious " + Suspicious + " \u00b7 Clean " + (Undetected + Harmless) + " \u00b7 " + Total + " engines"; public bool Clean => Status == "done" && Flagged == 0 && Total > 0; private string When => Scanned <= 0 ? "" : " Scanned " + DateTimeOffset.FromUnixTimeMilliseconds(Scanned).LocalDateTime.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + "."; public string Line => Status switch { "done" => "VirusTotal: " + Flagged + " of " + Total + " antivirus engines flagged it." + When, "queued" => "VirusTotal: it's being scanned right now. The result shows up within about 30 minutes.", "not_official" => "VirusTotal: this copy isn't an official release, so it has no report. Get the trainer from the official Nexus page.", _ => "VirusTotal: no result yet. The update server checks again every 30 minutes.", }; } internal static class VirusTotal { private const string Base = "https://updates.smellypawz.com"; public static VtResult Self; public static async Task Lookup(string query) { string json = await Http.Client.GetStringAsync(Base + "/v1/vt?" + query); using JsonDocument doc = JsonDocument.Parse(json); JsonElement r = doc.RootElement; int N(string k) => r.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.Number ? e.GetInt32() : 0; VtResult v = new() { Status = r.TryGetProperty("status", out JsonElement s) && s.ValueKind == JsonValueKind.String ? s.GetString() : "unknown", Flagged = N("malicious") + N("suspicious"), Total = N("total"), Malicious = N("malicious"), Suspicious = N("suspicious"), Undetected = N("undetected"), Harmless = N("harmless"), Scanned = r.TryGetProperty("scanned", out JsonElement sc) && sc.ValueKind == JsonValueKind.Number ? sc.GetInt64() : 0, }; if (r.TryGetProperty("sha256", out JsonElement h) && h.ValueKind == JsonValueKind.String && Regex.IsMatch(h.GetString(), "^[0-9a-f]{64}$")) { v.Sha = h.GetString(); v.Link = "https://www.virustotal.com/gui/file/" + v.Sha; } return v; } public static Task ForSha(string sha) => Lookup("sha=" + sha); public static Task ForThisVersion() => Lookup("app=" + (Mac.On ? "trainermac" : "trainerlinux") + "&version=" + Program.Version); } internal static class Usage { private const string Base = "https://updates.smellypawz.com"; public static string Status = "Not counted yet."; public static long Day => (long)Math.Floor((DateTime.UtcNow - DateTime.UnixEpoch).TotalDays); public static string NewId() => Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); public static bool ValidId(string id) => id != null && Regex.IsMatch(id, "^[0-9a-f]{32}$"); public static async Task Ping(string id) { if (!ValidId(id)) return false; string s = await Http.Client.GetStringAsync(Base + "/v1/ping?app=trainerlinux&id=" + id + "&v=" + Program.Version + "&os=" + (Mac.On ? "mac" : "linux")); return s.Contains("\"ok\":true"); } public static async Task Forget(string id) { if (!ValidId(id)) return true; string s = await Http.Client.GetStringAsync(Base + "/v1/forget?app=trainerlinux&id=" + id); return s.Contains("\"ok\":true"); } public static async Task Stats() { string json = await Http.Client.GetStringAsync(Base + "/v1/users"); using JsonDocument doc = JsonDocument.Parse(json); JsonElement r = doc.RootElement; static int N(JsonElement o, string k) => o.ValueKind == JsonValueKind.Object && o.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.Number ? e.GetInt32() : 0; if (!r.TryGetProperty("week", out _)) return null; JsonElement p = r.TryGetProperty("platforms30d", out JsonElement pe) ? pe : default; CultureInfo c = CultureInfo.InvariantCulture; int mac = N(p, "mac"); return "Today: " + N(r, "today").ToString("N0", c) + "\nThis week: " + N(r, "week").ToString("N0", c) + "\nThis month: " + N(r, "month").ToString("N0", c) + "\nLast 90 days: " + N(r, "last90days").ToString("N0", c) + "\n\nLast 30 days: Windows " + N(p, "win").ToString("N0", c) + " · Linux / Steam Deck " + N(p, "linux").ToString("N0", c) + (mac > 0 ? " · macOS " + mac.ToString("N0", c) : ""); } public static async Task Count() { string json = await Http.Client.GetStringAsync(Base + "/v1/users"); using JsonDocument doc = JsonDocument.Parse(json); JsonElement r = doc.RootElement; int week = r.TryGetProperty("week", out JsonElement w) && w.ValueKind == JsonValueKind.Number ? w.GetInt32() : 0; int month = r.TryGetProperty("month", out JsonElement m) && m.ValueKind == JsonValueKind.Number ? m.GetInt32() : week; return week.ToString("N0", CultureInfo.InvariantCulture) + (week == 1 ? " person" : " people") + " used the trainer this week, " + month.ToString("N0", CultureInfo.InvariantCulture) + " this month."; } } internal static class Updater { private const string Base = "https://updates.smellypawz.com"; private static string AppName => Mac.On ? "trainermac" : "trainerlinux"; public static bool Manual => Mac.On; public static string ManualPage => Nexus.PageUrl + "?tab=files"; private const long MaxBytes = 120L * 1024 * 1024; public static string Status = "Not checked yet."; public static UpdateInfo Ready; public static int Compare(string a, string b) { string[] x = a.Split('.'), y = b.Split('.'); for (int i = 0; i < 3; i++) { int p = i < x.Length && int.TryParse(x[i], out int px) ? px : 0; int q = i < y.Length && int.TryParse(y[i], out int qy) ? qy : 0; if (p != q) return p.CompareTo(q); } return 0; } public static async Task Check() { string json = await Http.Client.GetStringAsync(Base + "/v1/latest?app=" + AppName + "&have=" + Program.Version); using JsonDocument doc = JsonDocument.Parse(json); JsonElement r = doc.RootElement; string S(string k) => r.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() : null; string ver = S("version"); if (ver == null || !Regex.IsMatch(ver, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$") || Compare(ver, Program.Version) <= 0) return null; if (Manual) { string mn = S("notes") ?? ""; mn = mn.Replace("\\n", "\n").Replace("\r\n", "\n").Trim(); return new UpdateInfo { Version = ver, Notes = mn.Length > 4000 ? mn[..4000] : mn }; } string sha = S("sha256")?.ToLowerInvariant(); if (sha == null || !Regex.IsMatch(sha, "^[0-9a-f]{64}$")) return null; long size = r.TryGetProperty("size", out JsonElement se) && se.ValueKind == JsonValueKind.Number ? se.GetInt64() : 0; if (size <= 0 || size > MaxBytes) return null; string notes = S("notes") ?? ""; notes = notes.Replace("\\n", "\n").Replace("\r\n", "\n").Trim(); if (notes.Length > 4000) notes = notes[..4000]; UpdateInfo info = new() { Version = ver, Sha = sha, Size = size, Notes = notes }; try { info.Vt = await VirusTotal.ForSha(sha); } catch (Exception) { info.Vt = null; } return info; } public static async Task Install(UpdateInfo u, Action progress) { if (OperatingSystem.IsWindows()) return "updates install on Linux only"; string cur = Environment.ProcessPath; if (string.IsNullOrEmpty(cur)) return "couldn't find where the trainer is"; string dir = Path.Combine(Dirs.Cache, "update"); try { if (Directory.Exists(dir)) Directory.Delete(dir, true); } catch (Exception) { } Private.Dir(Dirs.Cache); Private.Dir(dir); string tgz = Path.Combine(dir, "update.tar.gz"); string err = await Http.Download(Base + "/v1/download?app=" + AppName + "&version=" + u.Version, tgz, MaxBytes, u.Size, progress); if (err != null) return err; if (Http.Sha(tgz) != u.Sha) return "the download didn't match its fingerprint, so it was thrown away"; int listed; try { listed = await Nexus.HashListed(u.Sha); } catch (Exception) { listed = 0; } if (listed == 0) return "couldn't reach Nexus Mods to double-check the update. Try again later"; if (listed < 0) return "this update isn't listed on the official Nexus page yet, so it wasn't installed"; string x = Path.Combine(dir, "x"); Private.Dir(x); ProcessStartInfo list = new("tar") { RedirectStandardOutput = true, UseShellExecute = false }; list.ArgumentList.Add("-tzf"); list.ArgumentList.Add(tgz); using (Process p = Process.Start(list)) { string names = await p.StandardOutput.ReadToEndAsync(); await p.WaitForExitAsync(); if (p.ExitCode != 0) return "couldn't read the update"; foreach (string n in names.Split('\n', StringSplitOptions.RemoveEmptyEntries)) if (n.StartsWith('/') || n.Split('/').Contains("..")) return "the update had an unsafe path in it"; } ProcessStartInfo kinds = new("tar") { RedirectStandardOutput = true, UseShellExecute = false }; kinds.ArgumentList.Add("-tvzf"); kinds.ArgumentList.Add(tgz); using (Process p = Process.Start(kinds)) { string rows = await p.StandardOutput.ReadToEndAsync(); await p.WaitForExitAsync(); if (p.ExitCode != 0) return "couldn't read the update"; foreach (string r in rows.Split('\n', StringSplitOptions.RemoveEmptyEntries)) if (r[0] != '-' && r[0] != 'd') return "the update had a link or special file in it, so it was thrown away"; } ProcessStartInfo ex = new("tar") { UseShellExecute = false }; ex.ArgumentList.Add("-xzf"); ex.ArgumentList.Add(tgz); ex.ArgumentList.Add("--no-same-owner"); ex.ArgumentList.Add("-C"); ex.ArgumentList.Add(x); using (Process p = Process.Start(ex)) { await p.WaitForExitAsync(); if (p.ExitCode != 0) return "couldn't unpack the update"; } string exe = Directory.EnumerateFiles(x, "UltraParadiseCUTrainer", SearchOption.AllDirectories).FirstOrDefault(); if (exe == null || new FileInfo(exe).LinkTarget != null) return "the update didn't have the trainer in it"; try { string tmp = cur + ".new"; File.Copy(exe, tmp, true); File.SetUnixFileMode(tmp, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); File.Move(tmp, cur, true); string icon = Path.Combine(Path.GetDirectoryName(exe), "icon.png"); if (File.Exists(icon)) File.Copy(icon, Path.Combine(Path.GetDirectoryName(cur), "icon.png"), true); } catch (Exception e) { return "couldn't install the update: " + e.Message; } try { Directory.Delete(dir, true); } catch (Exception) { } try { Process.Start(new ProcessStartInfo(cur, "--updated") { UseShellExecute = false }); } catch (Exception e) { return "the update is installed, but the trainer couldn't restart itself (" + e.Message + "). Open it again."; } return null; } } internal static class Bark { private static string Folder => Path.Combine(Dirs.Cache, "sounds"); private static readonly Random rng = new(); public static float Pitch = 1f; public static List Names = new(); private static string player; private static int plays; private static DateTime last = DateTime.MinValue; public static void LoadSaved() { string s = Settings.Get("barkset", ""); if (s.Length > 0) Parse(s); } private static bool Parse(string rest) { int sp = rest.IndexOf(' '); if (sp <= 0) return false; if (!float.TryParse(rest[..sp], NumberStyles.Float, CultureInfo.InvariantCulture, out float p)) return false; List names = rest[(sp + 1)..].Split(',', StringSplitOptions.RemoveEmptyEntries).Where(Ok).Take(16).ToList(); if (names.Count == 0) return false; Pitch = Math.Clamp(p, 0.5f, 2f); Names = names; return true; } private static bool Ok(string n) => n.Length is > 0 and <= 40 && n.All(c => char.IsAsciiLetterOrDigit(c) || c == '_' || c == '-'); public static List OnSet(string rest) { List want = new(); if (!Parse(rest)) return want; Settings.Set("barkset", rest); foreach (string n in Names) if (!File.Exists(Path.Combine(Folder, n + ".wav"))) want.Add(n); return want; } public static void OnSfx(string rest) { int sp = rest.IndexOf(' '); if (sp <= 0) return; string name = rest[..sp]; if (!Ok(name)) return; byte[] b; try { b = Convert.FromBase64String(rest[(sp + 1)..]); } catch (Exception) { return; } if (b.Length < 44 || b.Length > 12 * 1024 * 1024 || b[0] != 'R' || b[1] != 'I' || b[2] != 'F' || b[3] != 'F' || b[8] != 'W' || b[9] != 'A' || b[10] != 'V' || b[11] != 'E') return; try { Directory.CreateDirectory(Folder); File.WriteAllBytes(Path.Combine(Folder, name + ".wav"), b); } catch (Exception) { } } private static string Player() { if (player != null) return player.Length > 0 ? player : null; player = ""; if (OperatingSystem.IsWindows()) return null; if (Mac.On) { player = File.Exists("/usr/bin/afplay") ? "/usr/bin/afplay" : ""; return player.Length > 0 ? player : null; } foreach (string exe in new[] { "pw-play", "paplay", "aplay" }) foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "/usr/bin:/bin").Split(':')) { if (dir.Length == 0) continue; string f = Path.Combine(dir, exe); if (File.Exists(f)) { player = f; return player; } } return null; } public static void Play() => Play(false); public static string Play(bool test) { if (!test && (DateTime.UtcNow - last).TotalMilliseconds < 400) return null; try { List have = Names.Where(n => File.Exists(Path.Combine(Folder, n + ".wav"))).ToList(); if (have.Count == 0) return "No bark sounds yet. Start a run with the trainer attached once, and it picks your runner's barks up from the game."; string p = Player(); if (p == null) return "No sound player found. Install pipewire (pw-play), pulseaudio-utils (paplay) or alsa-utils (aplay)."; last = DateTime.UtcNow; byte[] b = File.ReadAllBytes(Path.Combine(Folder, have[rng.Next(have.Count)] + ".wav")); float pitch = Pitch * (0.92f + (float)rng.NextDouble() * 0.16f); int rate = BitConverter.ToInt32(b, 24), ch = b[22], bits = b[34]; int nr = Math.Clamp((int)(rate * pitch), 8000, 192000); BitConverter.GetBytes(nr).CopyTo(b, 24); BitConverter.GetBytes(nr * ch * (bits / 8)).CopyTo(b, 28); string playDir = Path.Combine(Dirs.Cache, "play"); Private.Dir(Dirs.Cache); Private.Dir(playDir); string tmp = Path.Combine(playDir, "bark-" + (++plays % 4) + ".wav"); Private.Write(tmp, b); ProcessStartInfo si = new(p) { UseShellExecute = false, RedirectStandardError = false, RedirectStandardOutput = false }; si.ArgumentList.Add(tmp); using Process pr = Process.Start(si); return null; } catch (Exception e) { return "The bark couldn't play: " + e.Message; } } } internal sealed class Fix { public string Label, Act; public COpt Opt; } internal sealed class Issue { public string Title, Detail; public bool Danger; public readonly List Fixes = new(); } internal static class Advisor { public static float F(Dictionary d, string k, float def) => d != null && d.TryGetValue(k, out string v) && float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out float f) ? f : def; private static void Add(List list, Dictionary byId, bool danger, string title, string detail, params string[] fixes) { Issue i = new() { Danger = danger, Title = title, Detail = detail }; foreach (string f in fixes) { if (f.StartsWith("act:", StringComparison.Ordinal)) { string[] p = f[4..].Split('|'); i.Fixes.Add(new Fix { Act = p[0], Label = p.Length > 1 ? p[1] : p[0] }); } else if (byId.TryGetValue(f, out COpt o)) i.Fixes.Add(new Fix { Opt = o, Label = o.Name }); } list.Add(i); } public static List Check(Dictionary d, Dictionary byId) { List list = new(); if (d == null) return list; CultureInfo ci = CultureInfo.InvariantCulture; if (F(d, "alive", 1) < 0.5f) { Add(list, byId, true, "Your character is dead", "Nothing can save this run now."); return list; } if (F(d, "arrest", 0) > 0.5f) Add(list, byId, true, "Your heart has stopped", "Cardiac arrest. Heal right away or you won't come back.", "heal", "GodMode"); else if (F(d, "crit", 0) > 0.5f) Add(list, byId, true, "You're dying", "Your body is failing. Heal now, and God Mode keeps you alive.", "heal", "GodMode"); float bleed = F(d, "bleed", 0); if (bleed > 0.01f) Add(list, byId, bleed > 0.25f, bleed > 0.25f ? "Bleeding badly" : "Bleeding", "Losing " + bleed.ToString("0.00", ci) + " litres of blood a minute.", "NoBleeding", "heal"); float blood = F(d, "blood", 100); if (blood < 70f) Add(list, byId, blood < 45f, "Low blood", "Blood is at " + blood.ToString("0", ci) + "%. Under 25% gets very dangerous.", "heal", "FasterHealing"); float oxy = F(d, "oxy", 100); if (oxy < 85f) Add(list, byId, oxy < 70f, "Low oxygen", "Blood oxygen is at " + oxy.ToString("0", ci) + "%.", "UnlimitedOxygen", "heal"); float brain = F(d, "brain", 100); if (brain < 80f) Add(list, byId, brain < 50f, "Brain damage", "Brain health is " + brain.ToString("0", ci) + ". At 0 you die.", "heal", "GodMode"); float consc = F(d, "consc", 100); if (consc < 60f) Add(list, byId, consc < 40f, "Losing consciousness", "Consciousness is at " + consc.ToString("0", ci) + "%.", "heal", "NoPain"); float pain = F(d, "pain", 0); if (pain > 50f) Add(list, byId, pain > 75f, "In a lot of pain", "Pain is at " + pain.ToString("0", ci) + "%. It knocks you out and drags your mood down.", "NoPain"); float temp = F(d, "temp", 37); if (temp < 34f || temp > 39.5f) Add(list, byId, temp < 30f || temp > 41f, temp < 34f ? "Too cold" : "Overheating", "Body temperature is " + temp.ToString("0.0", ci) + " °C.", "StableTemperature"); float hunger = F(d, "hunger", 100); if (hunger < 25f) Add(list, byId, hunger < 10f, "Starving", "Hunger is at " + hunger.ToString("0", ci) + ".", "NoHunger"); float thirst = F(d, "thirst", 100); if (thirst < 25f) Add(list, byId, thirst < 10f, "Dehydrated", "Thirst is at " + thirst.ToString("0", ci) + ".", "NoThirst"); float energy = F(d, "energy", 100); if (energy < 20f) Add(list, byId, energy < 5f, "Exhausted", "Energy is at " + energy.ToString("0", ci) + "%.", "NoTiredness"); float infect = F(d, "infect", 0); if (infect >= 25f) Add(list, byId, infect >= 60f, "Infected wound", "Worst infection is at " + infect.ToString("0", ci) + ".", "NoInfection", "heal"); float sick = F(d, "sick", 0); if (sick > 40f) Add(list, byId, sick > 70f, "Sick", "Sickness is at " + sick.ToString("0", ci) + "%.", "NoSickness"); float venom = F(d, "venom", 0); if (venom > 0.5f) Add(list, byId, venom > 300f, "Poisoned", "Toxin at " + (venom * 0.1f).ToString("0.0", ci) + " ppm.", "NoSickness"); float rad = F(d, "rad", 0); if (rad > 3f) Add(list, byId, rad > 7.5f, "Radiation sickness", "Radiation dose is " + rad.ToString("0.0", ci) + " gy.", "NoRadiation"); int broken = (int)F(d, "broken", 0), disloc = (int)F(d, "disloc", 0), shrap = (int)F(d, "shrapnel", 0), missing = (int)F(d, "missing", 0); if (broken + disloc > 0) { List parts = new(); if (broken > 0) parts.Add(broken + " broken"); if (disloc > 0) parts.Add(disloc + " dislocated"); Add(list, byId, false, "Injured limbs", string.Join(", ", parts) + ".", "heal"); } if (shrap > 0) Add(list, byId, false, "Shrapnel", shrap + " limb" + (shrap == 1 ? " has" : "s have") + " shrapnel in it.", "heal"); if (missing > 0) Add(list, byId, false, "Missing limbs", missing + " limb" + (missing == 1 ? " is" : "s are") + " gone.", "limbs"); float mood = F(d, "mood", 0); if (mood < -40f) Add(list, byId, mood <= -75f, "Very low mood", "Mood is " + mood.ToString("0", ci) + ". This low, your character may hurt themselves.", "act:moodmax|Max Mood", "MoodLock"); if (F(d, "radline", 0) > 0.5f) Add(list, byId, true, "The radiation line is here", "Get out of this layer or stop the line.", "PauseRadiation", "exit"); if (F(d, "enc", 0) > 0.5f) Add(list, byId, false, "Carrying too much", "Over-encumbered: slower, and tiring faster.", "UnlimitedCarry"); return list.Where(i => i.Danger).Concat(list.Where(i => !i.Danger)).ToList(); } } internal sealed class KnownMod { public int Id; public string Dll, Name, Ts; public KnownMod(int id, string dll, string name, string ts) { Id = id; Dll = dll; Name = name; Ts = ts; } public string Page => "https://www.nexusmods.com/scavprototype/mods/" + Id; } internal static class Mods { public static readonly KnownMod[] All = { new(874, "CUCheats.dll", "CU Cheats - Ultra Paradise", "CUCheats"), new(885, "SaveAnywhere.dll", "Save Anywhere", "SaveAnywhere"), new(894, "NoDurability.dll", "No Durability", "NoDurability"), new(915, "PickYourNumber.dll", "Pick Your Number, Age and Height", "PickYourNumber"), new(897, "GetStinky.dll", "Get Stinky", "GetStinky"), new(1183, "ThighHighsRevamped.dll", "Thigh Highs Revamped", "ThighHighsRevamped"), new(1059, "AlwaysGivenAChance.dll", "Always Given A Chance", "AlwaysGivenAChance"), new(999, "CustomDeathScreen.dll", "Custom Death Screen", null), new(998, "NoMoreSoundCannons.dll", "No More Sound Cannons", "NoMoreSoundCannons"), new(1190, "ControllerSupport.dll", "Controller Support", "ControllerSupport"), new(1200, "HatsHatsHats.dll", "Hats Hats Hats", "HatsHatsHats"), new(1204, "SpeedrunCU.dll", "Speed Run CU", "SpeedRunCU"), new(1214, "IRegretNothing.dll", "I Regret Nothing", "IRegretNothing"), new(1233, "Interpretation.dll", "Interpretation - Expie and Milky Reskin", "Interpretation"), }; public static string Plugins(string game) => Path.Combine(game, "BepInEx", "plugins"); public static readonly (int id, string why)[] Recommended = { (885, "Save your run anywhere, not just at the usual spots"), (1190, "Play with an Xbox or PlayStation controller"), (894, "Your gear and tools stop wearing out"), (915, "Pick your experiment number, age and height"), (1059, "Your last stand always gets its chance"), (1200, "A Santa hat on new runs, and a traffic cone to find"), }; public static bool SteamDeck { get { try { foreach (string f in new[] { "/sys/devices/virtual/dmi/id/board_vendor", "/sys/devices/virtual/dmi/id/sys_vendor" }) if (File.Exists(f) && File.ReadAllText(f).Trim() == "Valve") return true; } catch (Exception) { } return false; } } public static string Why(int id) { if (id == 1190 && SteamDeck) return "Recommended for the Steam Deck: full controller support in game"; foreach (var r in Recommended) if (r.id == id) return r.why; return null; } public static string Downloads { get { string d = null; try { string f = Path.Combine(Dirs.Home, ".config", "user-dirs.dirs"); if (File.Exists(f)) foreach (string line in File.ReadAllLines(f)) { Match m = Regex.Match(line, "^XDG_DOWNLOAD_DIR=\"(.+)\"$"); if (m.Success) d = m.Groups[1].Value.Replace("$HOME", Dirs.Home); } } catch (Exception) { } if (d == null || !Directory.Exists(d)) d = Path.Combine(Dirs.Home, "Downloads"); return Directory.Exists(d) ? d : null; } } private static IEnumerable Find(string game, string dll) { string p = Plugins(game); if (!Directory.Exists(p)) return Enumerable.Empty(); return Directory.EnumerateFiles(p, "*.dll", SearchOption.AllDirectories).Where(f => string.Equals(Path.GetFileName(f), dll, StringComparison.OrdinalIgnoreCase)); } public static bool Installed(string game, KnownMod m) { try { return Game.IsGameDir(game) && Find(game, m.Dll).Any(); } catch (Exception) { return false; } } public static KnownMod Identify(string zip) { try { FileInfo fi = new(zip); if (!fi.Exists || fi.Length > 200L * 1024 * 1024) return null; using ZipArchive za = ZipFile.OpenRead(zip); KnownMod hit = null; foreach (ZipArchiveEntry e in za.Entries) { if (e.FullName.Replace('\\', '/').Contains("ModLoader/", StringComparison.OrdinalIgnoreCase)) return null; foreach (KnownMod m in All) if (string.Equals(e.Name, m.Dll, StringComparison.OrdinalIgnoreCase)) hit = m; } return hit; } catch (Exception) { return null; } } public static bool SameAsInstalled(string game, string zip, KnownMod m) { try { using ZipArchive za = ZipFile.OpenRead(zip); ZipArchiveEntry e = za.Entries.FirstOrDefault(x => string.Equals(x.Name, m.Dll, StringComparison.OrdinalIgnoreCase)); if (e == null) return false; using Stream s = e.Open(); using MemoryStream ms = new(); s.CopyTo(ms); string h = Http.Sha(ms.ToArray()); return Find(game, m.Dll).Any(f => Http.Sha(f) == h); } catch (Exception) { return false; } } private static int Segment(string p, string seg) { if (p.StartsWith(seg, StringComparison.OrdinalIgnoreCase)) return 0; int i = p.IndexOf("/" + seg, StringComparison.OrdinalIgnoreCase); return i < 0 ? -1 : i + 1; } public static string Install(string zip, string game, out KnownMod mod) { mod = Identify(zip); if (mod == null) return "that zip isn't one of casualexpie's BepInEx mods"; if (!Game.IsGameDir(game)) return "the game folder wasn't found"; if (!Game.BepInstalled(game)) return "install BepInEx first (Game Setup tab)"; if (Game.GameRunning()) return "close the game first"; string root = Path.GetFullPath(Plugins(game)).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; List<(ZipArchiveEntry e, string target)> plan = new(); using (ZipArchive za = ZipFile.OpenRead(zip)) { bool tsZip = za.GetEntry("manifest.json") != null; string tsDir = Thunderstore.Owner + "-" + (mod.Ts ?? Path.GetFileNameWithoutExtension(mod.Dll)) + "/"; foreach (ZipArchiveEntry e in za.Entries) { if (string.IsNullOrEmpty(e.Name)) continue; string p = e.FullName.Replace('\\', '/'); if (p.Contains("../") || p.StartsWith('/') || p.Contains(':')) return "that zip has unsafe file paths, so it wasn't installed"; if (e.Name.StartsWith("README", StringComparison.OrdinalIgnoreCase) && e.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) continue; int bi = Segment(p, "BepInEx/plugins/"); string rel; if (bi >= 0) rel = p[(bi + "BepInEx/plugins/".Length)..]; else if (Segment(p, "BepInEx/") >= 0) continue; else if (tsZip) rel = tsDir + p; else rel = e.Name; string target = Path.GetFullPath(Path.Combine(root, rel)); if (!target.StartsWith(root, StringComparison.Ordinal)) continue; plan.Add((e, target)); } if (plan.Count == 0) return "there was nothing to install in that zip"; foreach (var (e, target) in plan) { Directory.CreateDirectory(Path.GetDirectoryName(target)); e.ExtractToFile(target, true); } } foreach (string f in Find(game, mod.Dll).ToList()) if (!plan.Any(x => string.Equals(Path.GetFullPath(f), x.target, StringComparison.Ordinal))) { try { File.Delete(f); } catch (Exception) { } } return null; } public static string Remove(string game, KnownMod m) { if (Game.GameRunning()) return "close the game first"; int n = 0; foreach (string f in Find(game, m.Dll).ToList()) { File.Delete(f); n++; } return n == 0 ? m.Name + " wasn't installed" : null; } } internal static class KeyMap { public static string Unity(Avalonia.Input.Key k) { if (k >= Avalonia.Input.Key.NumPad0 && k <= Avalonia.Input.Key.NumPad9) return "Keypad" + (k - Avalonia.Input.Key.NumPad0); if (k >= Avalonia.Input.Key.D0 && k <= Avalonia.Input.Key.D9) return "Alpha" + (k - Avalonia.Input.Key.D0); if (k >= Avalonia.Input.Key.A && k <= Avalonia.Input.Key.Z) return k.ToString(); if (k >= Avalonia.Input.Key.F1 && k <= Avalonia.Input.Key.F15) return k.ToString(); return k switch { Avalonia.Input.Key.Insert => "Insert", Avalonia.Input.Key.Home => "Home", Avalonia.Input.Key.End => "End", Avalonia.Input.Key.PageUp => "PageUp", Avalonia.Input.Key.PageDown => "PageDown", Avalonia.Input.Key.Up => "UpArrow", Avalonia.Input.Key.Down => "DownArrow", Avalonia.Input.Key.Left => "LeftArrow", Avalonia.Input.Key.Right => "RightArrow", Avalonia.Input.Key.Decimal => "KeypadPeriod", Avalonia.Input.Key.Add => "KeypadPlus", Avalonia.Input.Key.Subtract => "KeypadMinus", Avalonia.Input.Key.Multiply => "KeypadMultiply", Avalonia.Input.Key.Divide => "KeypadDivide", Avalonia.Input.Key.Space => "Space", Avalonia.Input.Key.Tab => "Tab", Avalonia.Input.Key.Enter => "Return", Avalonia.Input.Key.OemTilde => "BackQuote", Avalonia.Input.Key.OemMinus => "Minus", Avalonia.Input.Key.OemPlus => "Equals", Avalonia.Input.Key.OemOpenBrackets => "LeftBracket", Avalonia.Input.Key.OemCloseBrackets => "RightBracket", Avalonia.Input.Key.OemSemicolon => "Semicolon", Avalonia.Input.Key.OemQuotes => "Quote", Avalonia.Input.Key.OemComma => "Comma", Avalonia.Input.Key.OemPeriod => "Period", Avalonia.Input.Key.OemQuestion => "Slash", Avalonia.Input.Key.OemPipe => "Backslash", _ => null, }; } } }