Пример #1
0
        public void TestInitialize()
        {
            var logger   = new Mock <ILogger>();
            var iOHelper = new Mock <IIOHelper>();

            strategy = new UriDownloadStrategy(logger.Object, iOHelper.Object);
        }
Пример #2
0
 private static IDownloadStrategy AsTemporarilyIgnored(this IDownloadStrategy effectiveStrategy, int?maxFileAgeInMinutes, string target)
 {
     if (maxFileAgeInMinutes.HasValue)
     {
         return(new TemporarilyIgnoreUpdatesDownloadStrategy(effectiveStrategy, new FileSystemProxy(), target, maxFileAgeInMinutes.Value));
     }
     return(effectiveStrategy);
 }
Пример #3
0
 private static IDownloadStrategy AsCached(this IDownloadStrategy effectiveStrategy, bool ignoreCache)
 {
     if (ignoreCache)
     {
         return(effectiveStrategy);
     }
     return(new CacheDownloadStrategy(effectiveStrategy, new DirectoryProxy(), new FileProxy()));
 }
Пример #4
0
        public CacheDownloadStrategy(IDownloadStrategy effectiveStrategy, IFileSystemProxy fileSystemProxy)
        {
            if (effectiveStrategy == null)
                throw new ArgumentException("CacheDownloadStrategy needs a non-null effective strategy");
            if (effectiveStrategy.FallbackStrategy != null)
                throw new ArgumentException("CacheDownloadStrategy should not have a fallback strategy");

            EffectiveStrategy = effectiveStrategy;
            FileSystemProxy = fileSystemProxy;
        }
Пример #5
0
 public CrawlerThread(
     ILogger logger,
     SimpleDownloadStrategy downloadStrategy,
     PostgreSqlContext context,
     EntityManager entityManager
     )
 {
     _logger           = logger;
     _downloadStrategy = downloadStrategy;
     _context          = context;
     _entityManager    = entityManager;
     _waitingWebsites  = context.CrawlerWebsites.Where(website => !website.Crawled);
 }
        public CacheDownloadStrategy(IDownloadStrategy effectiveStrategy, IFileSystemProxy fileSystemProxy)
        {
            if (effectiveStrategy == null)
            {
                throw new ArgumentException("CacheDownloadStrategy needs a non-null effective strategy");
            }
            if (effectiveStrategy.FallbackStrategy != null)
            {
                throw new ArgumentException("CacheDownloadStrategy should not have a fallback strategy");
            }

            EffectiveStrategy = effectiveStrategy;
            FileSystemProxy   = fileSystemProxy;
        }
        public TemporarilyIgnoreUpdatesDownloadStrategy(
            IDownloadStrategy effectiveStrategy, 
            IFileProxy fileProxy,
            string target,
            int maxFileAgeOfPaketExeInMinutes)
        {
            if (effectiveStrategy == null)
                throw new ArgumentException("TemporarilyIgnoreUpdatesDownloadStrategy needs a non-null effective strategy");

            if (string.IsNullOrEmpty(target))
                throw new ArgumentException("TemporarilyIgnoreUpdatesDownloadStrategy needs a non-empty target");

            _effectiveStrategy = effectiveStrategy;
            _maxFileAgeOfPaketExeInMinutes = maxFileAgeOfPaketExeInMinutes;
            _fileProxy = fileProxy;

            _target = target;
        }
        public TemporarilyIgnoreUpdatesDownloadStrategy(
            IDownloadStrategy effectiveStrategy, 
            IFileSystemProxy fileSystemProxy,
            string target,
            int maxFileAgeOfPaketExeInMinutes)
        {
            if (effectiveStrategy == null)
                throw new ArgumentException("TemporarilyIgnoreUpdatesDownloadStrategy needs a non-null effective strategy");

            if (string.IsNullOrEmpty(target))
                throw new ArgumentException("TemporarilyIgnoreUpdatesDownloadStrategy needs a non-empty target");
            
            _effectiveStrategy = effectiveStrategy;
            _maxFileAgeOfPaketExeInMinutes = maxFileAgeOfPaketExeInMinutes;
            this.fileSystemProxy = fileSystemProxy;

            _target = target;
        }
        public void Run()
        {
            Console.WriteLine(
                "Select a browser to use:{0}1. Mozilla Firefox{0}2. Google Chrome",
                Environment.NewLine);
            Console.Write("Selected browser: ");
            int browserType = int.Parse(Console.ReadLine());
            this.Browser = BrowserFactory.GetBrowser((BrowserType)browserType);
            Console.Clear();

            this.Browser.Navigate().GoToUrl(Constants.BaseSiteUrl);

            Console.WriteLine(
                "Select a download strategy:{0}1. Category{0}2. Search{0}3. Latest wallpapers{0}4. Top wallpapers",
                Environment.NewLine);
            Console.Write("Selected strategy: ");
            int downloadStrategyType = int.Parse(Console.ReadLine());
            this.Strategy = DownloadStrategyFactory.GetStrategy((DownloadStrategyType)downloadStrategyType, this.Browser);
            this.Strategy.Execute();
        }
