GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — UnityLauncherPro/UnityLauncherPro/GetUnityUpdates.cs at 180 · unitycoder/UnityLauncherPro Expand file tree/ Copy pathGetUnityUpdates.csMore file actions 441 lines (367 loc) · 17.9 KB / Copy pathGetUnityUpdates.csFile metadata and controls441 lines (367 loc) · 17.9 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace UnityLauncherPro { public static class GetUnityUpdates { private const string BaseApiUrl = "https://services.api.unity.com/unity/editor/release/v1/releases"; private const int BatchSize = 25; private const int RequestsPerBatch = 10; private const int DelayBetweenBatches = 1000; // 1 second in milliseconds private const string CacheFileName = "UnityVersionCache.json"; private static readonly HttpClient Client = new HttpClient(); public static string unofficalReleasesURL = "https://raw.githubusercontent.com/unitycoder/UnofficialUnityReleasesWatcher/refs/heads/main/unity-releases.md"; static Dictionary<string, string> unofficialReleaseURLs = new Dictionary<string, string>(); public static async Task<List<UnityVersion>> FetchAll(bool useUnofficialList = false) { var cachedVersions = LoadCachedVersions(); var newVersions = await FetchNewVersions(cachedVersions); var allVersions = newVersions.Concat(cachedVersions).ToList(); if (useUnofficialList == true) { var unofficialVersions = await FetchUnofficialVersions(cachedVersions); unofficialReleaseURLs.Clear(); // TODO modify FetchUnofficialVersions to put items in this dictionary directly foreach (var version in unofficialVersions) { Console.WriteLine("version in unofficials: " + version); // add only if not there yet if (unofficialReleaseURLs.ContainsKey(version.Version) == false) { Console.WriteLine("added unofficial: " + version.Version + " , " + version.directURL); unofficialReleaseURLs.Add(version.Version, version.directURL); } } // combine allVersions = unofficialVersions.Concat(allVersions).ToList(); } if (newVersions.Count > 0 || (useUnofficialList && unofficialReleaseURLs.Count > 0)) { SaveCachedVersions(allVersions); } return allVersions; } public static async Task<List<UnityVersion>> FetchUnofficialVersions(List<UnityVersion> cachedVersions) { var unofficialVersions = new List<UnityVersion>(); var existingVersions = new HashSet<string>(cachedVersions.Select(v => v.Version)); try { var content = await Client.GetStringAsync(unofficalReleasesURL); // Parse the Markdown content var lines = content.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { //Console.WriteLine(line); if (line.StartsWith("- ")) // Identify Markdown list items { var urlPart = line.Substring(4).Trim(); // bug in server, has double - var version = ExtractVersionFromUrl(urlPart); //Console.WriteLine("VERSION: " + version); //Console.WriteLine("IsNullOrEmpty: " + (string.IsNullOrEmpty(version)) + ", existingVersions:" + (existingVersions.Contains(version))); if (string.IsNullOrEmpty(version) == false && existingVersions.Contains(version) == false) { var stream = InferStreamFromVersion(version); Console.WriteLine(version + " , " + urlPart); unofficialVersions.Add(new UnityVersion { Version = version, Stream = stream, ReleaseDate = DateTime.Now, // NOTE not correct, but we don't have known release date for unofficial versions (its only when they are found..) //ReleaseDate = DateTime.MinValue // Release date is unavailable in the MD format, TODO add to md as #2021-01-01 ? directURL = urlPart, // this is available only for unofficial releases }); } } } } catch (Exception ex) { Console.WriteLine($"Error fetching unofficial versions: {ex.Message}"); } return unofficialVersions; } // TODO fixme, f is not always LTS private static UnityVersionStream InferStreamFromVersion(string version) { if (Tools.IsAlpha(version)) return UnityVersionStream.Alpha; if (Tools.IsBeta(version)) return UnityVersionStream.Beta; if (Tools.IsLTS(version)) return UnityVersionStream.LTS; //if (version.Contains("a")) return UnityVersionStream.Alpha; //if (version.Contains("b")) return UnityVersionStream.Beta; //if (version.Contains("f")) return UnityVersionStream.LTS; return UnityVersionStream.Tech; // Default to Tech if no identifier is found } /// <summary> /// Extracts the Unity version from the given URL. /// </summary> /// <param name="url">The URL to parse.</param> /// <returns>The Unity version string.</returns> private static string ExtractVersionFromUrl(string url) { try { var versionStart = url.LastIndexOf('#') + 1; return versionStart > 0 && versionStart < url.Length ? url.Substring(versionStart) : null; } catch { return null; } } public static async Task<string> FetchDownloadUrl(string unityVersion) { if (string.IsNullOrEmpty(unityVersion)) { return null; } // unity release api string apiUrl = $"{BaseApiUrl}?limit=1&version={unityVersion}&architecture=X86_64&platform=WINDOWS"; try { string responseString = await Client.GetStringAsync(apiUrl); return await ExtractDownloadUrlAsync(responseString, unityVersion); } catch (Exception e) { Console.WriteLine($"Error fetching download URL: {e.Message}"); return null; } } private static async Task<string> ExtractDownloadUrlAsync(string json, string unityVersion) { //Console.WriteLine("json: " + json + " vers: " + unityVersion); if (json.Contains("\"results\":[]")) { Console.WriteLine("No results found from releases API, checking unofficial list (if enabled), v=" + unityVersion); // print unofficialReleaseURLs foreach (var kvp in unofficialReleaseURLs) { Console.WriteLine($"Unofficial: {kvp.Key} => {kvp.Value}"); } if (unofficialReleaseURLs.ContainsKey(unityVersion)) { Console.WriteLine("Unofficial release found in the list: "); string unityHash = Tools.ParseHashCodeFromURL(unofficialReleaseURLs[unityVersion]); // Console.WriteLine(unityHash); string downloadURL = Tools.ParseDownloadURLFromWebpage(unityVersion, unityHash, false, true); // Console.WriteLine("direct download url: "+downloadURL); return downloadURL; } return null; } int resultsIndex = json.IndexOf("\"results\":"); if (resultsIndex == -1) return null; int downloadsIndex = json.IndexOf("\"downloads\":", resultsIndex); if (downloadsIndex == -1) return null; int urlIndex = json.IndexOf("\"url\":", downloadsIndex); if (urlIndex == -1) return null; int urlStart = json.IndexOf('"', urlIndex + 6) + 1; int urlEnd = json.IndexOf('"', urlStart); string downloadUrl = json.Substring(urlStart, urlEnd - urlStart); int revisionIndex = json.IndexOf("\"shortRevision\":", resultsIndex); string shortRevision = null; if (revisionIndex != -1) { int revisionStart = json.IndexOf('"', revisionIndex + 16) + 1; int revisionEnd = json.IndexOf('"', revisionStart); shortRevision = json.Substring(revisionStart, revisionEnd - revisionStart); } if (!string.IsNullOrEmpty(downloadUrl) && !string.IsNullOrEmpty(shortRevision)) { int revisionPosition = downloadUrl.LastIndexOf(shortRevision, StringComparison.Ordinal) + shortRevision.Length + 1; string assistantUrl = downloadUrl.Substring(0, revisionPosition) + $"UnityDownloadAssistant-{unityVersion}.exe"; if (await CheckAssistantUrl(assistantUrl)) { //Console.WriteLine("ExtractDownloadUrlAsync: Assistant download URL found."); return assistantUrl; } else { Console.WriteLine("Assistant download URL not found, returning original download URL."); return downloadUrl; } } Console.WriteLine("Returning original download URL."); return downloadUrl; } private static async Task<bool> CheckAssistantUrl(string assistantUrl) { try { using (HttpResponseMessage response = await Client.GetAsync(assistantUrl)) { return response.IsSuccessStatusCode; } } catch (Exception ex) { Console.WriteLine($"Request failed: {ex.Message}"); return false; } } private static async Task<List<UnityVersion>> FetchNewVersions(List<UnityVersion> cachedVersions) { var newVersions = new List<UnityVersion>(); var cachedVersionSet = new HashSet<string>(cachedVersions.Select(v => v.Version)); int offset = 0; int total = int.MaxValue; bool foundNewVersionInBatch; while (offset < total) { var batchUpdates = await FetchBatch(offset); if (batchUpdates == null || batchUpdates.Count == 0) break; foundNewVersionInBatch = false; foreach (var version in batchUpdates) { if (!cachedVersionSet.Contains(version.Version)) { newVersions.Add(version); foundNewVersionInBatch = true; } } if (!foundNewVersionInBatch) { // Exit if no new versions are found in the current batch break; } offset += batchUpdates.Count; // Apply delay if reaching batch limit if (offset % (BatchSize * RequestsPerBatch) == 0) { await Task.Delay(DelayBetweenBatches); } } return newVersions; } private static async Task<List<UnityVersion>> FetchBatch(int offset) { string url = $"{BaseApiUrl}?limit={BatchSize}&offset={offset}&architecture=X86_64&platform=WINDOWS"; try { string response = await Client.GetStringAsync(url); return ParseUnityVersions(response); } catch (Exception e) { Console.WriteLine($"Error fetching batch: {e.Message}"); return null; } } private static List<UnityVersion> ParseUnityVersions(string json) { var versions = new List<UnityVersion>(); int resultsIndex = json.IndexOf("\"results\":"); if (resultsIndex == -1) return versions; string[] items = json.Substring(resultsIndex).Split(new[] { "{" }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in items) { if (item.Contains("\"version\"")) { var version = new UnityVersion { Version = GetStringValue(item, "version"), ReleaseDate = DateTime.TryParse(GetStringValue(item, "releaseDate"), out var date) ? date : default, Stream = Enum.TryParse<UnityVersionStream>(GetStringValue(item, "stream"), true, out var stream) ? stream : UnityVersionStream.Tech }; //Console.WriteLine(version.Version); versions.Add(version); } } return versions; } private static List<UnityVersion> ParseCachedUnityVersions(string json) { var versions = new List<UnityVersion>(); // Remove square brackets at the beginning and end of the array json = json.Trim(new[] { '[', ']' }); // Split each item based on the closing bracket and opening bracket of consecutive objects string[] items = json.Split(new[] { "},{" }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in items) { // Ensure each item is properly enclosed in braces to handle edge cases string cleanItem = "{" + item.Trim(new[] { '{', '}' }) + "}"; // Parse each UnityVersion object if (cleanItem.Contains("\"version\"")) { var version = new UnityVersion { Version = GetStringValue(cleanItem, "version"), ReleaseDate = DateTime.TryParse(GetStringValue(cleanItem, "releaseDate"), out var date) ? date : default, Stream = Enum.TryParse<UnityVersionStream>(GetStringValue(cleanItem, "stream"), true, out var stream) ? stream : UnityVersionStream.Tech }; versions.Add(version); } } return versions; } //private static string GetStringValue(string source, string propertyName) //{ // int propertyIndex = source.IndexOf($"\"{propertyName}\":"); // if (propertyIndex == -1) return null; // int valueStart = source.IndexOf('"', propertyIndex + propertyName.Length + 2) + 1; // int valueEnd = source.IndexOf('"', valueStart); // return source.Substring(valueStart, valueEnd - valueStart); //} private static string GetStringValue(string source, string propertyName) { int propertyIndex = source.IndexOf($"\"{propertyName}\":"); if (propertyIndex == -1) return null; int valueStart = source.IndexOf('"', propertyIndex + propertyName.Length + 2) + 1; int valueEnd = source.IndexOf('"', valueStart); return source.Substring(valueStart, valueEnd - valueStart); } private static List<UnityVersion> LoadCachedVersions() { string configFilePath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; string configDirectory = Path.GetDirectoryName(configFilePath); if (configDirectory == null) return new List<UnityVersion>(); string cacheFilePath = Path.Combine(configDirectory, CacheFileName); if (!File.Exists(cacheFilePath)) return new List<UnityVersion>(); Console.WriteLine("cache file: " + cacheFilePath); string json = File.ReadAllText(cacheFilePath); return ParseCachedUnityVersions(json); } private static void SaveCachedVersions(List<UnityVersion> versions) { string json = "["; foreach (var version in versions) { json += $"{{\"version\":\"{version.Version}\",\"releaseDate\":\"{version.ReleaseDate:O}\",\"stream\":\"{version.Stream}\"}},"; } json = json.TrimEnd(',') + "]"; string configFilePath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; string configDirectory = Path.GetDirectoryName(configFilePath); if (configDirectory == null) return; string cacheFilePath = Path.Combine(configDirectory, CacheFileName); //Console.WriteLine("Saving cachedrelease: " + cacheFilePath); File.WriteAllText(cacheFilePath, json); } internal static async Task<string> CheckUnofficialVersionList(string version) { // fetch md page from unofficalReleasesURL var content = await Client.GetStringAsync(unofficalReleasesURL); // parse lines var lines = content.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { if (line.StartsWith("- ")) // Identify Markdown list items { var urlPart = line.Substring(4).Trim(); // bug in server, has double - var foundVersion = ExtractVersionFromUrl(urlPart); if (foundVersion == version) { Console.WriteLine("Found unofficial version in the list: " + foundVersion + " , " + urlPart); return urlPart; } } } return null; } } } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |