static async Task <Tuple <ReleaseAsset, string> > GetNightlyBuild() { Trace.WriteLine("Looking for most recent nightly build..."); var github = new GitHubClient(new ProductHeaderValue("Z3-Tests-Nightly-Runner")); var release = await github.Repository.Release.Get(Settings.GitHubOwner, Settings.GitHubZ3Repository, "Nightly"); if (release == null) { return(null); // no matching files found } var assets = release.Assets.Select(f => Tuple.Create(f, regex.Match(f.Name))).Where(fm => fm.Item2.Success).ToArray(); if (assets == null || assets.Length == 0) { return(null); // no matching files found } // Multiple matching files, should take the most recent DateTimeOffset max = DateTimeOffset.MinValue; ReleaseAsset recent = null; string hash = release.TargetCommitish; foreach (var a in assets) { var commit = await github.Repository.Commit.Get(Settings.GitHubOwner, Settings.GitHubZ3Repository, hash); var date = a.Item1.UpdatedAt; if (date > max) { max = date; recent = a.Item1; } } return(Tuple.Create(recent, release.TargetCommitish)); }
static async Task Run() { string connectionString = await GetConnectionString(); Tuple <ReleaseAsset, string> asset_hash = await GetNightlyBuild(); if (asset_hash == null || asset_hash.Item1 == null) { Trace.WriteLine("Repository has no new build."); return; } ReleaseAsset asset = asset_hash.Item1; string hash = asset_hash.Item2; AzureExperimentManager manager = AzureExperimentManager.Open(connectionString); DateTime last_submission_time = await GetLastNightlyExperimentSubmissionTime(manager); if (last_submission_time >= asset.UpdatedAt) { Trace.WriteLine("No changes found since last nightly experiment."); return; } using (MemoryStream stream = new MemoryStream(asset.Size)) { await Download(asset, stream); stream.Position = 0; Trace.WriteLine("Opening an experiment manager..."); await SubmitExperiment(manager, stream, asset.Name, hash); } }
public ReleaseDownloaderForm(ReleaseAsset releaseAsset, IFolder extractionFolder) { ReleaseAsset = releaseAsset; ExtractionFolder = extractionFolder; InitializeComponent(); }
private void SendLockpickButtonClicked(object sender, RoutedEventArgs e) { if (!HACGUIKeyset.TempLockpickPayloadFileInfo.Exists) { GitHubClient gitClient = new GitHubClient(new ProductHeaderValue("Github")); Task.Run(async() => { Release release = await gitClient.Repository.Release.GetLatest("shchmue", "Lockpick_RCM"); // get latest release ReleaseAsset asset = release.Assets.FirstOrDefault(r => r.BrowserDownloadUrl.EndsWith(".bin")); // get first asset that ends with .bin (the payload) HttpClient httpClient = new HttpClient(); Stream src = await httpClient.GetStreamAsync(asset.BrowserDownloadUrl); // get stream of .bin file using (Stream dest = HACGUIKeyset.TempLockpickPayloadFileInfo.OpenWrite()) await src.CopyToAsync(dest); // stream payload to file while (!HACGUIKeyset.TempLockpickPayloadFileInfo.CanOpen()) { ; // prevent race condition? } }).Wait(); } InjectService.SendPayload(HACGUIKeyset.TempLockpickPayloadFileInfo); }
public ReleaseInstallationDialog(Release release, ReleaseAsset asset, string releaseNotes) { DataContext = this; InitializeComponent(); if (DesignerProperties.GetIsInDesignMode(this)) { ReleaseNotes = "new Feature 1"; VersionInfoString = string.Format("{0} - {1} ({2} MB)", "42.42.42.42", "DemoRelease", string.Format("{0:0.000}", 42 / 1024d / 1024d)); InstallAfterDownload = true; } else { // ToDo: Evil Hack to have the cake (see actual design in design mode) and eat it too (have different styles at runtime) this.Resources = null; this.asset = asset; this.KeyDown += Window_KeyDown; ReleaseNotes = releaseNotes; VersionInfoString = string.Format("{0} - {1} ({2} MB)", VersionStringFromMsiAsset(asset), release.Name, string.Format("{0:0.000}", asset.Size / 1024d / 1024d)); InstallAfterDownload = true; } }
public async Task Update(int SelectedIndex) { Gamemode Gamemode = DisplayGamemodes[SelectedIndex]; int CallerIndex = MainWindow?.Gamemodes.IndexOf(Gamemode) ?? -1; Release Release = GamemodeReleases[Gamemode]; ReleaseAsset FoundAsset = null; foreach (ReleaseAsset Asset in Release.Assets.Where(Asset => Asset.Name.EndsWith(".dll"))) { FoundAsset = Asset; } if (FoundAsset == null) { return; } if (!await Update(MainWindow.GetCurrentLazerPath(), Gamemode, FoundAsset)) { return; } GamemodeReleases.Remove(Gamemode); DisplayGamemodes.RemoveAt(SelectedIndex); Title = OriginalTitle.Replace("%%COUNT%%", GamemodeReleases.Count.ToString("N0")).Replace("%%S%%", GamemodeReleases.Count != 1 ? "s" : string.Empty); if (CallerIndex >= 0) { Gamemode GamemodeClone = (Gamemode)Gamemode.Clone(); GamemodeClone.UpdateStatus = UpdateStatus.UpToDate; GamemodeClone.GitHubTagVersion = Release.TagName ?? GamemodeClone.GitHubTagVersion; MainWindow.UpdateGamemode(CallerIndex, GamemodeClone, true); } }
private void UpdateDownloadWorker() { #if DEBUG var asset = new ReleaseAsset("", 0, "", "SPCodeUpdater.exe", "", "", "", 0, 0, DateTimeOffset.Now, DateTimeOffset.Now, "https://hexah.net/SPCodeUpdater.exe", null); #else var asset = updateInfo.Asset; #endif if (File.Exists(asset.Name)) { File.Delete(asset.Name); } try { using var client = new WebClient(); client.DownloadFile(asset.BrowserDownloadUrl, asset.Name); } catch (Exception e) { MessageBox.Show( "Error while downloading the updater." + Environment.NewLine + "Details: " + e.Message + Environment.NewLine + "$$$" + e.StackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Warning); Dispatcher.Invoke(Close); } Thread.Sleep(100); Dispatcher.Invoke(FinalizeUpdate); }
public static async Task UpdateCheck(bool Overwrite) { if (AppPath.EndsWith("lib", StringComparison.CurrentCultureIgnoreCase)) { AppPath = AppPath.Substring(0, AppPath.Length - 4); } // check to see if the user is online, and that github is up and running. Console.WriteLine("Checking connection to server."); using (Ping s = new Ping()) Console.WriteLine(s.Send("www.github.com").Status); // Initiate the github client. GitHubClient github = new GitHubClient(new Octokit.ProductHeaderValue("Brawltools")); // get repo, Release, and release assets Repository repo = await github.Repository.Get("libertyernie", "brawltools"); Release release = (await github.Release.GetAll(repo.Owner.Login, repo.Name))[0]; ReleaseAsset Asset = (await github.Release.GetAssets("libertyernie", repo.Name, release.Id))[0]; // Check if we were passed in the overwrite paramter, and if not create a new folder to extract in. if (!Overwrite) { Directory.CreateDirectory(AppPath + "/" + release.TagName); AppPath += "/" + release.TagName; } else { //Find and close the brawlbox application that will be overwritten Process[] px = Process.GetProcessesByName("BrawlBox"); Process p = px.FirstOrDefault(x => x.MainModule.FileName.StartsWith(AppPath)); if (p != null && p != default(Process) && p.CloseMainWindow()) { p.Close(); } } using (WebClient client = new WebClient()) { // Add the user agent header, otherwise we will get access denied. client.Headers.Add("User-Agent: Other"); // Full asset streamed into a single string string html = client.DownloadString(Asset.Url); // The browser download link to the self extracting archive, hosted on github string URL = html.Substring(html.IndexOf(BaseURL)).TrimEnd(new char[] { '}', '"' }); Console.WriteLine("\nDownloading"); client.DownloadFile(URL, AppPath + "/Update.exe"); Console.WriteLine("\nSuccess!"); Console.Clear(); Console.WriteLine("Starting install"); Process update = Process.Start(AppPath + "/Update.exe", "-d\"" + AppPath + "\""); } }
/// <summary> /// Check if there is an update available. /// </summary> /// <param name="targetRelease"> /// Release with installer. /// </param> /// <param name="asset"> /// Installer itself. /// </param> /// <returns>Returns whether a new version of Exiled is available or not.</returns> public bool FindUpdate(out Release targetRelease, out ReleaseAsset asset) { try { var url = string.Format(GitHubGetReleasesTemplate, REPOID); using (var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(SecondsWaitForAPI))) using (var result = httpClient.GetAsync(url, cancellationToken.Token).ConfigureAwait(false).GetAwaiter().GetResult()) using (var streamResult = result.Content.ReadAsStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult()) { var releases = JsonSerializer.Deserialize <Release[]>(streamResult) .Where(r => Version.TryParse(r.TagName, out _)) .OrderByDescending(r => r.CreatedAt.Ticks) .ToArray(); Log.Debug($"Found {releases.Length} releases"); for (int z = 0; z < releases.Length; z++) { var release = releases[z]; Log.Debug($"PRE: {release.PreRelease} | ID: {release.Id} | TAG: {release.TagName}"); for (int x = 0; x < release.Assets.Length; x++) { asset = release.Assets[x]; Log.Debug($" - ID: {asset.Id} | NAME: {asset.Name} | SIZE: {asset.Size} | URL: {asset.Url} | DownloadURL: {asset.BrowserDownloadUrl}"); } } if (releases.Length != 0 && FindRelease(releases, out targetRelease)) { var installerNames = GetAvailableInstallerNames(); if (!FindAsset(installerNames, targetRelease, out asset)) { // Error: no asset Log.Warn("Couldn't find the asset, the update will not be installed"); } else { Log.Info($"Found asset - ID: {asset.Id} | NAME: {asset.Name} | SIZE: {asset.Size} | URL: {asset.Url} | DownloadURL: {asset.BrowserDownloadUrl}"); return(true); } } else { // No errors Log.Info("No new versions found, you're using the most recent version of Exiled!"); } } } catch (Exception ex) { Log.Error($"{nameof(FindUpdate)} throw an exception:"); Log.Error(ex); } targetRelease = default; asset = default; return(false); }
async Task UpdateFromAssetAsync(ReleaseAsset asset) { var localFilePath = await DownloadUpdateToDiskAsync(asset); processManager.LaunchFile( localFilePath, "update \"" + CurrentProcessInformation.GetCurrentProcessFilePath() + "\""); }
private void GetTargetAssetIfNull() { if (_targetAsset == null) { var release = _releases.First(); _targetAsset = release.Assets.FirstOrDefault(x => x.Name == _githubConfig.AssetFileName); } }
async Task UpdateFromAssetAsync(ReleaseAsset asset) { var localFilePath = await DownloadUpdateToDiskAsync(asset); processManager.LaunchFile( localFilePath, "update"); }
async Task UpdateFromAssetAsync(ReleaseAsset asset) { var localFilePath = await DownloadUpdateAsync(asset); var temporaryDirectory = ExtractUpdate(localFilePath); StartUpdate(temporaryDirectory); }
public static void GetLatestVersion() { var paDialog = new PendingActivityDialog { Text = "Autoupdate syncthing", SupportsCancellation = false, SupportsProgressVisualization = false }; paDialog.BackgroundWorker.DoWork += delegate { paDialog.BackgroundWorker.ReportProgress(0, "Checking for latest version..."); var repos = GithubClient.Release.GetAll("syncthing", "syncthing").Result; var repoIndex = 0; ReleaseAsset asset = null; while (asset == null && repoIndex < repos.Count) { var latest = GithubClient.Release.GetAssets("syncthing", "syncthing", repos[0].Id).Result; var versions = GrabVersions(latest, repos[repoIndex++]); asset = Environment.Is64BitOperatingSystem ? versions.LatestAmd64 : versions.LatestIntel386; } if (asset == null) { return; } paDialog.BackgroundWorker.ReportProgress(0, $"Downloading {asset.Name}..."); var response = GithubClient.Connection.Get <byte[]>(new Uri(asset.Url), new Dictionary <string, string>(), "application/octet-stream").Result; paDialog.BackgroundWorker.ReportProgress(50, $"Unzipping {asset.Name}..."); var filename = Path.GetTempFileName(); using (var fileStream = File.Create(filename)) { fileStream.Write(response.BodyAsObject, 0, response.BodyAsObject.Length); } System.IO.Compression.ZipFile.ExtractToDirectory(filename, Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)); Directory.Move(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.GetFileNameWithoutExtension(asset.Name)), Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "syncthing")); if (string.IsNullOrEmpty(Settings.Default.SyncthingPath)) { Settings.Default.SyncthingPath = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "syncthing"), "syncthing.exe"); Settings.Default.Save(); } File.Delete(filename); paDialog.BackgroundWorker.ReportProgress(100, "Finished!"); Thread.Sleep(500); }; paDialog.BackgroundWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs args) { if (args.Error != null) { MessageBox.Show(args.Error.Message); } }; paDialog.ShowDialog(); }
private async Task <string> DownloadLatestGithubReleaseAsync() { try { GitHubReleaseModel latestGitHubRelease = await GetGitHubReleaseAsync(_defaultRepo); string assetFilePath = $"{_monitoredAppTempPath}"; string assetFilePathName = $"{assetFilePath}{latestGitHubRelease.ReleaseName}.zip"; System.Console.WriteLine(assetFilePathName); ReleaseAsset singleRelease = await GitHubClient.Repository.Release.GetAsset(_gitHubUser, _defaultRepo, latestGitHubRelease.ReleaseAssetDownloadId); IApiResponse <object> response = await GitHubClient.Connection.Get <object>(new Uri(singleRelease.Url), new Dictionary <string, string>(), "application/octet-stream"); byte[] bytes = (byte[])response.HttpResponse.Body; try { File.WriteAllBytes(assetFilePathName, bytes); bool fileExists = File.Exists(assetFilePathName); try { System.Console.WriteLine(File.GetAttributes(assetFilePathName)); DownloadedLatestReleaseFileAttributes = File.GetAttributes(assetFilePathName).ToString(); System.Console.WriteLine(DownloadedLatestReleaseFilePath); } catch (Exception e) { System.Console.WriteLine(e); } if (fileExists is true) { HasDownLoadedLatestRelease = true; DownloadedLatestReleaseFilePath = assetFilePathName; // TODO create event handler to set the prop so the releaseFile manager can take over } } catch (Exception e) { System.Console.WriteLine(e); //_log } //ExtractBuild(assetFilePathName, path, persisPath); //update the current build number return(latestGitHubRelease.ReleaseId.ToString()); } catch (Exception e) { //_log.ErrorException("Getting the repo info from {client} failed", e); //throw ex; return(null); } }
private static void Pool(object nil) { Thread.Sleep(2000); var currentVersion = new Version(App.VERSION); while (true) { try { Task <Release> taskRelease = client.Repository.Release.GetLatest("EFLFE", "ClockDisp"); taskRelease.Wait(); Release release = taskRelease.Result; if (release.Assets.Count > 0) { ReleaseAsset asset = release.Assets[0]; var assetVersion = new Version(release.TagName); // compare version if (assetVersion > currentVersion) { LastData = new UpdaterData( release.Name, release.Url, new Version(release.TagName), asset.Name, asset.BrowserDownloadUrl); OnDetectedNewVersion(LastData); return; } } } catch (Exception ex) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { throw ex; } else { App.Current.Dispatcher.Invoke(() => new MessageWindow( "Update Error", ex.ToString()).ShowDialog()); } #endif } timer = 1000 * 60; while (timer > 0) { Thread.Sleep(1); timer--; } } }
public PerFileUpdaterForm(ReleaseAsset oldUpdateInfoAsset, ReleaseAsset newUpdateInfoAsset, IFolder updatedFolder, Uri dlUri) { OldUpdateInfoAsset = oldUpdateInfoAsset; NewUpdateInfoAsset = newUpdateInfoAsset; UpdatedFolder = updatedFolder; DLUri = dlUri; InitializeComponent(); }
public async Task TestFileDownloadUrl() { Release latestRelease = await GetLatestRelease(); IReadOnlyList <ReleaseAsset> assets = latestRelease.Assets; ReleaseAsset releaseZipAsset = assets.Single(); Assert.Equal("https://github.com/Aleksbgbg/YouTube-Downloader/releases/download/v1.2.0/Release.zip", releaseZipAsset.BrowserDownloadUrl); }
async Task <string> DownloadUpdateAsync(ReleaseAsset asset) { var url = asset.BrowserDownloadUrl; var data = await fileDownloader.DownloadBytesAsync(url); var localFilePath = fileManager.WriteBytesToTemporaryFile(asset.Name, data); return(localFilePath); }
public static bool TryGetRulesetAsync(Release Release, out ReleaseAsset FoundAsset) { foreach (ReleaseAsset Asset in Release.Assets.Where(Asset => Asset.Name.ToLowerInvariant().EndsWith(".dll"))) { FoundAsset = Asset; return(true); } FoundAsset = null; return(false); }
private void DownloadLastRelease(ReleaseAsset asset, int version) { string install_path = Path.Combine(pathDownload, "game.zip"); _webClient.DownloadFile(asset.browser_download_url, install_path); ZipFile.ExtractToDirectory(install_path, pathDownload); File.Delete(install_path); File.WriteAllText(Path.Combine(pathDownload, "version"), Convert.ToString(version)); }
/// <summary> /// Create a new instance of this artifact from a Octokit artifact /// </summary> /// <param name="releaseAsset">The release artifact to create this from</param> public Artifact(ReleaseAsset releaseAsset) { Name = releaseAsset.Name; DownloadUrl = releaseAsset.BrowserDownloadUrl; try { DownloadUri = new Uri(DownloadUrl); } catch (Exception) { } }
/// <summary> /// <para> /// Returns the URI that can be used to download a GitHub release asset. /// </para> /// <note> /// This works only for published releases. /// </note> /// </summary> /// <param name="release">The target release.</param> /// <param name="asset">The target asset.</param> /// <returns>The asset URI.</returns> public string GetAssetUri(Release release, ReleaseAsset asset) { Covenant.Requires <ArgumentNullException>(release != null, nameof(release)); Covenant.Requires <ArgumentNullException>(asset != null, nameof(asset)); var releasedAsset = release.Assets.SingleOrDefault(a => a.Id == asset.Id); if (releasedAsset == null) { throw new DeploymentException($"Asset [id={asset.Id}] is not present in release [id={release.Id}]."); } return(releasedAsset.BrowserDownloadUrl); }
private ITaskItem TaskItemFor(Release release, ReleaseAsset asset) { var item = new TaskItem(); // I don't think there's a way, via the API, to get something like this: // https://github.com/git-tfs/msbuild-tasks/releases/download/v0.0.9/GitTfsTasks-0.0.9.zip item.ItemSpec = "https://github.com/" + Repository + "/releases/download/" + TagName + "/" + asset.Name; item.MaybeSetMetadata("ContentType", asset.ContentType); item.MaybeSetMetadata("Id", asset.Id.ToString()); item.MaybeSetMetadata("Label", asset.Label); item.MaybeSetMetadata("Name", asset.Name); item.MaybeSetMetadata("State", asset.State); return(item); }
private static async Task Download(ReleaseAsset binary, Stream stream) { Trace.WriteLine(string.Format("Downloading new nightly build from {0} ({1:F2} MB)...", binary.BrowserDownloadUrl, binary.Size / 1024.0 / 1024.0)); HttpWebRequest request = WebRequest.CreateHttp(binary.BrowserDownloadUrl); request.AutomaticDecompression = DecompressionMethods.GZip; using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream respStream = response.GetResponseStream()) { await respStream.CopyToAsync(stream); } }
public static async Task <Release> LatestRelease() { if (release == null) { release = ( await Client.Repository.Release.GetAll("mat1jaczyyy", "apollo-studio") ).First(i => i.Prerelease == false); download = release.Assets.FirstOrDefault(i => i.Name.Contains( RuntimeInformation.IsOSPlatform(OSPlatform.Windows)? "Win.zip" : "Mac.zip" )); } return(release); }
private string VersionStringFromMsiAsset(ReleaseAsset asset) { if (asset.Name.EndsWith(".msi")) { string versionString = asset.Name.Replace("RecNForget.Setup.", string.Empty).Replace(".msi", string.Empty); Version version; if (Version.TryParse(versionString, out version)) { return(version.ToString()); } } return(string.Empty); }
public bool TryGetInstallerFromRelease(Release release, out ReleaseAsset installer) { if (release == null) { throw new ArgumentNullException(nameof(release)); } var is64bit = Environment.Is64BitProcess; installer = release.Assets .FirstOrDefault(asset => asset.Name .Equals($"ImageSort.{(is64bit ? "x64" : "x86")}.msi", StringComparison.OrdinalIgnoreCase)); return(installer != null); }
public async Task <Stream> GetStreamFromAssetAsync(ReleaseAsset asset) { using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("User-Agent", "Image-Sort"); try { return(await httpClient.GetStreamAsync(asset.BrowserDownloadUrl)); } catch (HttpRequestException) { return(null); } }
private void SelectButton_Click(object sender, RoutedEventArgs e) { if (host == "GameBanana") { KeyValuePair <String, GameBananaItemFile> selectedItem = (KeyValuePair <String, GameBananaItemFile>)FileGrid.SelectedItem; chosenFileUrl = selectedItem.Value.DownloadUrl; chosenFileName = selectedItem.Value.FileName; } else if (host == "GitHub") { ReleaseAsset selectedItem = (ReleaseAsset)FileGrid.SelectedItem; chosenFileUrl = selectedItem.BrowserDownloadUrl; chosenFileName = selectedItem.Name; } Close(); }