Пример #10
0
        public Manager(string PATH)
        {
            EndPointFactory   factory1         = EndPointFactory.GetInstance();
            IEndPoint         endPoint         = factory1.CreateEndPoint();
            IUrl              url              = endPoint.GetUrl(PATH);
            IDownloadStrategy downloadStrategy = endPoint.GetDownloadStrategy();

            (IStatusCode, string)result = endPoint.Download(downloadStrategy, url);

            if (result.Item1.GetStatusCode() != 0)
            {
                throw new RuntimeException("Failed to download: " + result.Item1.GetStatusCode());
            }
            else
            {
                ClassCreatorFactory factory2     = ClassCreatorFactory.GetInstance();
                IClassCreator       classCreator = factory2.CreateClassCreator();
                url.SetBody(result.Item2);
                IClassCreatorStrategy creatorStrategy = classCreator.GetClassCreatorStrategy();
                var res = classCreator.CreateClass(creatorStrategy, url);
            }
        }
        public string GetLatestVersion(bool ignorePrerelease, bool silent)
        {
            try
            {
                return FallbackStrategy.GetLatestVersion(ignorePrerelease, silent);
            }
            catch (WebException)
            {
                if (FallbackStrategy.FallbackStrategy != null)
                {
                    FallbackStrategy = FallbackStrategy.FallbackStrategy;
                    return GetLatestVersion(ignorePrerelease, silent);
                }

                var latestVersion = GetLatestVersionInCache(ignorePrerelease);

                if (!silent)
                    Console.WriteLine("Unable to look up the latest version online, the cache contains version {0}.", latestVersion);

                return latestVersion;
            }
        }
Пример #12
0
        public string GetLatestVersion(bool ignorePrerelease, bool silent)
        {
            try
            {
                return(FallbackStrategy.GetLatestVersion(ignorePrerelease, silent));
            }
            catch (WebException)
            {
                if (FallbackStrategy.FallbackStrategy != null)
                {
                    FallbackStrategy = FallbackStrategy.FallbackStrategy;
                    return(GetLatestVersion(ignorePrerelease, silent));
                }

                var latestVersion = GetLatestVersionInCache(ignorePrerelease);

                if (!silent)
                {
                    Console.WriteLine("Unable to look up the latest version online, the cache contains version {0}.", latestVersion);
                }

                return(latestVersion);
            }
        }
Пример #13
0
        public void Process(string sources)
        {
            //TODO : Move this logic to separate windows service and make the service listen on Message Queue like Rabbitmq

            logger.AddInformationLog($"sources value: {sources}");

            //Data validations
            if (string.IsNullOrWhiteSpace(sources))
            {
                throw new ArgumentException($"The sources Is null or empty string.");
            }

            string delimiter = ConfigurationManager.AppSettings["Delimiter"];

            logger.AddInformationLog($"Delimiter config value: {delimiter}");

            string sourcesParsingDelimiter = string.IsNullOrWhiteSpace(delimiter) ? "," : delimiter;

            logger.AddInformationLog($"Sources parsing delimiter: {sourcesParsingDelimiter}");

            string localPath = ConfigurationManager.AppSettings["LocalDirectory"];

            logger.AddInformationLog($"LocalDirectory config value: {localPath}");

            List <string> soursesUrls = parser.Parse(sources, sourcesParsingDelimiter).ToList();

            logger.AddInformationLog($"sourses Urls counts after parsing: {soursesUrls?.Count}");

            ConcurrentQueue <Exception> exceptions = new ConcurrentQueue <Exception>();

            using (repoDownloadedFile)
            {
                Parallel.ForEach(soursesUrls, url =>
                {
                    try
                    {
                        IDownloadStrategy downloadStrategy = downloadStrategyFactory.Build(url);

                        string physicalPath = downloadStrategy.Download(url, localPath);
                        string virtualPath  = $"{localPath.Replace('\\', '/')}/{Path.GetFileName(physicalPath)}";
                        logger.AddInformationLog($"Local path is: {localPath} for URL: {url} ");

                        repoDownloadedFile.Add(new DomainModels.DownloadedFile()
                        {
                            FileRemotePath   = url,
                            LocalPath        = virtualPath,
                            ProcessingStatus = (int)DownloadStatutes.ReadyForProcessing,
                        });

                        repoDownloadedFile.SaveChanges();

                        logger.AddInformationLog($"Source :{url} saved to the database with status ready for processing");
                    }
                    catch (Exception ex)
                    {
                        exceptions.Enqueue(ex);
                        logger.AddErrorLog(ex);
                    }
                });

                if (exceptions.Any())
                {
                    throw new AggregateException(exceptions);
                }
            }
        }
