using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using Microsoft.Win32; namespace UltraParadise { internal sealed class TsPackage { public string Name, Version, Url, Icon, Description; public long Downloads; public bool Deprecated; public DateTime Updated; public System.Drawing.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 Folder { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"); } } private static string CacheFile { get { return Path.Combine(Folder, "thunderstore.txt"); } } public static string PageUrl(string name) { return TeamUrl + name + "/"; } public static string InstallLink(TsPackage p) { return "ror2mm://v1/install/thunderstore.io/" + Owner + "/" + p.Name + "/" + p.Version + "/"; } public static Dictionary Load(out DateTime when) { when = DateTime.MinValue; try { if (!File.Exists(CacheFile)) return null; when = File.GetLastWriteTimeUtc(CacheFile); Dictionary d = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string line in File.ReadAllLines(CacheFile)) { string[] f = line.Split('\t'); if (f.Length < 5) continue; TsPackage p = new TsPackage(); p.Name = f[0]; p.Version = f[1]; long.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out p.Downloads); p.Deprecated = f[3] == "1"; p.Url = f[4]; long t; if (f.Length > 5 && long.TryParse(f[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out t)) p.Updated = new DateTime(t, DateTimeKind.Utc); if (f.Length > 6) p.Icon = f[6]; if (f.Length > 7) p.Description = f[7]; if (Safe(p)) d[p.Name] = p; } return d.Count > 0 ? d : null; } catch (Exception) { return null; } } public static Dictionary Fetch() { ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Api); req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; req.Accept = "application/json"; req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; req.Timeout = 20000; req.ReadWriteTimeout = 20000; string json; using (WebResponse res = req.GetResponse()) using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) json = r.ReadToEnd(); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); js.MaxJsonLength = 64 * 1024 * 1024; object[] all = js.DeserializeObject(json) as object[]; if (all == null) return null; Dictionary d = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (object o in all) { Dictionary n = o as Dictionary; if (n == null || Str(n, "owner") != Owner) continue; object[] vers = n.ContainsKey("versions") ? n["versions"] as object[] : null; if (vers == null || vers.Length == 0) continue; TsPackage p = new TsPackage(); p.Name = Str(n, "name"); p.Url = Str(n, "package_url"); p.Deprecated = n.ContainsKey("is_deprecated") && n["is_deprecated"] is bool && (bool)n["is_deprecated"]; Dictionary latest = vers[0] as Dictionary; if (latest == null) continue; p.Version = Str(latest, "version_number"); p.Icon = Str(latest, "icon"); p.Description = Str(latest, "description"); foreach (object vo in vers) { Dictionary v = vo as Dictionary; if (v == null) continue; object dl; if (v.TryGetValue("downloads", out dl) && dl != null) { try { p.Downloads += Convert.ToInt64(dl, CultureInfo.InvariantCulture); } catch (Exception) { } } } DateTime when; if (DateTime.TryParse(Str(latest, "date_created") ?? Str(n, "date_updated") ?? "", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out when)) p.Updated = when; if (Safe(p)) d[p.Name] = p; } try { Directory.CreateDirectory(Folder); StringBuilder sb = new StringBuilder(); foreach (TsPackage p in d.Values) sb.Append(p.Name).Append('\t').Append(p.Version).Append('\t').Append(p.Downloads.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(p.Deprecated ? "1" : "0").Append('\t').Append(p.Url).Append('\t').Append(p.Updated.Ticks.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(p.Icon ?? "").Append('\t').Append(p.Description ?? "").Append('\n'); File.WriteAllText(CacheFile, sb.ToString()); } catch (Exception) { } return d; } private static bool Safe(TsPackage p) { if (string.IsNullOrEmpty(p.Name) || string.IsNullOrEmpty(p.Version)) return false; if (!System.Text.RegularExpressions.Regex.IsMatch(p.Name, "^[A-Za-z0-9_]{1,64}$")) return false; if (!System.Text.RegularExpressions.Regex.IsMatch(p.Version, "^\\d+\\.\\d+\\.\\d+$")) return false; if (string.IsNullOrEmpty(p.Url) || !p.Url.StartsWith("https://thunderstore.io/", StringComparison.Ordinal)) p.Url = PageUrl(p.Name); Uri iu; if (string.IsNullOrEmpty(p.Icon) || !Uri.TryCreate(p.Icon, UriKind.Absolute, out iu) || iu.Scheme != "https" || !iu.Host.EndsWith(".thunderstore.io", StringComparison.OrdinalIgnoreCase)) p.Icon = null; p.Description = System.Text.RegularExpressions.Regex.Replace(p.Description ?? "", "\\s+", " ").Trim(); if (p.Description.Length > 300) p.Description = p.Description.Substring(0, 300); return true; } public static int Compare(string a, string b) { Version va, vb; if (!System.Version.TryParse(a ?? "", out va) || !System.Version.TryParse(b ?? "", out vb)) return 0; return va.CompareTo(vb); } private static string Str(Dictionary d, string k) { object v; return d.TryGetValue(k, out v) && v != null ? v.ToString() : null; } } internal sealed class MgrProfile { public string Manager, Name, Dir; public readonly HashSet Dlls = new HashSet(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Versions = new Dictionary(StringComparer.OrdinalIgnoreCase); } internal sealed class ModManager { public string Name, Data; public readonly List Profiles = new List(); } internal static class ModManagers { public static List Scan() { List list = new List(); string app = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); Try(list, "r2modman", Path.Combine(app, @"r2modmanPlus-local\CasualtiesUnknown\profiles")); Try(list, "Thunderstore Mod Manager", Path.Combine(app, @"Thunderstore Mod Manager\DataFolder\CasualtiesUnknown\profiles")); Try(list, "Gale", Path.Combine(app, @"com.kesomannen.gale\" + Thunderstore.Community + @"\profiles")); return list; } public static string Handler() { try { using (RegistryKey k = Registry.ClassesRoot.OpenSubKey(@"ror2mm\shell\open\command")) { string cmd = k != null ? k.GetValue(null) as string : null; if (string.IsNullOrEmpty(cmd)) return null; string c = cmd.ToLowerInvariant(); string exe = cmd.Trim(); if (exe.StartsWith("\"")) { int q = exe.IndexOf('"', 1); exe = q > 0 ? exe.Substring(1, q - 1) : exe.Trim('"'); } else { int sp = exe.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); if (sp > 0) exe = exe.Substring(0, sp + 4); } if (!File.Exists(exe)) return null; if (c.Contains("gale")) return "Gale"; if (c.Contains("thunderstore")) return "Thunderstore Mod Manager"; if (c.Contains("r2modman")) return "r2modman"; return "your mod manager"; } } catch (Exception) { return null; } } private static void Try(List list, string name, string profiles) { try { if (!Directory.Exists(profiles)) return; ModManager m = new ModManager(); m.Name = name; m.Data = profiles; foreach (string dir in Directory.GetDirectories(profiles)) { MgrProfile p = new MgrProfile(); p.Manager = name; p.Name = Path.GetFileName(dir); p.Dir = dir; ScanProfile(p); m.Profiles.Add(p); if (m.Profiles.Count >= 50) break; } list.Add(m); } catch (Exception) { } } 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 Stack(); 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.Substring(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; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.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) { int n = 0; HashSet seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (MgrProfile p in m.Profiles) foreach (KnownMod k in Installer.Mods) if (p.Dlls.Contains(k.Dll) && seen.Add(k.Dll)) n++; return n; } } }