using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace UltraParadise.Linux { internal sealed class TsPackage { public string Name, Version, Url, Icon, Description; public long Downloads; public bool Deprecated; public Avalonia.Media.Imaging.Bitmap Image; } internal static class Thunderstore { public const string Owner = "casualexpie"; public const string Community = "casualties-unknown"; public const string TeamUrl = "https://thunderstore.io/c/" + Community + "/p/" + Owner + "/"; private const string Api = "https://thunderstore.io/c/" + Community + "/api/v1/package/"; private static string CacheFile => Path.Combine(Dirs.Cache, "thunderstore.txt"); public static string PageUrl(string name) => TeamUrl + name + "/"; public static string InstallLink(TsPackage p) => "ror2mm://v1/install/thunderstore.io/" + Owner + "/" + p.Name + "/" + p.Version + "/"; public static bool SafeUrl(string u) => u != null && (u.StartsWith("https://thunderstore.io/", StringComparison.Ordinal) || u.StartsWith("ror2mm://v1/install/thunderstore.io/", StringComparison.Ordinal)); public static Dictionary Load(out DateTime when) { when = DateTime.MinValue; try { if (!File.Exists(CacheFile)) return null; when = File.GetLastWriteTimeUtc(CacheFile); Dictionary d = new(StringComparer.OrdinalIgnoreCase); foreach (string line in File.ReadAllLines(CacheFile)) { string[] f = line.Split('\t'); if (f.Length < 5) continue; TsPackage p = new() { Name = f[0], Version = f[1], Deprecated = f[3] == "1", Url = f[4], Icon = f.Length > 5 ? f[5] : null, Description = f.Length > 6 ? f[6] : null }; long.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out p.Downloads); if (Safe(p)) d[p.Name] = p; } return d.Count > 0 ? d : null; } catch (Exception) { return null; } } public static async Task> Fetch() { using HttpRequestMessage req = new(HttpMethod.Get, Api); req.Headers.Accept.ParseAdd("application/json"); using HttpResponseMessage res = await Http.Client.SendAsync(req); res.EnsureSuccessStatusCode(); string json = await res.Content.ReadAsStringAsync(); using JsonDocument doc = JsonDocument.Parse(json); if (doc.RootElement.ValueKind != JsonValueKind.Array) return null; Dictionary d = new(StringComparer.OrdinalIgnoreCase); static string S(JsonElement e, string k) => e.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; foreach (JsonElement n in doc.RootElement.EnumerateArray()) { if (S(n, "owner") != Owner) continue; if (!n.TryGetProperty("versions", out JsonElement vers) || vers.ValueKind != JsonValueKind.Array || vers.GetArrayLength() == 0) continue; TsPackage p = new() { Name = S(n, "name"), Url = S(n, "package_url"), Deprecated = n.TryGetProperty("is_deprecated", out JsonElement dep) && dep.ValueKind == JsonValueKind.True, Version = S(vers[0], "version_number"), Icon = S(vers[0], "icon"), Description = S(vers[0], "description"), }; foreach (JsonElement v in vers.EnumerateArray()) if (v.TryGetProperty("downloads", out JsonElement dl) && dl.ValueKind == JsonValueKind.Number && dl.TryGetInt64(out long x)) p.Downloads += x; if (Safe(p)) d[p.Name] = p; } try { Private.Dir(Dirs.Cache); File.WriteAllText(CacheFile, string.Concat(d.Values.Select(p => p.Name + "\t" + p.Version + "\t" + p.Downloads.ToString(CultureInfo.InvariantCulture) + "\t" + (p.Deprecated ? "1" : "0") + "\t" + p.Url + "\t" + (p.Icon ?? "") + "\t" + (p.Description ?? "") + "\n"))); } catch (Exception) { } return d; } private static bool Safe(TsPackage p) { if (string.IsNullOrEmpty(p.Name) || string.IsNullOrEmpty(p.Version)) return false; if (!Regex.IsMatch(p.Name, "^[A-Za-z0-9_]{1,64}$") || !Regex.IsMatch(p.Version, "^\\d+\\.\\d+\\.\\d+$")) return false; if (p.Url == null || !p.Url.StartsWith("https://thunderstore.io/", StringComparison.Ordinal)) p.Url = PageUrl(p.Name); if (string.IsNullOrEmpty(p.Icon) || !Uri.TryCreate(p.Icon, UriKind.Absolute, out Uri iu) || iu.Scheme != "https" || !iu.Host.EndsWith(".thunderstore.io", StringComparison.OrdinalIgnoreCase)) p.Icon = null; p.Description = Regex.Replace(p.Description ?? "", "\\s+", " ").Trim(); if (p.Description.Length > 300) p.Description = p.Description[..300]; return true; } public static int Compare(string a, string b) { if (!System.Version.TryParse(a ?? "", out Version va) || !System.Version.TryParse(b ?? "", out Version vb)) return 0; return va.CompareTo(vb); } } internal sealed class MgrProfile { public string Manager, Name, Dir; public readonly HashSet Dlls = new(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Versions = new(StringComparer.OrdinalIgnoreCase); } internal sealed class ModManager { public string Name; public readonly List Profiles = new(); } internal static class ModManagers { public static List Scan() { List list = new(); string h = Dirs.Home; string xc = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); string xd = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); string config = string.IsNullOrEmpty(xc) ? Path.Combine(h, ".config") : xc; string data = string.IsNullOrEmpty(xd) ? Path.Combine(h, ".local", "share") : xd; string mac = Path.Combine(h, "Library", "Application Support"); string r2 = Path.Combine("r2modmanPlus-local", "CasualtiesUnknown", "profiles"); string gale = Path.Combine("com.kesomannen.gale", Thunderstore.Community, "profiles"); Try(list, "r2modman", Path.Combine(config, r2), Path.Combine(h, ".var", "app", "com.github.ebkr.r2modman", "config", r2), Path.Combine(mac, r2)); Try(list, "Gale", Path.Combine(data, gale), Path.Combine(h, ".var", "app", "com.kesomannen.gale", "data", gale), Path.Combine(mac, gale)); return list; } public static string Handler() { if (OperatingSystem.IsMacOS()) return null; try { ProcessStartInfo si = new("xdg-mime") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; si.ArgumentList.Add("query"); si.ArgumentList.Add("default"); si.ArgumentList.Add("x-scheme-handler/ror2mm"); using Process p = Process.Start(si); if (p == null) return null; string o = p.StandardOutput.ReadToEnd().Trim().ToLowerInvariant(); if (!p.WaitForExit(3000)) { try { p.Kill(); } catch (Exception) { } return null; } if (o.Length == 0) return null; if (o.Contains("gale")) return "Gale"; if (o.Contains("r2modman")) return "r2modman"; return "your mod manager"; } catch (Exception) { return null; } } private static void Try(List list, string name, params string[] roots) { ModManager m = null; foreach (string profiles in roots) { try { if (!Directory.Exists(profiles)) continue; m ??= new ModManager { Name = name }; foreach (string dir in Directory.GetDirectories(profiles).Take(50)) { MgrProfile p = new() { Manager = name, Name = Path.GetFileName(dir), Dir = dir }; ScanProfile(p); m.Profiles.Add(p); } } catch (Exception) { } } if (m != null) list.Add(m); } private static void ScanProfile(MgrProfile p) { string plugins = Path.Combine(p.Dir, "BepInEx", "plugins"); if (!Directory.Exists(plugins)) return; int seen = 0; Stack todo = new(); todo.Push(plugins); while (todo.Count > 0 && seen < 4000) { string d = todo.Pop(); string[] files, dirs; try { files = Directory.GetFiles(d); dirs = Directory.GetDirectories(d); } catch (Exception) { continue; } foreach (string f in files) { seen++; if (f.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) p.Dlls.Add(Path.GetFileName(f)); } foreach (string sub in dirs) { string n = Path.GetFileName(sub); if (n.StartsWith(Thunderstore.Owner + "-", StringComparison.OrdinalIgnoreCase)) { string v = ManifestVersion(Path.Combine(sub, "manifest.json")); if (v != null) p.Versions[n[(Thunderstore.Owner.Length + 1)..]] = v; } todo.Push(sub); } } } private static string ManifestVersion(string file) { try { if (!File.Exists(file) || new FileInfo(file).Length > 64 * 1024) return null; Match m = Regex.Match(File.ReadAllText(file), "\"version_number\"\\s*:\\s*\"(\\d+\\.\\d+\\.\\d+)\""); return m.Success ? m.Groups[1].Value : null; } catch (Exception) { return null; } } public static MgrProfile Find(List list, KnownMod k) { if (list == null) return null; foreach (ModManager m in list) foreach (MgrProfile p in m.Profiles) if (p.Dlls.Contains(k.Dll)) return p; return null; } public static int Count(ModManager m) => Mods.All.Count(k => m.Profiles.Any(p => p.Dlls.Contains(k.Dll))); } }