Пример #14
0
        private static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, bool silent)
        {
            Action <Exception> handleException = exception =>
            {
                if (!File.Exists(dlArgs.Target))
                {
                    Environment.ExitCode = 1;
                }
                BootstrapperHelper.WriteConsoleError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };

            try
            {
                var localVersion = BootstrapperHelper.GetLocalFileVersion(dlArgs.Target);

                var latestVersion = dlArgs.LatestVersion;
                if (latestVersion == String.Empty)
                {
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                }

                if (dlArgs.DoSelfUpdate)
                {
                    if (!silent)
                    {
                        Console.WriteLine("Trying self update");
                    }
                    downloadStrategy.SelfUpdate(latestVersion, silent);
                }
                else
                {
                    if (!localVersion.StartsWith(latestVersion))
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target, silent);
                        if (!silent)
                        {
                            Console.WriteLine("Done.");
                        }
                    }
                    else
                    {
                        if (!silent)
                        {
                            Console.WriteLine("Paket.exe {0} is up to date.", localVersion);
                        }
                    }
                }
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!File.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        if (!silent)
                        {
                            Console.WriteLine("'{0}' download failed. Try fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        }
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, silent);
                        shouldHandleException = !File.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                {
                    handleException(exn);
                }
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #15
0
        public static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, IFileSystemProxy fileSystemProxy, Action onSuccess)
        {
            Action <Exception> handleException = exception =>
            {
#if DEBUG
                Environment.ExitCode = 1;
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.ToString(), downloadStrategy.Name));
                return;
#else
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
                if (!fileSystemProxy.FileExists(dlArgs.Target))
                {
                    Environment.ExitCode = 1;
                }
                else
                {
                    fileSystemProxy.WaitForFileFinished(dlArgs.Target);
                    onSuccess();
                }
