/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// Provides static methods for managing GitHub releases and assets via the GitHub API. /// public static class BuildGithub { /// /// Provides a static HTTP client instance for making requests to GitHub APIs. /// /// Using a static instance of HttpClient helps prevent socket exhaustion and improves /// performance when making multiple requests. This client is intended for internal use when interacting with /// GitHub services. private static readonly HttpClient GithubHttpClient; /// /// The GitHub API token used for authentication. /// private static readonly string BaseToken; /// /// The base URL for the GitHub API. /// private static readonly string BaseUrl; /// /// Initializes static members of the class by reading environment variables. /// static BuildGithub() { GithubHttpClient = BuildHttpClient.CreateHttpClient(); BaseToken = Win32.GetEnvironmentVariable("GITHUB_MIRROR_KEY"); BaseUrl = Win32.GetEnvironmentVariable("GITHUB_MIRROR_API"); } /// /// Queries the GitHub Action Run API for the current build's queue time. /// /// /// A tuple containing a boolean indicating success and the representing the queue time of the build, or if an error occurs. /// public static async Task<(bool Success, DateTime QueueTime)> BuildQueryQueueTime() { string repo = Win32.GetEnvironmentVariable("GITHUB_REPOSITORY"); string runId = Win32.GetEnvironmentVariable("GITHUB_RUN_ID"); string token = Win32.GetEnvironmentVariable("GITHUB_TOKEN"); DateTime queueTime; if (string.IsNullOrWhiteSpace(repo) || string.IsNullOrWhiteSpace(runId) || string.IsNullOrWhiteSpace(token)) { queueTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); Console.WriteLine($"Build StartTime: {VT.YELLOW}{queueTime}{VT.RESET} (TickCount)"); Console.WriteLine($"Build Elapsed: {VT.YELLOW}{(DateTimeOffset.UtcNow - queueTime)}{VT.RESET} (TickCount)"); return (true, queueTime); } try { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/{repo}/actions/runs/{runId}")) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.TryAddWithoutValidation("X-GitHub-Api-Version", "2022-11-28"); var content = await BuildHttpClient.SendMessage(GithubHttpClient, requestMessage, GithubResponseContext.Default.GithubActionRun); if (content == null) { Console.WriteLine($"{VT.RED}[ERROR] Failed to deserialize the response.{VT.RESET}"); ArgumentNullException.ThrowIfNull((GithubActionRun)null); } var offset = new DateTimeOffset(DateTime.SpecifyKind(content.CreatedAt, DateTimeKind.Utc)); Console.WriteLine($"Build Created: {VT.GREEN}{content.CreatedAt}{VT.RESET}"); Console.WriteLine($"Build Started: {VT.GREEN}{content.RunStartedAt}{VT.RESET}"); Console.WriteLine($"Build Elapsed: {VT.GREEN}{(DateTimeOffset.UtcNow - offset)}{VT.RESET}"); queueTime = offset.DateTime; return (true, queueTime); } } catch (Exception ex) { Console.WriteLine($"{VT.RED}[ERROR] {ex}{VT.RESET}"); queueTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); return (false, queueTime); } } /// /// Downloads the GitHub meta-IP ranges and returns them as a list of strings. /// /// A list of IP address ranges from the GitHub meta-endpoint, or null on error. public static async IAsyncEnumerable DownloadGithubIpRanges([EnumeratorCancellation] CancellationToken CancellationToken = default) { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/meta")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.TryAddWithoutValidation("X-GitHub-Api-Version", "2022-11-28"); using var response = await BuildHttpClient.SendMessageResponse(GithubHttpClient, requestMessage, CancellationToken); if (response == null || !response.IsSuccessStatusCode) { Program.PrintColorMessage("[DownloadGithubIpRanges] response failed", ConsoleColor.Red); yield break; } await using Stream stream = await response.Content.ReadAsStreamAsync(CancellationToken); var meta = await JsonSerializer.DeserializeAsync(stream, GithubResponseContext.Default.DictionaryStringJsonElement, CancellationToken); if (meta == null) { Program.PrintColorMessage("[DownloadGithubIpRanges] invalid response", ConsoleColor.Red); yield break; } var results = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var property in meta) { if (property.Value.ValueKind != JsonValueKind.Array) continue; foreach (var entry in property.Value.EnumerateArray()) { if (entry.ValueKind != JsonValueKind.String) continue; var value = entry.GetString(); if (IsIpRange(value) && results.Add(value)) { yield return value; } } } } static bool IsIpRange(string Value) { if (string.IsNullOrWhiteSpace(Value)) return false; ReadOnlySpan span = Value.AsSpan(); var slashIndex = span.IndexOf('/'); var address = slashIndex >= 0 ? span[..slashIndex] : span; return IPAddress.TryParse(address, out _); } } /// /// Retrieves a GitHub release by its release ID. /// /// The unique identifier of the release. /// /// A object containing release details, or null if not found or on error. /// public static async Task GetRelease(ulong ReleaseId) { if (string.IsNullOrWhiteSpace(BaseUrl)) return null; if (string.IsNullOrWhiteSpace(BaseToken)) return null; try { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/releases/{ReleaseId}")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); var httpResult = await BuildHttpClient.SendMessage(GithubHttpClient, requestMessage, GithubResponseContext.Default.GithubReleaseQueryResponse); if (httpResult == null) { Program.PrintColorMessage("[GetRelease-GithubReleaseQueryResponse]", ConsoleColor.Red); return null; } return httpResult; } } catch (Exception ex) { Program.PrintColorMessage($"[GetRelease] {ex}", ConsoleColor.Red); } return null; } /// /// Creates a new GitHub release. /// /// The version tag for the release. /// Indicates whether the release is a draft. /// Indicates whether the release is a prerelease. /// Indicates whether to auto-generate release notes. /// /// A object containing release details, or null on error. /// public static async Task CreateRelease(string Version, bool Draft = true, bool Prerelease = false, bool GenerateReleaseNotes = true) { if (string.IsNullOrWhiteSpace(BaseUrl)) return null; if (string.IsNullOrWhiteSpace(BaseToken)) return null; try { GithubReleasesRequest buildUpdateRequest = new GithubReleasesRequest { ReleaseTag = Version, Name = Version, Draft = Draft, Prerelease = Prerelease, GenerateReleaseNotes = GenerateReleaseNotes, }; using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/releases")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); requestMessage.Content = new ByteArrayContent(buildUpdateRequest.SerializeToBytes()); var httpResult = await BuildHttpClient.SendMessage(GithubHttpClient, requestMessage, GithubResponseContext.Default.GithubReleasesResponse); if (httpResult == null) { Program.PrintColorMessage("[CreateRelease-GithubReleasesResponse]", ConsoleColor.Red); return null; } if (string.IsNullOrWhiteSpace(httpResult.UploadUrl)) { Program.PrintColorMessage("[CreateRelease-upload_url]", ConsoleColor.Red); return null; } return httpResult; } } catch (Exception ex) { Program.PrintColorMessage($"[CreateRelease] {ex}", ConsoleColor.Red); } return null; } /// /// Deletes a GitHub release and its associated tag. /// /// The version tag of the release to delete. /// /// true if the release and tag were deleted or did not exist; false on error. /// public static async Task DeleteRelease(string Version) { if (string.IsNullOrWhiteSpace(BaseUrl)) return false; if (string.IsNullOrWhiteSpace(BaseToken)) return false; try { HttpResponseMessage responseMessage; GithubReleasesResponse githubResponseMessage; using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/releases/tags/{Version}")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); responseMessage = await BuildHttpClient.SendMessageResponse(GithubHttpClient, requestMessage); if (!responseMessage.IsSuccessStatusCode) { if (responseMessage.StatusCode == HttpStatusCode.NotFound) { return true; // tag doesn't exist } else { Program.PrintColorMessage("[DeleteRelease-GetAsync] " + responseMessage, ConsoleColor.Red); return false; } } } { var result = await responseMessage.Content.ReadAsStreamAsync(); githubResponseMessage = await JsonSerializer.DeserializeAsync(result, GithubResponseContext.Default.GithubReleasesResponse); if (githubResponseMessage == null) { Program.PrintColorMessage("[DeleteRelease-GithubReleasesResponse]", ConsoleColor.Red); return false; } } if (githubResponseMessage.ReleaseId == 0) { Program.PrintColorMessage("[DeleteRelease-ReleaseId]", ConsoleColor.Red); return false; } // Delete the release (required) using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Delete, $"{BaseUrl}/releases/{githubResponseMessage.ReleaseId}")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); using var response = await BuildHttpClient.SendMessageResponse(GithubHttpClient, requestMessage); if (!response.IsSuccessStatusCode) { Program.PrintColorMessage("[DeleteRelease-DeleteAsync]", ConsoleColor.Red); return false; } } // Delete the release tag (optional) using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Delete, $"{BaseUrl}/git/refs/tags/{Version}")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); using var response = await BuildHttpClient.SendMessageResponse(GithubHttpClient, requestMessage); if (!response.IsSuccessStatusCode) { Program.PrintColorMessage("[DeleteRelease-DeleteAsync]", ConsoleColor.Red); return false; } } } catch (Exception ex) { Program.PrintColorMessage("[DeleteRelease] " + ex, ConsoleColor.Red); //return false; ignore } return true; } /// /// Updates an existing GitHub release. /// /// The unique identifier of the release to update. /// Indicates whether the release is a draft. /// Indicates whether the release is a prerelease. /// /// A object containing updated release details, or null on error. /// public static async Task UpdateRelease(ulong ReleaseId, bool Draft = false, bool Prerelease = false) { if (string.IsNullOrWhiteSpace(BaseUrl)) return null; if (string.IsNullOrWhiteSpace(BaseToken)) return null; try { GithubReleasesRequest buildUpdateRequest = new GithubReleasesRequest { Draft = Draft, Prerelease = Prerelease }; using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Patch, $"{BaseUrl}/releases/{ReleaseId}")) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); requestMessage.Content = new ByteArrayContent(buildUpdateRequest.SerializeToBytes()); var response = await BuildHttpClient.SendMessage(GithubHttpClient, requestMessage, GithubResponseContext.Default.GithubReleasesResponse); if (response == null) { Program.PrintColorMessage("[UpdateRelease-GithubReleasesResponse]", ConsoleColor.Red); return null; } if (string.IsNullOrWhiteSpace(response.UploadUrl)) { Program.PrintColorMessage("[UpdateRelease-upload_url]", ConsoleColor.Red); return null; } return response; } } catch (Exception ex) { Program.PrintColorMessage("[UpdateRelease] " + ex, ConsoleColor.Red); } return null; } /// /// Uploads an asset file to a GitHub release. /// /// The upload URL for the release asset. /// The path to the file to upload. /// The name of the asset. /// The label for the asset. /// /// A object containing asset upload details, or null on error. /// public static async Task UploadAsset(string ReleaseAssetUrl, string FileName, string Name, string Label) { if (string.IsNullOrWhiteSpace(BaseToken)) return null; if (!ReleaseAssetUrl.Contains("{?name,label}", StringComparison.OrdinalIgnoreCase)) return null; string uploadUrl = ReleaseAssetUrl.Replace( "{?name,label}", $"?name={Uri.EscapeDataString(Name)}&label={Uri.EscapeDataString(Label)}", StringComparison.OrdinalIgnoreCase ); try { await using var fileStream = File.OpenRead(FileName); await using var bufferedStream = new BufferedStream(fileStream); using var requestMessage = new HttpRequestMessage(HttpMethod.Post, uploadUrl); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Token", BaseToken); requestMessage.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); requestMessage.Content = new StreamContent(bufferedStream); requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await BuildHttpClient.SendMessage(GithubHttpClient, requestMessage, GithubResponseContext.Default.GithubAssetsResponse); if (response == null || !response.Uploaded || string.IsNullOrWhiteSpace(response.DownloadUrl)) { Program.PrintColorMessage("[UploadAssets] upload failed", ConsoleColor.Red); return null; } return response; } catch (Exception ex) { Program.PrintColorMessage("[UploadAssets] " + ex, ConsoleColor.Red); return null; } } } /// /// Represents a GitHub release with associated assets. /// public class GithubRelease : IComparable, IComparable, IEquatable { /// /// Gets the unique identifier of the release. /// public readonly ulong ReleaseId; /// /// Gets the list of assets associated with the release. /// public readonly List Files; /// /// Initializes a new instance of the class with default values. /// public GithubRelease() { this.ReleaseId = 0; this.Files = new List(); } /// /// Initializes a new instance of the class with a specified release ID. /// /// The unique identifier of the release. public GithubRelease(ulong ReleaseId) { this.ReleaseId = ReleaseId; this.Files = new List(); } /// /// Gets a value indicating whether the release is valid (has a non-zero ID and at least one asset). /// public bool Valid => this.ReleaseId != 0 && this.Files.Count > 0; /// /// Gets the download URL for a specified file name in the release assets. /// /// The name of the file to find. /// The download URL if found; otherwise, an empty string. public string GetFileUrl(string FileName) { foreach (var entry in this.Files) { if (string.Equals(FileName, entry.Filename, StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(entry.DownloadUrl)) return entry.DownloadUrl; } } return string.Empty; } /// /// Gets deployment information for a specified asset name. /// /// The name of the deployment file. /// /// The if found; otherwise, null. /// public GithubReleaseAsset GetDeployInfo(string Name) { foreach (var entry in this.Files) { if (string.Equals(entry.DeployFile.Name, Name, StringComparison.OrdinalIgnoreCase)) { return entry; } } return null; } /// public override string ToString() { return this.ReleaseId.ToString(); } /// public override int GetHashCode() { return this.ReleaseId.GetHashCode(); } /// public override bool Equals(object Obj) { return Obj is GithubRelease file && this.ReleaseId == file.ReleaseId; } /// public bool Equals(GithubRelease Other) { return Other != null && this.ReleaseId == Other.ReleaseId; } /// public int CompareTo(object Obj) { if (Obj == null) return 1; if (Obj is GithubRelease package) return string.Compare(this.ReleaseId.ToString(), package.ReleaseId.ToString(), StringComparison.OrdinalIgnoreCase); else return 1; } /// public int CompareTo(GithubRelease Obj) { if (Obj == null) return 1; return string.Compare(this.ReleaseId.ToString(), Obj.ReleaseId.ToString(), StringComparison.OrdinalIgnoreCase); } /// /// Determines whether two instances are equal. /// public static bool operator ==(GithubRelease Left, GithubRelease Right) { if (ReferenceEquals(Left, null)) { return ReferenceEquals(Right, null); } return Left.Equals(Right); } /// /// Determines whether two instances are not equal. /// public static bool operator !=(GithubRelease Left, GithubRelease Right) { return !(Left == Right); } /// /// Determines whether one is less than another. /// public static bool operator <(GithubRelease Left, GithubRelease Right) { return ReferenceEquals(Left, null) ? !ReferenceEquals(Right, null) : Left.CompareTo(Right) < 0; } /// /// Determines whether one is less than or equal to another. /// public static bool operator <=(GithubRelease Left, GithubRelease Right) { return ReferenceEquals(Left, null) || Left.CompareTo(Right) <= 0; } /// /// Determines whether one is greater than another. /// public static bool operator >(GithubRelease Left, GithubRelease Right) { return !ReferenceEquals(Left, null) && Left.CompareTo(Right) > 0; } /// /// Determines whether one is greater than or equal to another. /// public static bool operator >=(GithubRelease Left, GithubRelease Right) { return ReferenceEquals(Left, null) ? ReferenceEquals(Right, null) : Left.CompareTo(Right) >= 0; } } /// /// Represents an asset in a GitHub release. /// /// The name of the asset file. /// The download URL for the asset. /// The deployment file metadata. public class GithubReleaseAsset(string Filename, string DownloadUrl, DeployFile DeployFile) : IComparable, IComparable, IEquatable { /// /// Gets the filename of the asset. /// public string Filename { get; } = Filename; /// /// Gets the download URL for the asset. /// public string DownloadUrl { get; } = DownloadUrl; /// /// Gets the deployment file metadata. /// public DeployFile DeployFile { get; } = DeployFile; /// public override string ToString() { return this.Filename; } /// public override int GetHashCode() { return this.Filename.GetHashCode(StringComparison.OrdinalIgnoreCase); } /// public override bool Equals(object Obj) { return Obj is GithubReleaseAsset file && this.Filename.Equals(file.Filename, StringComparison.OrdinalIgnoreCase); } /// public bool Equals(GithubReleaseAsset Other) { return Other != null && this.Filename.Equals(Other.Filename, StringComparison.OrdinalIgnoreCase); } /// public int CompareTo(object Obj) { if (Obj == null) return 1; if (Obj is GithubReleaseAsset package) return string.Compare(this.Filename, package.Filename, StringComparison.OrdinalIgnoreCase); else return 1; } /// public int CompareTo(GithubReleaseAsset Obj) { if (Obj == null) return 1; return string.Compare(this.Filename, Obj.Filename, StringComparison.OrdinalIgnoreCase); } /// /// Determines whether two instances are equal. /// public static bool operator ==(GithubReleaseAsset Left, GithubReleaseAsset Right) { if (ReferenceEquals(Left, null)) { return ReferenceEquals(Right, null); } return Left.Equals(Right); } /// /// Determines whether two instances are not equal. /// public static bool operator !=(GithubReleaseAsset Left, GithubReleaseAsset Right) { return !(Left == Right); } /// /// Determines whether one is less than another. /// public static bool operator <(GithubReleaseAsset Left, GithubReleaseAsset Right) { return ReferenceEquals(Left, null) ? !ReferenceEquals(Right, null) : Left.CompareTo(Right) < 0; } /// /// Determines whether one is less than or equal to another. /// public static bool operator <=(GithubReleaseAsset Left, GithubReleaseAsset Right) { return ReferenceEquals(Left, null) || Left.CompareTo(Right) <= 0; } /// /// Determines whether one is greater than another. /// public static bool operator >(GithubReleaseAsset Left, GithubReleaseAsset Right) { return !ReferenceEquals(Left, null) && Left.CompareTo(Right) > 0; } /// /// Determines whether one is greater than or equal to another. /// public static bool operator >=(GithubReleaseAsset Left, GithubReleaseAsset Right) { return ReferenceEquals(Left, null) ? ReferenceEquals(Right, null) : Left.CompareTo(Right) >= 0; } } /// /// Represents a deployable file with metadata including name, filename, hash, signature, and length. /// /// /// This class stores deployment file information and provides methods to update download details /// from GitHub API responses. The hash code is based on the file name. /// /// The name of the deployment file. /// The filename of the deployment file. /// The hash value of the deployment file. /// The digital signature of the deployment file. /// The file size/length of the deployment file. public class DeployFile(string Name, string Filename, string FileHash, string FileSignature, string FileLength) { /// /// Gets the name of the deployment file. /// public readonly string Name = Name; /// /// Gets the filename of the deployment file. /// public readonly string FileName = Filename; /// /// Gets the hash value of the deploy file. /// public readonly string FileHash = FileHash; /// /// Gets the digital signature of the deployment file. /// public readonly string FileSignature = FileSignature; /// /// Gets the file size/length of the deployment file. /// public readonly string FileLength = FileLength; /// /// Gets or sets the hash value from the download source. /// public string DownloadHash { get; private set; } /// /// Gets or sets the download URL from the download source. /// public string DownloadLink { get; private set; } /// /// Updates the download hash and link from a GitHub assets response. /// /// The GitHub assets response containing hash and download URL. /// True if the response was successfully processed; otherwise, false. /// /// Returns false if the response is null, the hash value is empty, or the download URL is empty. /// public bool UpdateAssetsResponse(GithubAssetsResponse Response) { if (Response == null) { Program.PrintColorMessage("[UpdateAssetsResponse] response null.", ConsoleColor.Red); return false; } if (string.IsNullOrWhiteSpace(Response.HashValue)) { Program.PrintColorMessage("[UpdateAssetsResponse] HashValue null.", ConsoleColor.Red); return false; } if (string.IsNullOrWhiteSpace(Response.DownloadUrl)) { Program.PrintColorMessage("[UpdateAssetsResponse] DownloadUrl null.", ConsoleColor.Red); return false; } this.DownloadHash = Response.HashValue; this.DownloadLink = Response.DownloadUrl; return true; } /// public override string ToString() { return this.Name; } /// public override int GetHashCode() { return this.Name.GetHashCode(); } } }