cu-trainer/Ultra Paradise Application/src/Thunderstore.cs
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Globalization; |
| 4 | using System.IO; |
| 5 | using System.Net; |
| 6 | using System.Text; |
| 7 | using Microsoft.Win32; |
| 8 | |
| 9 | namespace UltraParadise |
| 10 | { |
| 11 | internal sealed class TsPackage |
| 12 | { |
| 13 | public string Name, Version, Url, Icon, Description; |
| 14 | public long Downloads; |
| 15 | public bool Deprecated; |
| 16 | public DateTime Updated; |
| 17 | public System.Drawing.Bitmap Image; |
| 18 | } |
| 19 | |
| 20 | internal static class Thunderstore |
| 21 | { |
| 22 | public const string Owner = "casualexpie"; |
| 23 | public const string Community = "casualties-unknown"; |
| 24 | public const string TeamUrl = "https://thunderstore.io/c/" + Community + "/p/" + Owner + "/"; |
| 25 | private const string Api = "https://thunderstore.io/c/" + Community + "/api/v1/package/"; |
| 26 | |
| 27 | private static string Folder { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"); } } |
| 28 | private static string CacheFile { get { return Path.Combine(Folder, "thunderstore.txt"); } } |
| 29 | |
| 30 | public static string PageUrl(string name) { return TeamUrl + name + "/"; } |
| 31 | |
| 32 | public static string InstallLink(TsPackage p) |
| 33 | { |
| 34 | return "ror2mm://v1/install/thunderstore.io/" + Owner + "/" + p.Name + "/" + p.Version + "/"; |
| 35 | } |
| 36 | |
| 37 | public static Dictionary<string, TsPackage> Load(out DateTime when) |
| 38 | { |
| 39 | when = DateTime.MinValue; |
| 40 | try |
| 41 | { |
| 42 | if (!File.Exists(CacheFile)) return null; |
| 43 | when = File.GetLastWriteTimeUtc(CacheFile); |
| 44 | Dictionary<string, TsPackage> d = new Dictionary<string, TsPackage>(StringComparer.OrdinalIgnoreCase); |
| 45 | foreach (string line in File.ReadAllLines(CacheFile)) |
| 46 | { |
| 47 | string[] f = line.Split('\t'); |
| 48 | if (f.Length < 5) continue; |
| 49 | TsPackage p = new TsPackage(); |
| 50 | p.Name = f[0]; |
| 51 | p.Version = f[1]; |
| 52 | long.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out p.Downloads); |
| 53 | p.Deprecated = f[3] == "1"; |
| 54 | p.Url = f[4]; |
| 55 | long t; |
| 56 | if (f.Length > 5 && long.TryParse(f[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out t)) p.Updated = new DateTime(t, DateTimeKind.Utc); |
| 57 | if (f.Length > 6) p.Icon = f[6]; |
| 58 | if (f.Length > 7) p.Description = f[7]; |
| 59 | if (Safe(p)) d[p.Name] = p; |
| 60 | } |
| 61 | return d.Count > 0 ? d : null; |
| 62 | } |
| 63 | catch (Exception) { return null; } |
| 64 | } |
| 65 | |
| 66 | public static Dictionary<string, TsPackage> Fetch() |
| 67 | { |
| 68 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 69 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Api); |
| 70 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 71 | req.Accept = "application/json"; |
| 72 | req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; |
| 73 | req.Timeout = 20000; |
| 74 | req.ReadWriteTimeout = 20000; |
| 75 | string json; |
| 76 | using (WebResponse res = req.GetResponse()) |
| 77 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 78 | json = r.ReadToEnd(); |
| 79 | System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); |
| 80 | js.MaxJsonLength = 64 * 1024 * 1024; |
| 81 | object[] all = js.DeserializeObject(json) as object[]; |
| 82 | if (all == null) return null; |
| 83 | Dictionary<string, TsPackage> d = new Dictionary<string, TsPackage>(StringComparer.OrdinalIgnoreCase); |
| 84 | foreach (object o in all) |
| 85 | { |
| 86 | Dictionary<string, object> n = o as Dictionary<string, object>; |
| 87 | if (n == null || Str(n, "owner") != Owner) continue; |
| 88 | object[] vers = n.ContainsKey("versions") ? n["versions"] as object[] : null; |
| 89 | if (vers == null || vers.Length == 0) continue; |
| 90 | TsPackage p = new TsPackage(); |
| 91 | p.Name = Str(n, "name"); |
| 92 | p.Url = Str(n, "package_url"); |
| 93 | p.Deprecated = n.ContainsKey("is_deprecated") && n["is_deprecated"] is bool && (bool)n["is_deprecated"]; |
| 94 | Dictionary<string, object> latest = vers[0] as Dictionary<string, object>; |
| 95 | if (latest == null) continue; |
| 96 | p.Version = Str(latest, "version_number"); |
| 97 | p.Icon = Str(latest, "icon"); |
| 98 | p.Description = Str(latest, "description"); |
| 99 | foreach (object vo in vers) |
| 100 | { |
| 101 | Dictionary<string, object> v = vo as Dictionary<string, object>; |
| 102 | if (v == null) continue; |
| 103 | object dl; |
| 104 | if (v.TryGetValue("downloads", out dl) && dl != null) { try { p.Downloads += Convert.ToInt64(dl, CultureInfo.InvariantCulture); } catch (Exception) { } } |
| 105 | } |
| 106 | DateTime when; |
| 107 | if (DateTime.TryParse(Str(latest, "date_created") ?? Str(n, "date_updated") ?? "", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out when)) p.Updated = when; |
| 108 | if (Safe(p)) d[p.Name] = p; |
| 109 | } |
| 110 | try |
| 111 | { |
| 112 | Directory.CreateDirectory(Folder); |
| 113 | StringBuilder sb = new StringBuilder(); |
| 114 | foreach (TsPackage p in d.Values) |
| 115 | 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'); |
| 116 | File.WriteAllText(CacheFile, sb.ToString()); |
| 117 | } |
| 118 | catch (Exception) { } |
| 119 | return d; |
| 120 | } |
| 121 | |
| 122 | private static bool Safe(TsPackage p) |
| 123 | { |
| 124 | if (string.IsNullOrEmpty(p.Name) || string.IsNullOrEmpty(p.Version)) return false; |
| 125 | if (!System.Text.RegularExpressions.Regex.IsMatch(p.Name, "^[A-Za-z0-9_]{1,64}$")) return false; |
| 126 | if (!System.Text.RegularExpressions.Regex.IsMatch(p.Version, "^\\d+\\.\\d+\\.\\d+$")) return false; |
| 127 | if (string.IsNullOrEmpty(p.Url) || !p.Url.StartsWith("https://thunderstore.io/", StringComparison.Ordinal)) p.Url = PageUrl(p.Name); |
| 128 | Uri iu; |
| 129 | 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; |
| 130 | p.Description = System.Text.RegularExpressions.Regex.Replace(p.Description ?? "", "\\s+", " ").Trim(); |
| 131 | if (p.Description.Length > 300) p.Description = p.Description.Substring(0, 300); |
| 132 | return true; |
| 133 | } |
| 134 | |
| 135 | public static int Compare(string a, string b) |
| 136 | { |
| 137 | Version va, vb; |
| 138 | if (!System.Version.TryParse(a ?? "", out va) || !System.Version.TryParse(b ?? "", out vb)) return 0; |
| 139 | return va.CompareTo(vb); |
| 140 | } |
| 141 | |
| 142 | private static string Str(Dictionary<string, object> d, string k) |
| 143 | { |
| 144 | object v; |
| 145 | return d.TryGetValue(k, out v) && v != null ? v.ToString() : null; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | internal sealed class MgrProfile |
| 150 | { |
| 151 | public string Manager, Name, Dir; |
| 152 | public readonly HashSet<string> Dlls = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| 153 | public readonly Dictionary<string, string> Versions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| 154 | } |
| 155 | |
| 156 | internal sealed class ModManager |
| 157 | { |
| 158 | public string Name, Data; |
| 159 | public readonly List<MgrProfile> Profiles = new List<MgrProfile>(); |
| 160 | } |
| 161 | |
| 162 | internal static class ModManagers |
| 163 | { |
| 164 | public static List<ModManager> Scan() |
| 165 | { |
| 166 | List<ModManager> list = new List<ModManager>(); |
| 167 | string app = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); |
| 168 | Try(list, "r2modman", Path.Combine(app, @"r2modmanPlus-local\CasualtiesUnknown\profiles")); |
| 169 | Try(list, "Thunderstore Mod Manager", Path.Combine(app, @"Thunderstore Mod Manager\DataFolder\CasualtiesUnknown\profiles")); |
| 170 | Try(list, "Gale", Path.Combine(app, @"com.kesomannen.gale\" + Thunderstore.Community + @"\profiles")); |
| 171 | return list; |
| 172 | } |
| 173 | |
| 174 | public static string Handler() |
| 175 | { |
| 176 | try |
| 177 | { |
| 178 | using (RegistryKey k = Registry.ClassesRoot.OpenSubKey(@"ror2mm\shell\open\command")) |
| 179 | { |
| 180 | string cmd = k != null ? k.GetValue(null) as string : null; |
| 181 | if (string.IsNullOrEmpty(cmd)) return null; |
| 182 | string c = cmd.ToLowerInvariant(); |
| 183 | string exe = cmd.Trim(); |
| 184 | if (exe.StartsWith("\"")) { int q = exe.IndexOf('"', 1); exe = q > 0 ? exe.Substring(1, q - 1) : exe.Trim('"'); } |
| 185 | else { int sp = exe.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); if (sp > 0) exe = exe.Substring(0, sp + 4); } |
| 186 | if (!File.Exists(exe)) return null; |
| 187 | if (c.Contains("gale")) return "Gale"; |
| 188 | if (c.Contains("thunderstore")) return "Thunderstore Mod Manager"; |
| 189 | if (c.Contains("r2modman")) return "r2modman"; |
| 190 | return "your mod manager"; |
| 191 | } |
| 192 | } |
| 193 | catch (Exception) { return null; } |
| 194 | } |
| 195 | |
| 196 | private static void Try(List<ModManager> list, string name, string profiles) |
| 197 | { |
| 198 | try |
| 199 | { |
| 200 | if (!Directory.Exists(profiles)) return; |
| 201 | ModManager m = new ModManager(); |
| 202 | m.Name = name; |
| 203 | m.Data = profiles; |
| 204 | foreach (string dir in Directory.GetDirectories(profiles)) |
| 205 | { |
| 206 | MgrProfile p = new MgrProfile(); |
| 207 | p.Manager = name; |
| 208 | p.Name = Path.GetFileName(dir); |
| 209 | p.Dir = dir; |
| 210 | ScanProfile(p); |
| 211 | m.Profiles.Add(p); |
| 212 | if (m.Profiles.Count >= 50) break; |
| 213 | } |
| 214 | list.Add(m); |
| 215 | } |
| 216 | catch (Exception) { } |
| 217 | } |
| 218 | |
| 219 | private static void ScanProfile(MgrProfile p) |
| 220 | { |
| 221 | string plugins = Path.Combine(p.Dir, @"BepInEx\plugins"); |
| 222 | if (!Directory.Exists(plugins)) return; |
| 223 | int seen = 0; |
| 224 | Stack<string> todo = new Stack<string>(); |
| 225 | todo.Push(plugins); |
| 226 | while (todo.Count > 0 && seen < 4000) |
| 227 | { |
| 228 | string d = todo.Pop(); |
| 229 | string[] files, dirs; |
| 230 | try { files = Directory.GetFiles(d); dirs = Directory.GetDirectories(d); } catch (Exception) { continue; } |
| 231 | foreach (string f in files) |
| 232 | { |
| 233 | seen++; |
| 234 | if (f.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) p.Dlls.Add(Path.GetFileName(f)); |
| 235 | } |
| 236 | foreach (string sub in dirs) |
| 237 | { |
| 238 | string n = Path.GetFileName(sub); |
| 239 | if (n.StartsWith(Thunderstore.Owner + "-", StringComparison.OrdinalIgnoreCase)) |
| 240 | { |
| 241 | string v = ManifestVersion(Path.Combine(sub, "manifest.json")); |
| 242 | if (v != null) p.Versions[n.Substring(Thunderstore.Owner.Length + 1)] = v; |
| 243 | } |
| 244 | todo.Push(sub); |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | private static string ManifestVersion(string file) |
| 250 | { |
| 251 | try |
| 252 | { |
| 253 | if (!File.Exists(file) || new FileInfo(file).Length > 64 * 1024) return null; |
| 254 | System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(File.ReadAllText(file), "\"version_number\"\\s*:\\s*\"(\\d+\\.\\d+\\.\\d+)\""); |
| 255 | return m.Success ? m.Groups[1].Value : null; |
| 256 | } |
| 257 | catch (Exception) { return null; } |
| 258 | } |
| 259 | |
| 260 | public static MgrProfile Find(List<ModManager> list, KnownMod k) |
| 261 | { |
| 262 | if (list == null) return null; |
| 263 | foreach (ModManager m in list) |
| 264 | foreach (MgrProfile p in m.Profiles) |
| 265 | if (p.Dlls.Contains(k.Dll)) return p; |
| 266 | return null; |
| 267 | } |
| 268 | |
| 269 | public static int Count(ModManager m) |
| 270 | { |
| 271 | int n = 0; |
| 272 | HashSet<string> seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| 273 | foreach (MgrProfile p in m.Profiles) |
| 274 | foreach (KnownMod k in Installer.Mods) |
| 275 | if (p.Dlls.Contains(k.Dll) && seen.Add(k.Dll)) n++; |
| 276 | return n; |
| 277 | } |
| 278 | } |
| 279 | } |