casualexpiesource

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

237 lines · 11.0 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Globalization;
5using System.IO;
6using System.Linq;
7using System.Net.Http;
8using System.Text;
9using System.Text.Json;
10using System.Text.RegularExpressions;
11using System.Threading.Tasks;
12
13namespace UltraParadise.Linux
14{
15 internal sealed class TsPackage
16 {
17 public string Name, Version, Url, Icon, Description;
18 public long Downloads;
19 public bool Deprecated;
20 public Avalonia.Media.Imaging.Bitmap Image;
21 }
22
23 internal static class Thunderstore
24 {
25 public const string Owner = "casualexpie";
26 public const string Community = "casualties-unknown";
27 public const string TeamUrl = "https://thunderstore.io/c/" + Community + "/p/" + Owner + "/";
28 private const string Api = "https://thunderstore.io/c/" + Community + "/api/v1/package/";
29 private static string CacheFile => Path.Combine(Dirs.Cache, "thunderstore.txt");
30
31 public static string PageUrl(string name) => TeamUrl + name + "/";
32 public static string InstallLink(TsPackage p) => "ror2mm://v1/install/thunderstore.io/" + Owner + "/" + p.Name + "/" + p.Version + "/";
33
34 public static bool SafeUrl(string u) => u != null && (u.StartsWith("https://thunderstore.io/", StringComparison.Ordinal) || u.StartsWith("ror2mm://v1/install/thunderstore.io/", StringComparison.Ordinal));
35
36 public static Dictionary<string, TsPackage> Load(out DateTime when)
37 {
38 when = DateTime.MinValue;
39 try
40 {
41 if (!File.Exists(CacheFile)) return null;
42 when = File.GetLastWriteTimeUtc(CacheFile);
43 Dictionary<string, TsPackage> d = new(StringComparer.OrdinalIgnoreCase);
44 foreach (string line in File.ReadAllLines(CacheFile))
45 {
46 string[] f = line.Split('\t');
47 if (f.Length < 5) continue;
48 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 };
49 long.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out p.Downloads);
50 if (Safe(p)) d[p.Name] = p;
51 }
52 return d.Count > 0 ? d : null;
53 }
54 catch (Exception) { return null; }
55 }
56
57 public static async Task<Dictionary<string, TsPackage>> Fetch()
58 {
59 using HttpRequestMessage req = new(HttpMethod.Get, Api);
60 req.Headers.Accept.ParseAdd("application/json");
61 using HttpResponseMessage res = await Http.Client.SendAsync(req);
62 res.EnsureSuccessStatusCode();
63 string json = await res.Content.ReadAsStringAsync();
64 using JsonDocument doc = JsonDocument.Parse(json);
65 if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
66 Dictionary<string, TsPackage> d = new(StringComparer.OrdinalIgnoreCase);
67 static string S(JsonElement e, string k) => e.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
68 foreach (JsonElement n in doc.RootElement.EnumerateArray())
69 {
70 if (S(n, "owner") != Owner) continue;
71 if (!n.TryGetProperty("versions", out JsonElement vers) || vers.ValueKind != JsonValueKind.Array || vers.GetArrayLength() == 0) continue;
72 TsPackage p = new()
73 {
74 Name = S(n, "name"),
75 Url = S(n, "package_url"),
76 Deprecated = n.TryGetProperty("is_deprecated", out JsonElement dep) && dep.ValueKind == JsonValueKind.True,
77 Version = S(vers[0], "version_number"),
78 Icon = S(vers[0], "icon"),
79 Description = S(vers[0], "description"),
80 };
81 foreach (JsonElement v in vers.EnumerateArray())
82 if (v.TryGetProperty("downloads", out JsonElement dl) && dl.ValueKind == JsonValueKind.Number && dl.TryGetInt64(out long x)) p.Downloads += x;
83 if (Safe(p)) d[p.Name] = p;
84 }
85 try
86 {
87 Private.Dir(Dirs.Cache);
88 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")));
89 }
90 catch (Exception) { }
91 return d;
92 }
93
94 private static bool Safe(TsPackage p)
95 {
96 if (string.IsNullOrEmpty(p.Name) || string.IsNullOrEmpty(p.Version)) return false;
97 if (!Regex.IsMatch(p.Name, "^[A-Za-z0-9_]{1,64}$") || !Regex.IsMatch(p.Version, "^\\d+\\.\\d+\\.\\d+$")) return false;
98 if (p.Url == null || !p.Url.StartsWith("https://thunderstore.io/", StringComparison.Ordinal)) p.Url = PageUrl(p.Name);
99 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;
100 p.Description = Regex.Replace(p.Description ?? "", "\\s+", " ").Trim();
101 if (p.Description.Length > 300) p.Description = p.Description[..300];
102 return true;
103 }
104
105 public static int Compare(string a, string b)
106 {
107 if (!System.Version.TryParse(a ?? "", out Version va) || !System.Version.TryParse(b ?? "", out Version vb)) return 0;
108 return va.CompareTo(vb);
109 }
110 }
111
112 internal sealed class MgrProfile
113 {
114 public string Manager, Name, Dir;
115 public readonly HashSet<string> Dlls = new(StringComparer.OrdinalIgnoreCase);
116 public readonly Dictionary<string, string> Versions = new(StringComparer.OrdinalIgnoreCase);
117 }
118
119 internal sealed class ModManager
120 {
121 public string Name;
122 public readonly List<MgrProfile> Profiles = new();
123 }
124
125 internal static class ModManagers
126 {
127 public static List<ModManager> Scan()
128 {
129 List<ModManager> list = new();
130 string h = Dirs.Home;
131 string xc = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
132 string xd = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
133 string config = string.IsNullOrEmpty(xc) ? Path.Combine(h, ".config") : xc;
134 string data = string.IsNullOrEmpty(xd) ? Path.Combine(h, ".local", "share") : xd;
135 string mac = Path.Combine(h, "Library", "Application Support");
136 string r2 = Path.Combine("r2modmanPlus-local", "CasualtiesUnknown", "profiles");
137 string gale = Path.Combine("com.kesomannen.gale", Thunderstore.Community, "profiles");
138 Try(list, "r2modman", Path.Combine(config, r2), Path.Combine(h, ".var", "app", "com.github.ebkr.r2modman", "config", r2), Path.Combine(mac, r2));
139 Try(list, "Gale", Path.Combine(data, gale), Path.Combine(h, ".var", "app", "com.kesomannen.gale", "data", gale), Path.Combine(mac, gale));
140 return list;
141 }
142
143 public static string Handler()
144 {
145 if (OperatingSystem.IsMacOS()) return null;
146 try
147 {
148 ProcessStartInfo si = new("xdg-mime") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true };
149 si.ArgumentList.Add("query");
150 si.ArgumentList.Add("default");
151 si.ArgumentList.Add("x-scheme-handler/ror2mm");
152 using Process p = Process.Start(si);
153 if (p == null) return null;
154 string o = p.StandardOutput.ReadToEnd().Trim().ToLowerInvariant();
155 if (!p.WaitForExit(3000)) { try { p.Kill(); } catch (Exception) { } return null; }
156 if (o.Length == 0) return null;
157 if (o.Contains("gale")) return "Gale";
158 if (o.Contains("r2modman")) return "r2modman";
159 return "your mod manager";
160 }
161 catch (Exception) { return null; }
162 }
163
164 private static void Try(List<ModManager> list, string name, params string[] roots)
165 {
166 ModManager m = null;
167 foreach (string profiles in roots)
168 {
169 try
170 {
171 if (!Directory.Exists(profiles)) continue;
172 m ??= new ModManager { Name = name };
173 foreach (string dir in Directory.GetDirectories(profiles).Take(50))
174 {
175 MgrProfile p = new() { Manager = name, Name = Path.GetFileName(dir), Dir = dir };
176 ScanProfile(p);
177 m.Profiles.Add(p);
178 }
179 }
180 catch (Exception) { }
181 }
182 if (m != null) list.Add(m);
183 }
184
185 private static void ScanProfile(MgrProfile p)
186 {
187 string plugins = Path.Combine(p.Dir, "BepInEx", "plugins");
188 if (!Directory.Exists(plugins)) return;
189 int seen = 0;
190 Stack<string> todo = new();
191 todo.Push(plugins);
192 while (todo.Count > 0 && seen < 4000)
193 {
194 string d = todo.Pop();
195 string[] files, dirs;
196 try { files = Directory.GetFiles(d); dirs = Directory.GetDirectories(d); } catch (Exception) { continue; }
197 foreach (string f in files)
198 {
199 seen++;
200 if (f.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) p.Dlls.Add(Path.GetFileName(f));
201 }
202 foreach (string sub in dirs)
203 {
204 string n = Path.GetFileName(sub);
205 if (n.StartsWith(Thunderstore.Owner + "-", StringComparison.OrdinalIgnoreCase))
206 {
207 string v = ManifestVersion(Path.Combine(sub, "manifest.json"));
208 if (v != null) p.Versions[n[(Thunderstore.Owner.Length + 1)..]] = v;
209 }
210 todo.Push(sub);
211 }
212 }
213 }
214
215 private static string ManifestVersion(string file)
216 {
217 try
218 {
219 if (!File.Exists(file) || new FileInfo(file).Length > 64 * 1024) return null;
220 Match m = Regex.Match(File.ReadAllText(file), "\"version_number\"\\s*:\\s*\"(\\d+\\.\\d+\\.\\d+)\"");
221 return m.Success ? m.Groups[1].Value : null;
222 }
223 catch (Exception) { return null; }
224 }
225
226 public static MgrProfile Find(List<ModManager> list, KnownMod k)
227 {
228 if (list == null) return null;
229 foreach (ModManager m in list)
230 foreach (MgrProfile p in m.Profiles)
231 if (p.Dlls.Contains(k.Dll)) return p;
232 return null;
233 }
234
235 public static int Count(ModManager m) => Mods.All.Count(k => m.Profiles.Any(p => p.Dlls.Contains(k.Dll)));
236 }
237}