#endif
            };

            try
            {
                string versionRequested;
                if (!dlArgs.IgnorePrerelease)
                {
                    versionRequested = "prerelease requested";
                }
                else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                {
                    versionRequested = "downloading latest stable";
                }
                else
                {
                    versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);
                }

                ConsoleImpl.WriteInfo("Checking Paket version ({0})...", versionRequested);
                ConsoleImpl.WriteTrace("Target path is {0}", dlArgs.Target);
                var localVersion = fileSystemProxy.GetLocalFileVersion(dlArgs.Target);
                ConsoleImpl.WriteTrace("File in target path version: v{0}", string.IsNullOrEmpty(localVersion) ? "UNKNOWN" : localVersion);

                var specificVersionRequested = true;
                var latestVersion            = dlArgs.LatestVersion;

                if (latestVersion == string.Empty)
                {
                    ConsoleImpl.WriteTrace("No version specified, checking online...");

                    var getLatestVersionWatch = Stopwatch.StartNew();
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                    getLatestVersionWatch.Stop();

                    ConsoleImpl.WriteTrace("Latest version check found v{0} in {1:0.##} second(s)", latestVersion, getLatestVersionWatch.Elapsed.TotalSeconds);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    ConsoleImpl.WriteInfo("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    if (currentSemVer.PreRelease != null && dlArgs.IgnorePrerelease)
                    {
                        currentSemVer = new SemVer();
                    }
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison   = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        PaketHashFile hashFile = null;
                        if (downloadStrategy.CanDownloadHashFile)
                        {
                            ConsoleImpl.WriteTrace("Downloading hash for v{0} ...", latestVersion);
                            var downloadHashWatch = Stopwatch.StartNew();
                            hashFile = downloadStrategy.DownloadHashFile(latestVersion);
                            downloadHashWatch.Stop();

                            ConsoleImpl.WriteTrace("Hash download took {0:0.##} second(s)", downloadHashWatch.Elapsed.TotalSeconds);
                        }

                        ConsoleImpl.WriteTrace("Downloading v{0} ...", latestVersion);

                        var downloadWatch = Stopwatch.StartNew();
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target, hashFile);
                        downloadWatch.Stop();

                        ConsoleImpl.WriteTrace("Download took {0:0.##} second(s)", downloadWatch.Elapsed.TotalSeconds);
                        ConsoleImpl.WriteInfo("Done in {0:0.##} second(s).", executionWatch.Elapsed.TotalSeconds);
                    }
                    else
                    {
                        ConsoleImpl.WriteInfo("Paket.exe {0} is up to date.", localVersion);
                    }
                }

                executionWatch.Stop();
                ConsoleImpl.WriteTrace("Paket Bootstrapping took {0:0.##} second(s)", executionWatch.Elapsed.TotalSeconds);

                onSuccess();
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!fileSystemProxy.FileExists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        ConsoleImpl.WriteInfo("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, fileSystemProxy, onSuccess);
                        shouldHandleException = !fileSystemProxy.FileExists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                {
                    handleException(exn);
                }
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #16
0
 public NumerekFlow(IDownloadStrategy strategy)
 {
     this.Strategy = strategy;
 }
Пример #17
0
        private static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, bool silent)
        {
            Action <Exception> handleException = exception =>
            {
                if (!File.Exists(dlArgs.Target))
                {
                    Environment.ExitCode = 1;
                }
                BootstrapperHelper.WriteConsoleError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };

            try
            {
                var localVersion = BootstrapperHelper.GetLocalFileVersion(dlArgs.Target);

                var latestVersion = dlArgs.LatestVersion;
                if (latestVersion == String.Empty)
                {
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                }

                if (dlArgs.DoSelfUpdate)
                {
                    if (!silent)
                    {
                        Console.WriteLine("Trying self update");
                    }
                    downloadStrategy.SelfUpdate(latestVersion, silent);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    var latestSemVer  = SemVer.Create(latestVersion);
                    if (currentSemVer.CompareTo(latestSemVer) != 0)
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target, silent);
                        if (!silent)
                        {
                            Console.WriteLine("Done.");
                        }
                    }
                    else
                    {
                        if (!silent)
                        {
                            Console.WriteLine("Paket.exe {0} is up to date.", localVersion);
                        }
                    }
                }
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!File.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        if (!silent)
                        {
                            Console.WriteLine("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.",
                                              downloadStrategy.Name, fallbackStrategy.Name);
                        }
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, silent);
                        shouldHandleException = !File.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                {
                    handleException(exn);
                }
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #18
0
        private static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, bool silent)
        {
            Action<Exception> handleException = exception =>
            {
                if (!File.Exists(dlArgs.Target))
                    Environment.ExitCode = 1;
                BootstrapperHelper.WriteConsoleError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };
            try
            {
                if (!silent)
                {
                    string versionRequested;
                    if (!dlArgs.IgnorePrerelease)
                        versionRequested = "prerelease requested";
                    else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                        versionRequested = "downloading latest stable";
                    else
                        versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);

                    Console.WriteLine("Checking Paket version ({0})...", versionRequested);
                }

                var localVersion = BootstrapperHelper.GetLocalFileVersion(dlArgs.Target);

                var specificVersionRequested = true;
                var latestVersion = dlArgs.LatestVersion;

                if (latestVersion == String.Empty)
                {
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease, silent);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    if (!silent)
                        Console.WriteLine("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion, silent);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target, silent);
                        if (!silent)
                            Console.WriteLine("Done.");
                    }
                    else
                    {
                        if (!silent)
                            Console.WriteLine("Paket.exe {0} is up to date.", localVersion);
                    }
                }
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!File.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        if (!silent)
                            Console.WriteLine("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", 
                                downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, silent);
                        shouldHandleException = !File.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                    handleException(exn);
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #19
0
 public (IStatusCode, string) Download(IDownloadStrategy strategy, IUrl toDownload)
 {
     (IStatusCode, string)result = strategy.Download(toDownload);
     return(result.Item1, result.Item2);
 }
