/* * 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 { /// /// 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() { 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. /// /// /// The representing the queue time of the build, or if an error occurs. /// public static bool BuildQueryQueueTime(out DateTime DateTime) { string repo = Win32.GetEnvironmentVariable("GITHUB_REPOSITORY"); string runId = Win32.GetEnvironmentVariable("GITHUB_RUN_ID"); string token = Win32.GetEnvironmentVariable("GITHUB_TOKEN"); if (string.IsNullOrWhiteSpace(repo) || string.IsNullOrWhiteSpace(runId) || string.IsNullOrWhiteSpace(token)) { DateTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); Console.WriteLine($"Build StartTime: {VT.YELLOW}{DateTime}{VT.RESET} (Failed)"); Console.WriteLine($"Build Elapsed: {VT.YELLOW}{(DateTimeOffset.UtcNow - DateTime)}{VT.RESET} (Failed)"); return true; } 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 httpResult = BuildHttpClient.SendMessage(requestMessage); if (string.IsNullOrWhiteSpace(httpResult)) { Console.WriteLine($"{VT.RED}[ERROR] Received empty response.{VT.RESET}"); ArgumentNullException.ThrowIfNull(httpResult); } var content = JsonSerializer.Deserialize(httpResult, GithubResponseContext.Default.GithubActionRun); if (content == null) { Console.WriteLine($"{VT.RED}[ERROR] Failed to deserialize the response.{VT.RESET}"); ArgumentNullException.ThrowIfNull(content); } 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}"); DateTime = offset.DateTime; return true; } } catch (Exception ex) { Console.WriteLine($"{VT.RED}[ERROR] {ex}{VT.RESET}"); DateTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); return false; } } /// /// 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 GithubReleaseQueryResponse 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 = BuildHttpClient.SendMessage(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 GithubReleasesResponse 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 = BuildHttpClient.SendMessage(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 bool 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 = BuildHttpClient.SendMessageResponse(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 = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (string.IsNullOrWhiteSpace(result)) { Program.PrintColorMessage("[DeleteRelease-ReadAsStringAsync]", ConsoleColor.Red); return false; } githubResponseMessage = JsonSerializer.Deserialize(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"); var response = BuildHttpClient.SendMessage(requestMessage); if (string.IsNullOrWhiteSpace(response)) { 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"); var response = BuildHttpClient.SendMessage(requestMessage); if (string.IsNullOrWhiteSpace(response)) { 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 GithubReleasesResponse 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 = BuildHttpClient.SendMessage(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 GithubAssetsResponse 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 upload_url = ReleaseAssetUrl.Replace( "{?name,label}", $"?name={Uri.EscapeDataString(Name)}&label={Uri.EscapeDataString(Label)}", StringComparison.OrdinalIgnoreCase ); try { using var fileStream = File.OpenRead(FileName); using var bufferedStream = new BufferedStream(fileStream); using var requestMessage = new HttpRequestMessage(HttpMethod.Post, upload_url); 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 = BuildHttpClient.SendMessage(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 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 { get { return 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) { for (int i = 0; i < this.Files.Count; i++) { var entry = this.Files[i]; 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 deploy file. /// /// The if found; otherwise, null. /// public GithubReleaseAsset GetDeployInfo(string Name) { for (int i = 0; i < this.Files.Count; i++) { var entry = this.Files[i]; 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 deploy file. /// The filename of the deploy file. /// The hash value of the deploy file. /// The digital signature of the deploy file. /// The file size/length of the deploy file. public class DeployFile(string Name, string Filename, string FileHash, string FileSignature, string FileLength) { /// /// Gets the name of the deploy file. /// public readonly string Name = Name; /// /// Gets the filename of the deploy 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 deploy file. /// public readonly string FileSignature = FileSignature; /// /// Gets the file size/length of the deploy 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(); } } }