public async Task DownloadReleases(string updateUrlOrPath, IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null, IFileDownloader urlDownloader = null) { progress = progress ?? (_ => { }); urlDownloader = urlDownloader ?? new FileDownloader(); var packagesDirectory = Path.Combine(rootAppDirectory, "packages"); int current = 0; int toIncrement = (int)(100.0 / releasesToDownload.Count()); if (Utility.IsHttpUrl(updateUrlOrPath)) { // From Internet await releasesToDownload.ForEachAsync(async x => { var targetFile = Path.Combine(packagesDirectory, x.Filename); await downloadRelease(updateUrlOrPath, x, urlDownloader, targetFile); lock (progress) progress(current += toIncrement); }); } else { // From Disk await releasesToDownload.ForEachAsync(x => { var targetFile = Path.Combine(packagesDirectory, x.Filename); File.Copy( Path.Combine(updateUrlOrPath, x.Filename), targetFile, true); lock (progress) progress(current += toIncrement); }); } }
private async Task <XElement> TryDownloadFileAsync(IFileDownloader fileDownloader, CancellationToken cancellationToken) { await LogInfoAsync("Read file from client", cancellationToken).ConfigureAwait(false); using var stream = await fileDownloader.ReadFileAsync().ConfigureAwait(false); if (stream == null) { await LogInfoAsync("Read file completed. Client returned no data", cancellationToken).ConfigureAwait(false); return(null); } await LogInfoAsync("Read file completed. Client returned data", cancellationToken).ConfigureAwait(false); await LogInfoAsync("Converting data to XElement", cancellationToken).ConfigureAwait(false); // We're reading in our own XML file, but even so, use conservative settings // just to be on the safe side. First, disallow DTDs entirely (we will never // have one ourself). And also, prevent any external resolution of files when // processing the XML. var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; using var reader = XmlReader.Create(stream, settings); var result = XElement.Load(reader); await LogInfoAsync("Converting data to XElement completed", cancellationToken).ConfigureAwait(false); return(result); }
public void LaunchRClientSetup(ICoreShell coreShell, IFileDownloader downloader = null) { coreShell.Services.Telemetry.ReportEvent(TelemetryArea.Configuration, RtvsTelemetry.ConfigurationEvents.RClientInstallYes); downloader = downloader ?? new FileDownloader(); string downloadError = null; var rClientExe = Path.Combine(Path.GetTempPath(), "RClientSetup.exe"); LongOperationNotification.ShowWaitingPopup(Resources.DownloadingRClientInstaller, new LongAction[] { new LongAction() { Name = Resources.DownloadingRClientInstaller, Action = (o, ct) => { downloadError = downloader.Download("http://go.microsoft.com/fwlink/?LinkId=800048", rClientExe, ct); }, }, }, coreShell.Services.Log); if (!string.IsNullOrEmpty(downloadError)) { var errorMessage = string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToDownloadRClient, downloadError); coreShell.ShowErrorMessage(errorMessage); coreShell.Services.Telemetry.ReportEvent(TelemetryArea.Configuration, RtvsTelemetry.ConfigurationEvents.RClientDownloadFailed, errorMessage); coreShell.Services.Log.WriteAsync(LogVerbosity.Minimal, MessageCategory.Error, "Microsoft R Client download error: " + errorMessage).DoNotWait(); } else { // Suppress 'Operation canceled by the user' if user clicks 'No' to elevation dialog. try { coreShell.ShowMessage(Resources.PleaseRestartVisualStudioAfterRClientSetup, MessageButtons.OK); coreShell.Services.ProcessServices.Start(rClientExe); } catch (Win32Exception ex) { if((uint)ex.NativeErrorCode == 0x800704C7) { coreShell.Services.Telemetry.ReportEvent(TelemetryArea.Configuration, RtvsTelemetry.ConfigurationEvents.RClientInstallCancel); } } } }
public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); if (urlDownloader != null) { this.urlDownloader = urlDownloader; } else { this.urlDownloader = (Utility.IsFtpUrl(urlOrPath) ? (IFileDownloader) new FtpFileDownloader() : new FileDownloader()); } if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName); return; } this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName); }
public SurveyController(IUnitOfWork unitOfWork, IWebHostEnvironment hostingEnvironment, IFileDownloader fileDownloaderService, IAuthorizationService authorizationService, IAccountManager accountManager) { this._unitOfWork = unitOfWork; this._authorizationService = authorizationService; this._accountManager = accountManager; this._fileDownloader = fileDownloaderService; }
public Downloader(IFileDownloader fileDownloader, IFileSystem fileSystem, string product, IDownloadUrlResolver downloadUrlResolver) { _fileDownloader = fileDownloader; _fileSystem = fileSystem; _product = product; _downloadUrlResolver = downloadUrlResolver; }
public static async Task<UpdateManager> GitHubUpdateManager( string repoUrl, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null, bool prerelease = false) { var repoUri = new Uri(repoUrl); var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString()); if (repoUri.Segments.Count() != 3) { throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo"); } using (var client = new HttpClient() { BaseAddress = new Uri(gitHubUrl) }) { client.DefaultRequestHeaders.UserAgent.Add(userAgent); var response = await client.GetAsync(String.Format("/repos{0}/releases", repoUri.PathAndQuery)); response.EnsureSuccessStatusCode(); var releases = SimpleJson.DeserializeObject<List<Release>>(await response.Content.ReadAsStringAsync()); var latestRelease = releases .Where(x => prerelease ? x.Prerelease : !x.Prerelease) .OrderByDescending(x => x.PublishedAt) .First(); var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/"); return new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader); } }
public static async Task <UpdateManager> GitHubUpdateManager( string repoUrl, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null, bool prerelease = false) { var repoUri = new Uri(repoUrl); var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString()); if (repoUri.Segments.Count() != 3) { throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo"); } using (var client = new HttpClient() { BaseAddress = new Uri(gitHubUrl) }) { client.DefaultRequestHeaders.UserAgent.Add(userAgent); var response = await client.GetAsync(String.Format("/repos{0}/releases", repoUri.PathAndQuery)); response.EnsureSuccessStatusCode(); var releases = SimpleJson.DeserializeObject <List <Release> >(await response.Content.ReadAsStringAsync()); var latestRelease = releases .Where(x => prerelease ? x.Prerelease : !x.Prerelease) .OrderByDescending(x => x.PublishedAt) .First(); var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/"); return(new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader)); } }
public DucascopyDownloaderManager(IFileManager <DucascopySymbol> fileManager, IFileDownloader fileDownloader, IConfiguration configuration, IInstrumentManager <DucascopySymbol, DucascopyGroup> instrumentManager) { _fileManager = fileManager; _fileDownloader = fileDownloader; _configuration = configuration; _instrumentManager = instrumentManager; }
/// <summary> /// Starts retrieving the <paramref name="moduleInfo"/> and calls the <paramref name="callback"/> when it is done. /// </summary> /// <param name="moduleInfo">Module that should have it's type loaded.</param> /// <param name="callback">Delegate to be called when typeloading process completes or fails.</param> public void BeginLoadModuleType(ModuleInfo moduleInfo, ModuleTypeLoadedCallback callback) { Uri uriRef = new Uri(moduleInfo.Ref, UriKind.RelativeOrAbsolute); lock (this.typeLoadingCallbacks) { ModuleTypeLoaderCallbackMetadata callbackMetadata = new ModuleTypeLoaderCallbackMetadata() { Callback = callback, ModuleInfo = moduleInfo }; List <ModuleTypeLoaderCallbackMetadata> callbacks; if (this.typeLoadingCallbacks.TryGetValue(uriRef, out callbacks)) { callbacks.Add(callbackMetadata); return; } this.typeLoadingCallbacks[uriRef] = new List <ModuleTypeLoaderCallbackMetadata> { callbackMetadata }; } IFileDownloader downloader = this.CreateDownloader(); downloader.DownloadCompleted += this.OnDownloadCompleted; downloader.DownloadAsync(uriRef, uriRef); }
public void DownloadAsync_WhenRequestsTwoDifferentFilesSimultaneously_DownloadsConcurrently() { // Arrange int delay = 2000; IFileDownloader downloader = CreateFileDownloader(delay); FileDownloadManager manager = new FileDownloadManager(downloader); string file1 = "a file"; Task <FileResult> request1 = manager.DownloadAsync(file1); string file2 = "another file"; Task <FileResult> request2 = manager.DownloadAsync(file2); // Act Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Task.WaitAll(Task.Run(async() => await request1), Task.Run(async() => await request2)); stopwatch.Stop(); //Assert FileResult result1 = request1.Result; FileResult result2 = request2.Result; int timeRatio = GetTimeRation(stopwatch, delay); A.CallTo(() => downloader.DownloadAsync(A <string> .Ignored)).MustHaveHappenedTwiceExactly(); result1.FileDownloadName.Should().Be(file1); result2.FileDownloadName.Should().Be(file2); result1.Should().NotBeSameAs(result2); timeRatio.Should().Be(1); }
public void DownloadAsync_WhenRequestsFileBeingDownloadedAtTheMoment_WaitsForExistingRequestToFinishAndReturnsItsResult() { // Arrange int delay = 2000; IFileDownloader downloader = CreateFileDownloader(delay); FileDownloadManager manager = new FileDownloadManager(downloader); string file = "a file"; Task <FileResult> request1 = manager.DownloadAsync(file); Task <FileResult> request2 = manager.DownloadAsync(file); // Act Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Task.WaitAll(Task.Run(async() => await request1), Task.Run(async() => await request2)); stopwatch.Stop(); //Assert FileResult result1 = request1.Result; FileResult result2 = request2.Result; int timeRatio = GetTimeRation(stopwatch, delay); A.CallTo(() => downloader.DownloadAsync(A <string> .Ignored)).MustHaveHappenedOnceExactly(); result1.FileDownloadName.Should().Be(file); result2.FileDownloadName.Should().Be(file); result1.Should().BeSameAs(result2); timeRatio.Should().Be(1); }
public async void DownloadAsync_WhenRequestsFileAlreadyDownloaded_DownloadsIndependently() { // Arrange int delay = 2000; IFileDownloader downloader = CreateFileDownloader(delay); FileDownloadManager manager = new FileDownloadManager(downloader); string file = "a file"; Task <FileResult> request2 = manager.DownloadAsync(file); // Act Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); FileResult result1 = await manager.DownloadAsync(file); FileResult result2 = await manager.DownloadAsync(file); stopwatch.Stop(); //Assert int timeRatio = GetTimeRation(stopwatch, delay); A.CallTo(() => downloader.DownloadAsync(A <string> .Ignored)).MustHaveHappenedTwiceExactly(); result1.FileDownloadName.Should().Be(file); result2.FileDownloadName.Should().Be(file); result1.Should().NotBeSameAs(result2); timeRatio.Should().Be(2); }
public PseDownloadManager(IFileManager <PseSymbol> fileManager, IFileDownloader fileDownloader, IConfiguration configuration, IInstrumentManager <PseSymbol, PseGroup> instrumentManager) { _fileManager = fileManager; _fileDownloader = fileDownloader; _configuration = configuration; _instrumentManager = instrumentManager; }
public BigBlueButtonFacade(IFileDownloader fileDownloader, IVideoService videoService, IPresentationService presentationService) { _fileDownloader = fileDownloader; _videoService = videoService; _presentationService = presentationService; }
public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.urlDownloader = urlDownloader ?? new FileDownloader(); if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, applicationName); return; } // Determine the rootAppDirectory in such a way so that Portable // Apps are more likely to work var entry = Assembly.GetEntryAssembly(); if (entry != null) { rootDirectory = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(entry.Location), "..", "..")); } this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); }
internal static async Task GetMappingAsync(Model.Version version, Side side) { FileDownloadervar = new FileDownloader(); FileDownloadervar.DownloadProgressChanged += (sender, e) => { MappingDownloadProgressChanged.Invoke(sender, e); Debug.WriteLine(e.ProgressPercentage); }; FileDownloadervar.DownloadFileCompleted += (sender, e) => { if (e.State == CompletedState.Succeeded) { Debug.WriteLine("download mapping success"); MappingDownloadCompleted.Invoke(sender, e); } else { Debug.WriteLine("download mapping failed"); } }; VersionInfo versioninfo = await Json.GetWebRequestObjectAsync <VersionInfo>(version.JsonUrl); VersioninfoCache = versioninfo; if (side == Side.Client) { FileDownloadervar.DownloadFileAsync(versioninfo.Downloads.ClientMappings.url, WorkingFile.MappingInfoTxt); } else { FileDownloadervar.DownloadFileAsync(versioninfo.Downloads.ServerMappings.url, WorkingFile.MappingInfoTxt); } }
/// <summary> /// Download the new version of KinesisTap build using package Url and install it. /// </summary> /// <param name="packageVersion">an instance of <see cref="PackageVersionInfo"/> object.</param> public async Task DownloadAndInstallNewVersionAsync(PackageVersionInfo packageVersion) { //Upload the new version string packageUrl = packageVersion.PackageUrl.Replace("{Version}", packageVersion.Version); string extension = Path.GetExtension(packageUrl).ToLower(); if (!IsExtensionSuportedByPlatform(extension)) { _logger.LogWarning($"Extension {extension} is not supported on {Utility.Platform}"); return; } _logger?.LogInformation($"Downloading {packageVersion.Name} version {packageVersion.Version} from {packageUrl}..."); IFileDownloader downloader = CreateDownloaderFromUrl(packageUrl, _context); string updateDirectory = "update"; if (!Directory.Exists(updateDirectory)) { Directory.CreateDirectory(updateDirectory); } string downloadPath = Path.Combine(updateDirectory, Path.GetFileName(packageUrl)); if (File.Exists(downloadPath)) { File.Delete(downloadPath); } await downloader.DownloadFileAsync(packageUrl, downloadPath); _logger?.LogInformation($"Package downloaded to {downloadPath}. Expanding package..."); if (!_skipSignatureVerification) { if (EXT_MSI.Equals(extension, StringComparison.Ordinal)) { if (!await VerifyAuthenticodeSignatureAsync(_appDataFileProvider.GetFullPath(downloadPath))) { PublishCounter(UpdateMetricsConstants.PackageSignaturesInvalid, CounterTypeEnum.Increment, 1); _logger.LogWarning("Cannot verify digital signature for package {0}", downloadPath); return; } PublishCounter(UpdateMetricsConstants.PackageSignaturesValid, CounterTypeEnum.Increment, 1); } } else { _logger.LogInformation("Skipping digital signature verification"); } if (EXT_NUPKG.Equals(extension)) { await InstallNugetPackageAsync(downloadPath); } else { await InstallPackageAsync(downloadPath); } }
public IconStore(string directory, string placeholderImagePath, IFileAccess fileAccess, IFileDownloader downloader) { _fileDirectory = directory; _placeholderImagePath = placeholderImagePath; _fileAccess = fileAccess; _downloader = downloader; }
public EvilGlobalServices(IFileDownloadHelper downloadHelper, IFileDownloader fileDownloader, IStringDownloader stringDownloader, Func<ExportLifetimeContext<IHostChecker>> getHostChecker) { DownloadHelper = downloadHelper; Downloader = fileDownloader; StringDownloader = stringDownloader; GetHostChecker = getHostChecker; }
public Syncer(IFileDownloader fileDownloader, IFileService fileService) { _fileDownloader = fileDownloader; _fileService = fileService; _uriProvider = new AisUriProvider(); _listFile = Path.Combine(fileService.AppDir, _listFileName); _timer.Start(async() => await Sync(), _interval); }
public UpdateCommand(ITeamCityClient client, IFileSystem fileSystem, IFileDownloader downloader, IAssemblyMetada assemblyMetada, Settings settings) { _client = client; _fileSystem = fileSystem; _downloader = downloader; _assemblyMetada = assemblyMetada; _settings = settings; }
public Downloader(IFileDownloader fileDownloader, IFileSystem fileSystem, string product, string prefix, string target) { _fileDownloader = fileDownloader; _fileSystem = fileSystem; _product = product; _prefix = prefix; _target = target; }
public ArchiveContent CreateFromExisting(string name, string destination, IAbsoluteFilePath file, IFileDownloader downloader) { var ac = new ArchiveContent(name, destination, downloader); ac.ImportFromArchive(file); return(ac); }
public async Task DownloadReleases(string updateUrlOrPath, IEnumerable <ReleaseEntry> releasesToDownload, Action <int> progress = null, IFileDownloader urlDownloader = null) { progress = progress ?? (_ => { }); urlDownloader = urlDownloader ?? new FileDownloader(); var packagesDirectory = Path.Combine(rootAppDirectory, "packages"); double current = 0; var toIncrement = 100.0 / releasesToDownload.Count(); if (Utility.IsHttpUrl(updateUrlOrPath)) { // From Internet await releasesToDownload.ForEachAsync( async x => { var targetFile = Path.Combine(packagesDirectory, x.Filename); double component = 0; await DownloadRelease( updateUrlOrPath, x, urlDownloader, targetFile, p => { lock (progress) { current -= component; component = toIncrement / 100.0 * p; progress((int)Math.Round(current += component)); } }); ChecksumPackage(x); }); } else { // From Disk await releasesToDownload.ForEachAsync( x => { var targetFile = Path.Combine(packagesDirectory, x.Filename); File.Copy( Path.Combine(updateUrlOrPath, x.Filename), targetFile, true); lock (progress) { progress((int)Math.Round(current += toIncrement)); } ChecksumPackage(x); }); } }
public ArchiveContent CreateFromDownload(string destination, string url, IFileDownloader downloader) { var name = GetName(url.Split('/').Last()); var ac = new ArchiveContent(name, destination, downloader); ac.ImportFromDownload(url); return(ac); }
public GenerateEscrowCommand(ITeamCityClient client, GenerateEscrowUseCase generateEscrowUseCase, ICommand downloadCommand, IFileSystem fileSystem, IFileDownloader downloader) { _client = client; _generateEscrowUseCase = generateEscrowUseCase; _downloadCommand = downloadCommand; _fileSystem = fileSystem; _downloader = downloader; }
public void Run(String Url, String DestinationFile) { fileDownloader = new FileDownloader.FileDownloader(); fileDownloader.DownloadFileCompleted += DownloadFileCompleted; fileDownloader.DownloadProgressChanged += OnDownloadProgressChanged; fileDownloader.DownloadFileAsync(new Uri(Url), DestinationFile); }
public TestUpdateCommand(ITeamCityClient client, IFileSystem fileSystem, IFileDownloader downloader, IAssemblyMetada assemblyMetada, Settings settings) : base(client, fileSystem, downloader, assemblyMetada, settings) { Client = client; FileSystem = fileSystem; Downloader = downloader; AssemblyMetada = assemblyMetada; Settings = settings; }
public static void SetFailedDownloadResultFor(this IFileDownloader downloader, string url) { var downloadResult = Substitute.For <IDownloadResult>(); downloadResult.Url.Returns(url); downloadResult.Success.Returns(false); downloadResult.Data.Returns((byte[])null); downloader.SetDownloadResult(url, downloadResult); }
public DownloadTask(string storagePath, string name, RefreshUri getDownloadUri, EventHandler <DownloadFileCompletedArgs> downloadFileCompleted, EventHandler <DownloadFileProgressChangedArgs> downloadFileProgressChanged) { Path = storagePath; Name = name; fileDownloader = new FileDownloadTask(Path, getDownloadUri, name); fileDownloader.DownloadFileCompleted += downloadFileCompleted; fileDownloader.DownloadProgressChanged += downloadFileProgressChanged; }
public ArticleViewModel(IEventAggregator eventAggregator, IFileDownloader fileDownloader) { _eventAggregator = eventAggregator; _fileDownloader = fileDownloader; _fileDownloader.DownloadCompleted += FileDownloaderDownloadCompleted; _eventAggregator.GetEvent<MenuItemChangedEvent>().Subscribe(ShowArticle); Close = new DelegateCommand<object>(CloseExecuted); }
public static void SetDownloadResult(this IFileDownloader downloader, string url, byte[] data) { var downloadResult = Substitute.For <IDownloadResult>(); downloadResult.Success.Returns(true); downloadResult.Data.Returns(data); downloadResult.Url.Returns(url); downloader.SetDownloadResult(url, downloadResult); }
public ArchiveContent CreateFromExisting(IAbsoluteDirectoryPath destination, IAbsoluteFilePath file, IFileDownloader downloader) { var name = GetName(file.ToString()); var ac = new ArchiveContent(name, destination.ToString(), downloader); ac.ImportFromArchive(file); return(ac); }
public DownloadAndInstaller(IFileDownloader downloader, StatusRepo statusRepo, string file, IAbsoluteDirectoryPath destination, IRestarter restarter) { _downloader = downloader; _statusRepo = statusRepo; _file = file; _destination = destination; _restarter = restarter; _sourceFile = Common.Paths.TempPath.GetChildFileWithName(_file); _progress = new Status(_file, statusRepo, 0, 0, default(TimeSpan?), RepoStatus.Downloading); }
public void DownloadAndInstallPackage() { this.InnerFileDownloader = new FileDownloader(); this.InnerFileDownloader.DownloadProgressChanged += this.OnDownloadProgressChanged; this.InnerFileDownloader.DownloadFileCompleted += this.OnDownloadFileCompleted; string destinationPath = AppDomain.CurrentDomain.BaseDirectory + @"\Package.zip"; this.InnerFileDownloader.DownloadFileAsync(this.PackageUri, destinationPath); }
public TurnoutCrawler(IServiceProvider serviceProvider, IOptions <LiveElectionSettings> options, IFileDownloader fileDownloader, IAppCache appCache) { _serviceProvider = serviceProvider; _fileDownloader = fileDownloader; _appCache = appCache; _settings = options.Value; }
public FileDownloadHelper(IFileDownloader downloader, Func<IMirrorSelector, ExportLifetimeContext<IMultiMirrorFileDownloader>> createMultiMirrorFileDownloader, Func<IReadOnlyCollection<Uri>, ExportLifetimeContext<IMirrorSelector>> createMirrorSelector, Func<int, IReadOnlyCollection<Uri>, ExportLifetimeContext<IMirrorSelector>> createMirrorSelectorWithLimit, Func<IMultiMirrorFileDownloader, ExportLifetimeContext<IFileQueueDownloader>> createQueueDownloader) { _downloader = downloader; _createMirrorSelector = createMirrorSelector; _createMirrorSelectorWithLimit = createMirrorSelectorWithLimit; _createMultiMirrorFileDownloader = createMultiMirrorFileDownloader; _createQueueDownloader = createQueueDownloader; }
Task downloadRelease(string updateBaseUrl, ReleaseEntry releaseEntry, IFileDownloader urlDownloader, string targetFile) { if (!updateBaseUrl.EndsWith("/")) { updateBaseUrl += '/'; } var sourceFileUrl = new Uri(new Uri(updateBaseUrl), releaseEntry.BaseUrl + releaseEntry.Filename).AbsoluteUri; File.Delete(targetFile); return urlDownloader.DownloadFile(sourceFileUrl, targetFile); }
public ArchiveContent(string name, string destination, IFileDownloader downloader) { Contract.Requires<ArgumentNullException>(name != null); Contract.Requires<ArgumentNullException>(destination != null); Name = name; Destination = System.IO.Path.GetFullPath(destination); _downloader = downloader; Path = System.IO.Path.GetFullPath(System.IO.Path.Combine(Destination, Name)); RepoPath = System.IO.Path.Combine(Path, RepoFolder); RepoTmpPath = System.IO.Path.Combine(RepoPath, "tmp").ToAbsoluteDirectoryPath(); ArchivePath = System.IO.Path.Combine(RepoPath, Name + ArchiveExtension).ToAbsoluteFilePath(); }
public static async Task<UpdateManager> GitHubUpdateManager( string repoUrl, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null, bool prerelease = false, string accessToken = null) { var repoUri = new Uri(repoUrl); var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString()); if (repoUri.Segments.Length != 3) { throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo"); } var releasesApiBuilder = new StringBuilder("repos") .Append(repoUri.AbsolutePath) .Append("/releases"); if (!string.IsNullOrWhiteSpace(accessToken)) releasesApiBuilder.Append("?access_token=").Append(accessToken); Uri baseAddress; if (repoUri.Host.EndsWith("github.com", StringComparison.OrdinalIgnoreCase)) { baseAddress = new Uri("https://api.github.com/"); } else { // if it's not github.com, it's probably an Enterprise server // now the problem with Enterprise is that the API doesn't come prefixed // it comes suffixed // so the API path of http://internal.github.server.local API location is // http://interal.github.server.local/api/v3. baseAddress = new Uri(string.Format("{0}{1}{2}/api/v3/", repoUri.Scheme, Uri.SchemeDelimiter, repoUri.Host)); } // above ^^ notice the end slashes for the baseAddress, explained here: http://stackoverflow.com/a/23438417/162694 using (var client = new HttpClient() { BaseAddress = baseAddress }) { client.DefaultRequestHeaders.UserAgent.Add(userAgent); var response = await client.GetAsync(releasesApiBuilder.ToString()); response.EnsureSuccessStatusCode(); var releases = SimpleJson.DeserializeObject<List<Release>>(await response.Content.ReadAsStringAsync()); var latestRelease = releases .Where(x => prerelease || !x.Prerelease) .OrderByDescending(x => x.PublishedAt) .First(); var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/"); return new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader); } }
Task downloadRelease(string updateBaseUrl, ReleaseEntry releaseEntry, IFileDownloader urlDownloader, string targetFile, Action<int> progress) { var baseUri = Utility.EnsureTrailingSlash(new Uri(updateBaseUrl)); var releaseEntryUrl = releaseEntry.BaseUrl + releaseEntry.Filename; if (!String.IsNullOrEmpty(releaseEntry.Query)) { releaseEntryUrl += releaseEntry.Query; } var sourceFileUrl = new Uri(baseUri, releaseEntryUrl).AbsoluteUri; File.Delete(targetFile); return urlDownloader.DownloadFile(sourceFileUrl, targetFile, progress); }
public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); this.urlDownloader = urlDownloader ?? new FileDownloader(); this.rootAppDirectory = rootDirectory ?? Path.Combine(GetLocalAppDataDirectory(), "Fusetools", this.applicationName, "App"); this.Log().Info(this.rootAppDirectory); }
Task downloadRelease(string updateBaseUrl, ReleaseEntry releaseEntry, IFileDownloader urlDownloader, string targetFile, Action<int> progress) { if (!updateBaseUrl.EndsWith("/")) { updateBaseUrl += '/'; } var releaseEntryUrl = releaseEntry.BaseUrl + releaseEntry.Filename; if (!String.IsNullOrEmpty(releaseEntry.Query)) { releaseEntryUrl += releaseEntry.Query; } var sourceFileUrl = new Uri(new Uri(updateBaseUrl), releaseEntryUrl).AbsoluteUri; File.Delete(targetFile); return urlDownloader.DownloadFile(sourceFileUrl, targetFile, progress); }
public SelfUpdater(Func<bool> enableBeta, IEventAggregator eventBus, IProcessManager processManager, IFileDownloader downloader, IMediator mediator, ExportFactory<IWebClient> webClientFactory, IRestarter restarter) { _eventBus = eventBus; _processManager = processManager; _downloader = downloader; _mediator = mediator; _webClientFactory = webClientFactory; _restarter = restarter; _enableBeta = enableBeta; Status = new TransferStatus("Play withSIX update.exe"); Destination = Common.Paths.TempPath.GetChildFileWithName(Exe); _localProductCode = GetLocalProduct(); _entryAssemblyLocation = Common.Paths.EntryLocation; _entryAssemblyLocalVersion = GetLocalVersion(); }
public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); this.urlDownloader = urlDownloader ?? new FileDownloader(); }
public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); this.urlDownloader = urlDownloader ?? new FileDownloader(); if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName); return; } this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName); }
public async Task DownloadReleases(string updateUrlOrPath, IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null, IFileDownloader urlDownloader = null) { progress = progress ?? (_ => { }); urlDownloader = urlDownloader ?? new FileDownloader(); int current = 0; int toIncrement = (int)(100.0 / releasesToDownload.Count()); if (Utility.IsHttpUrl(updateUrlOrPath)) { await releasesToDownload.ForEachAsync(async x => { await urlDownloader.DownloadFile( String.Format("{0}/{1}", updateUrlOrPath, x.Filename), Path.Combine(rootAppDirectory, "packages", x.Filename)); lock (progress) progress(current += toIncrement); }); } else { await releasesToDownload.ForEachAsync(x => { File.Copy( Path.Combine(updateUrlOrPath, x.Filename), Path.Combine(rootAppDirectory, "packages", x.Filename)); lock (progress) progress(current += toIncrement); }); } }
public ArchiveContent(string name, DirectoryInfo destination, IFileDownloader downloader) : this(name, destination.FullName, downloader) {}
public MultiMirrorFileDownloader(IFileDownloader downloader, IMirrorSelector mirrorSelector) { _downloader = downloader; _mirrorStrategy = mirrorSelector; }
public ArchiveContent CreateFromDownload(string destination, string url, IFileDownloader downloader) { var name = GetName(url.Split('/').Last()); var ac = new ArchiveContent(name, destination, downloader); ac.ImportFromDownload(url); return ac; }
public ProfilePhotoUrlFetcher(IFileDownloader downloader) { _downloader = downloader; }
public StringDownloader(IFileDownloader downloader) { _downloader = downloader; }
public TestableXapModuleTypeLoader(IFileDownloader downloader) { this.FileDownloader = downloader; }
public DataDownloader(IFileDownloader downloader) { _downloader = downloader; }
public async Task<UpdateInfo> CheckForUpdate( string localReleaseFile, string updateUrlOrPath, bool ignoreDeltaUpdates = false, Action<int> progress = null, IFileDownloader urlDownloader = null) { progress = progress ?? (_ => { }); var localReleases = Enumerable.Empty<ReleaseEntry>(); bool shouldInitialize = false; try { localReleases = Utility.LoadLocalReleases(localReleaseFile); } catch (Exception ex) { // Something has gone pear-shaped, let's start from scratch this.Log().WarnException("Failed to load local releases, starting from scratch", ex); shouldInitialize = true; } if (shouldInitialize) await initializeClientAppDirectory(); string releaseFile; var latestLocalRelease = localReleases.Count() > 0 ? localReleases.MaxBy(x => x.Version).First() : default(ReleaseEntry); // Fetch the remote RELEASES file, whether it's a local dir or an // HTTP URL if (Utility.IsHttpUrl(updateUrlOrPath)) { if (updateUrlOrPath.EndsWith("/")) { updateUrlOrPath = updateUrlOrPath.Substring(0, updateUrlOrPath.Length - 1); } this.Log().Info("Downloading RELEASES file from {0}", updateUrlOrPath); int retries = 3; retry: try { var url = String.Format("{0}/{1}", updateUrlOrPath, "RELEASES"); if (latestLocalRelease != null) { url = String.Format("{0}/RELEASES?id={1}&localVersion={2}&arch={3}", updateUrlOrPath, Uri.EscapeUriString(latestLocalRelease.PackageName), Uri.EscapeUriString(latestLocalRelease.Version.ToString()), Environment.Is64BitOperatingSystem ? "amd64" : "x86"); } var data = await urlDownloader.DownloadUrl(url); releaseFile = Encoding.UTF8.GetString(data); } catch (WebException ex) { this.Log().InfoException("Download resulted in WebException (returning blank release list)", ex); if (retries <= 0) throw; retries--; goto retry; } progress(33); } else { this.Log().Info("Reading RELEASES file from {0}", updateUrlOrPath); if (!Directory.Exists(updateUrlOrPath)) { var message = String.Format( "The directory {0} does not exist, something is probably broken with your application", updateUrlOrPath); throw new Exception(message); } var fi = new FileInfo(Path.Combine(updateUrlOrPath, "RELEASES")); if (!fi.Exists) { var message = String.Format( "The file {0} does not exist, something is probably broken with your application", fi.FullName); this.Log().Warn(message); var packages = (new DirectoryInfo(updateUrlOrPath)).GetFiles("*.nupkg"); if (packages.Length == 0) { throw new Exception(message); } // NB: Create a new RELEASES file since we've got a directory of packages ReleaseEntry.WriteReleaseFile( packages.Select(x => ReleaseEntry.GenerateFromFile(x.FullName)), fi.FullName); } releaseFile = File.ReadAllText(fi.FullName, Encoding.UTF8); progress(33); } var ret = default(UpdateInfo); var remoteReleases = ReleaseEntry.ParseReleaseFile(releaseFile); progress(66); if (!remoteReleases.Any()) { throw new Exception("Remote release File is empty or corrupted"); } ret = determineUpdateInfo(localReleases, remoteReleases, ignoreDeltaUpdates); progress(100); return ret; }
public async Task<UpdateInfo> CheckForUpdate( string localReleaseFile, string updateUrlOrPath, bool ignoreDeltaUpdates = false, Action<int> progress = null, IFileDownloader urlDownloader = null) { progress = progress ?? (_ => { }); var localReleases = Enumerable.Empty<ReleaseEntry>(); bool shouldInitialize = false; try { localReleases = LoadLocalReleases(localReleaseFile); } catch (Exception ex) { // Something has gone pear-shaped, let's start from scratch this.Log().WarnException("Failed to load local releases, starting from scratch", ex); shouldInitialize = true; } if (shouldInitialize) await initializeClientAppDirectory(); string releaseFile; // Fetch the remote RELEASES file, whether it's a local dir or an // HTTP URL if (Utility.IsHttpUrl(updateUrlOrPath)) { this.Log().Info("Downloading RELEASES file from {0}", updateUrlOrPath); try { var data = await urlDownloader.DownloadUrl(String.Format("{0}/{1}", updateUrlOrPath, "RELEASES")); releaseFile = Encoding.UTF8.GetString(data); } catch (WebException ex) { this.Log().InfoException("Download resulted in WebException (returning blank release list)", ex); releaseFile = String.Empty; } progress(33); } else { this.Log().Info("Reading RELEASES file from {0}", updateUrlOrPath); if (!Directory.Exists(updateUrlOrPath)) { var message = String.Format( "The directory {0} does not exist, something is probably broken with your application", updateUrlOrPath); throw new Exception(message); } var fi = new FileInfo(Path.Combine(updateUrlOrPath, "RELEASES")); if (!fi.Exists) { var message = String.Format( "The file {0} does not exist, something is probably broken with your application", fi.FullName); this.Log().Warn(message); var packages = (new DirectoryInfo(updateUrlOrPath)).GetFiles("*.nupkg"); if (packages.Length == 0) { throw new Exception(message); } // NB: Create a new RELEASES file since we've got a directory of packages ReleaseEntry.WriteReleaseFile( packages.Select(x => ReleaseEntry.GenerateFromFile(x.FullName)), fi.FullName); } releaseFile = File.ReadAllText(fi.FullName, Encoding.UTF8); progress(33); } var ret = default(UpdateInfo); var remoteReleases = ReleaseEntry.ParseReleaseFile(releaseFile); progress(66); if (remoteReleases.Any()) { ret = determineUpdateInfo(localReleases, remoteReleases, ignoreDeltaUpdates); } progress(100); return ret; }
protected FilesInstaller(IFileDownloader downloader, IRestarter restarter) { _downloader = downloader; _restarter = restarter; }
public LoggingFileDownloaderDecorator(IFileDownloader downloader) { _downloader = downloader; }