Пример #20
0
        private static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, bool silent)
        {
            Action<Exception> handleException = exception =>
            {
                if (!File.Exists(dlArgs.Target))
                    Environment.ExitCode = 1;
                BootstrapperHelper.WriteConsoleError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };
            try
            {
                var localVersion = BootstrapperHelper.GetLocalFileVersion(dlArgs.Target);

                var latestVersion = dlArgs.LatestVersion;
                if (latestVersion == String.Empty)
                {
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                }

                if (dlArgs.DoSelfUpdate)
                {
                    if (!silent)
                        Console.WriteLine("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion, silent);
                }
                else
                {
                    if (!localVersion.StartsWith(latestVersion))
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target, silent);
                        if (!silent)
                            Console.WriteLine("Done.");
                    }
                    else
                    {
                        if (!silent)
                            Console.WriteLine("Paket.exe {0} is up to date.", localVersion);
                    }
                }
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!File.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        if (!silent)
                            Console.WriteLine("'{0}' download failed. Try fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, silent);
                        shouldHandleException = !File.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                    handleException(exn);
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #21
0
 public CacheDownloadStrategy(IDownloadStrategy fallbackStrategy)
 {
     FallbackStrategy = fallbackStrategy;
 }
Пример #22
0
        public static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, IFileSystemProxy fileSystemProxy, Action onSuccess)
        {
            Action<Exception> handleException = exception =>
            {
                if (!fileSystemProxy.FileExists(dlArgs.Target))
                    Environment.ExitCode = 1;
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };
            try
            {
                string versionRequested;
                if (!dlArgs.IgnorePrerelease)
                    versionRequested = "prerelease requested";
                else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                    versionRequested = "downloading latest stable";
                else
                    versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);

                ConsoleImpl.WriteInfo("Checking Paket version ({0})...", versionRequested);
                ConsoleImpl.WriteTrace("Target path is {0}", dlArgs.Target);
                var localVersion = fileSystemProxy.GetLocalFileVersion(dlArgs.Target);
                ConsoleImpl.WriteTrace("File in target path version: v{0}", localVersion);

                var specificVersionRequested = true;
                var latestVersion = dlArgs.LatestVersion;

                if (latestVersion == string.Empty)
                {
                    ConsoleImpl.WriteTrace("No version specified, checking online...");

                    var getLatestVersionWatch = Stopwatch.StartNew();
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                    getLatestVersionWatch.Stop();

                    ConsoleImpl.WriteTrace("Latest version check found v{0} in {1:0.##} second(s)", latestVersion, getLatestVersionWatch.Elapsed.TotalSeconds);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    ConsoleImpl.WriteInfo("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    if (currentSemVer.PreRelease != null && dlArgs.IgnorePrerelease)
                        currentSemVer = new SemVer();
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        ConsoleImpl.WriteTrace("Downloading v{0} ...", latestVersion);

                        var downloadWatch = Stopwatch.StartNew();
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target);
                        downloadWatch.Stop();

                        ConsoleImpl.WriteTrace("Download took {0:0.##} second(s)", downloadWatch.Elapsed.TotalSeconds);
                        ConsoleImpl.WriteInfo("Done in {0:0.##} second(s).", executionWatch.Elapsed.TotalSeconds);
                    }
                    else
                    {
                        ConsoleImpl.WriteInfo("Paket.exe {0} is up to date.", localVersion);
                    }
                }

                executionWatch.Stop();
                ConsoleImpl.WriteTrace("Paket Bootstrapping took {0:0.##} second(s)", executionWatch.Elapsed.TotalSeconds);

                onSuccess();
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!fileSystemProxy.FileExists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        ConsoleImpl.WriteInfo("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, fileSystemProxy, onSuccess);
                        shouldHandleException = !fileSystemProxy.FileExists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                    handleException(exn);
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #23
0
        public static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, IFileProxy fileProxy)
        {
            Action <Exception> handleException = exception =>
            {
                if (!File.Exists(dlArgs.Target))
                {
                    Environment.ExitCode = 1;
                }
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };

            try
            {
                string versionRequested;
                if (!dlArgs.IgnorePrerelease)
                {
                    versionRequested = "prerelease requested";
                }
                else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                {
                    versionRequested = "downloading latest stable";
                }
                else
                {
                    versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);
                }

                ConsoleImpl.WriteDebug("Checking Paket version ({0})...", versionRequested);

                var localVersion = fileProxy.GetLocalFileVersion(dlArgs.Target);

                var specificVersionRequested = true;
                var latestVersion            = dlArgs.LatestVersion;

                if (latestVersion == String.Empty)
                {
                    latestVersion            = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    ConsoleImpl.WriteDebug("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    if (currentSemVer.PreRelease != null && dlArgs.IgnorePrerelease)
                    {
                        currentSemVer = new SemVer();
                    }
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison   = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target);
                        ConsoleImpl.WriteDebug("Done.");
                    }
                    else
                    {
                        ConsoleImpl.WriteDebug("Paket.exe {0} is up to date.", localVersion);
                    }
                }
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!File.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        ConsoleImpl.WriteDebug("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, fileProxy);
                        shouldHandleException = !File.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                {
                    handleException(exn);
                }
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
Пример #24
0
        public void TestInitialize()
        {
            var logger = new Mock <ILogger>();

            strategy = new SFTPDownloadStrategy(logger.Object);
        }
 public CacheDownloadStrategy(IDownloadStrategy fallbackStrategy)
 {
     FallbackStrategy = fallbackStrategy;
 }