Ejemplo n.º 1
0
        public async Task TestInvalid_HTTPDownloader_DownloadFilesAsync()
        {
            HTTPDownloader httpDownloader = new HTTPDownloader();
            var            ufe            = await Assert.ThrowsAsync <UriFormatException>(() => httpDownloader.DownloadFilesAsync(new string[] { "Invalid" }));

            Assert.Equal("Invalid URI: The format of the URI could not be determined.", ufe.Message);
        }
Ejemplo n.º 2
0
        public async Task TestZeroLength_HTTPDownloader_DownloadFilesAsync()
        {
            HTTPDownloader httpDownloader = new HTTPDownloader();
            var            e = await Record.ExceptionAsync(() => httpDownloader.DownloadFilesAsync(new string[0]));

            Assert.Null(e);
        }
Ejemplo n.º 3
0
        public async Task TestEmpty_HTTPDownloader_DownloadFilesAsync()
        {
            HTTPDownloader httpDownloader = new HTTPDownloader();
            var            ufe            = await Assert.ThrowsAsync <UriFormatException>(() => httpDownloader.DownloadFilesAsync(new string[] { "" }));

            Assert.Equal("Invalid URI: The URI is empty.", ufe.Message);
        }
Ejemplo n.º 4
0
        public async Task TestNull_HTTPDownloader_DownloadFilesAsync()
        {
            HTTPDownloader httpDownloader = new HTTPDownloader();
            var            ane            = await Assert.ThrowsAsync <ArgumentNullException>(() => httpDownloader.DownloadFilesAsync(null));

            Assert.Equal("Value cannot be null. (Parameter 'source')", ane.Message);
        }
 public UpdaterDownloadListener(UpdateWindow w, HTTPDownloader d)
 {
     window     = w;
     downloader = d;
     d.setProgressChangedEventHandler(new DownloadProgressChangedEventHandler(onProgressChanged));
     d.setNewFileDownloadingEventHandler(new NewFileDownloadingEventHandler(OnNewFile));
     d.setAllFileDownloadedEventHandler(new AllFileDownloadedEventHandler(OnAllFile));
 }
Ejemplo n.º 6
0
        public DownloadListener(PatcherWindow w, HTTPDownloader d)
        {
            window          = w;
            downloader      = d;
            baseCurrentSize = 0;
            totalSize       = d.getTotalSize();

            d.setProgressChangedEventHandler(new DownloadProgressChangedEventHandler(OnDownloadProgress));
            d.setAfterNewFileEventHandler(new AfterFileDownloadedEventHandler(OnAfterNewFile));
            d.setAllFileDownloadedEventHandler(new AllFileDownloadedEventHandler(allFileDownloaded));
        }
Ejemplo n.º 7
0
        public async Task TestValid_HTTPDownloader_DownloadFilesAsync()
        {
            HTTPDownloader httpDownloader = new HTTPDownloader();
            await httpDownloader.DownloadFilesAsync(new string[] { "https://www.google.com.sg/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" });

            using (SHA256Managed sha = new SHA256Managed())
            {
                var hash = sha.ComputeHash(new FileStream("./Download/googlelogo_color_272x92dp.png", FileMode.Open, FileAccess.Read));
                Assert.Equal("V3bNh2F+rOw7wA689TDRkkAmAz7ahS9wbBpnWpiRWCY=", Convert.ToBase64String(hash));
            }
        }
Ejemplo n.º 8
0
        private void _updateObsoleteFiles()
        {
            HTTPDownloader   downloader = new HTTPDownloader(ObsoleteFiles, Client, "source/");
            DownloadListener listener   = new DownloadListener(this, downloader);
            BackgroundWorker bw         = new BackgroundWorker();

            bw.DoWork += (object s, DoWorkEventArgs e) =>
            {
                downloader.startDownload();
            };
            bw.RunWorkerAsync();
        }
Ejemplo n.º 9
0
        public void VerifyIntegrity_20MBFile()
        {
            // Arrange
            string       fullPath           = String.Format("{0}{1}", OutputPath, Name_20MBFile);
            const string expected_md5Digest = "9017804333c820e3b4249130fc989e00";

            VerifyResources(fullPath);

            // Act
            HTTPDownloader.DownloadFile(URL_20MBFile, OutputPath, Name_20MBFile);

            // Assert
            Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
        }
Ejemplo n.º 10
0
        public void VerifyIntegrity_10MBFile()
        {
            // Arrange
            string       fullPath           = String.Format("{0}{1}", OutputPath, Name_10MBFile);
            const string expected_md5Digest = "3aa55f03c298b83cd7708e90d289afbd";

            VerifyResources(fullPath);

            // Act
            HTTPDownloader.DownloadFile(URL_10MBFile, OutputPath, Name_10MBFile);

            // Assert
            Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
        }
Ejemplo n.º 11
0
        public void VerifyIntegrity_5MBFile()
        {
            // Arrange
            string       fullPath           = String.Format("{0}{1}", OutputPath, Name_5MBFile);
            const string expected_md5Digest = "b3215c06647bc550406a9c8ccc378756";

            VerifyResources(fullPath);

            // Act
            HTTPDownloader.DownloadFile(URL_5MBFile, OutputPath, Name_5MBFile);

            // Assert
            Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
        }
Ejemplo n.º 12
0
        public void VerifyThrottleFeature_20MBFile_4Mbit()
        {
            // Arrange
            string fullPath = String.Format("{0}{1}", OutputPath, Name_20MBFile);

            long[] expected_timingResult = { 36 * 1000, 46 * 1000 };       // If the program has access to the full speed of your internet connection (in this case 4Mbit/s)
                                                                           // the download should take ~41 seconds.
                                                                           // But in a real world scenario, the connection speed can change second by second,
                                                                           // so in order to claim the test a success, the download should finish between 36 and 46 seconds.
            var stopWatch = new Stopwatch();

            VerifyResources(fullPath);

            // Act
            stopWatch.Start();
            HTTPDownloader.DownloadFile(URL_20MBFile, OutputPath, Name_20MBFile, 500000); // The download speed will be limited to 4Mbit/s
            stopWatch.Stop();

            // Assert
            Assert.IsTrue(stopWatch.ElapsedMilliseconds >= expected_timingResult[0] && stopWatch.ElapsedMilliseconds <= expected_timingResult[1]);
        }
        public async Task TestDownload()
        {
            var apiKey = Environment.GetEnvironmentVariable("NEXUSAPIKEY", EnvironmentVariableTarget.Machine);

            Assert.NotNull(apiKey);

            var nexusApi = new NexusAPIClient("Wabbajack.Downloader.Test", "1.0.0", apiKey);

            Assert.NotNull(nexusApi);

            var status = await nexusApi.GetUserStatus();

            Assert.True(status.is_premium);

            var link = await nexusApi.GetNexusDownloadLink("skyrimspecialedition", 12604, 35407);

            Assert.False(string.IsNullOrEmpty(link));

            var result = await HTTPDownloader.Download(link, "SkyUI.7z", nexusApi.HttpClient);

            Assert.True(result);
            Assert.True(File.Exists("SkyUI.7z"));
            Assert.Equal("5375e0e91051f57ad463dfe3412bba58abb975f8479a968dd9d4e5d329431662", await Utils.GetHash("SkyUI.7z"));
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            /*args = new string[8];
             * args[0] = "-f";
             * args[1] = @"C:\Users\Mutu.A\Desktop\urls.txt"; // URLs list file
             * args[2] = "-o";
             * args[3] = @"C:\Users\Mutu.A\Desktop\test";     // Output directory
             * args[4] = "-n";
             * args[5] = "2";                                 // Number of concurrent threads
             * args[6] = "-l";
             * args[7] = "0";                                 // Speed limit*/

            // Parsing the given arguments
            string URLsFileList = _Debug.GetArgument('f', args);
            string DownloadedFiles_OutputDirectory = _Debug.GetArgument('o', args);
            uint   Maximum_DownloadSpeedBytes      = uint.MaxValue;

            if (!UInt32.TryParse(_Debug.GetArgument('l', args), out Maximum_DownloadSpeedBytes))
            {
                _Debug.WriteFatalError("The '-l' parameter must be an (unsigned) integer (32-bit)");
            }
            else
            if (Maximum_DownloadSpeedBytes < 62500 && Maximum_DownloadSpeedBytes != 0)     // Minimum speed throttling : 0.5Mbit/s
            {
                Maximum_DownloadSpeedBytes = 62500;
            }
            else if (Maximum_DownloadSpeedBytes == 0)     // 0 = no speed limit
            {
                Maximum_DownloadSpeedBytes = uint.MaxValue;
            }

            if (!Byte.TryParse(_Debug.GetArgument('n', args), out HTTPDownloader.Maximum_NumberOfConcurrentThreads))
            {
                _Debug.WriteFatalError("The '-n' parameter must be an (unsigned) integer (8-bit)!");
            }
            else
            if (HTTPDownloader.Maximum_NumberOfConcurrentThreads == 0)
            {
                HTTPDownloader.Maximum_NumberOfConcurrentThreads = 1;
            }

            if (String.IsNullOrEmpty(URLsFileList))
            {
                _Debug.WriteFatalError("You must add the full path where the URLs list file is!");
            }
            if (String.IsNullOrEmpty(DownloadedFiles_OutputDirectory))
            {
                _Debug.WriteFatalError("You must add the full path where the downloaded files would be saved!");
            }

            Console.WriteLine("\nMaximum download speed: {0:0.0} Mbit/s => {1} bytes/s\n", Maximum_DownloadSpeedBytes / 125000F, Maximum_DownloadSpeedBytes);

            _Debug._Stopwatch.Start();
            // Parsing the file which contains the URLs list
            // Before starting: We verify the existence of the 'Output Directory'/'URLs List File'
            if (!Directory.Exists(DownloadedFiles_OutputDirectory))
            {
                _Debug.WriteFatalError("The output directory where the downloaded files would be saved doesn't exists!");
            }

            if (File.Exists(URLsFileList))
            {
                // Enumerating the lines in the file
                foreach (string _s in File.ReadAllLines(URLsFileList))
                {
                    if (!String.IsNullOrEmpty(_s))
                    {
                        string url      = _s.Substring(0, _s.IndexOf(' '));  // Gets the URL from the current line
                        string fileName = _s.Substring(_s.IndexOf(' ') + 1); // Gets the local file name from the current line

                        // If the working threads are less than the maximum working threads allowed...
                        if (HTTPDownloader.Current_NumberOfConcurrentThreads < HTTPDownloader.Maximum_NumberOfConcurrentThreads)
                        {
                            // We start a new working thread where the file should be downloaded
                            // Passing as parameters the URL, Output Directory, Local File Name and optionally the maximum speed limit
                            Thread downloadFileThread = new Thread(() => HTTPDownloader.DownloadFile(url, DownloadedFiles_OutputDirectory, fileName, Maximum_DownloadSpeedBytes));
                            downloadFileThread.Start();

                            // We need to keep track of the active working threads to simulate a queue list
                            HTTPDownloader.Current_NumberOfConcurrentThreads++;
                        }

                        // Until all threads are busy, we block the foreach loop
                        while (HTTPDownloader.Current_NumberOfConcurrentThreads >= HTTPDownloader.Maximum_NumberOfConcurrentThreads)
                        {
                            // Used to avoid overload of the CPU
                            Thread.Sleep(1);
                        }
                    }
                }
            }
            else
            {
                _Debug.WriteFatalError("Unable to find the file which contains the URLs list!");
            }

            // Blocking the main thread
            while (true)
            {
                if (HTTPDownloader.Current_NumberOfConcurrentThreads == 0)
                {
                    _Debug._Stopwatch.Stop();
                    Console.WriteLine("\n\nTime elapsed for the whole work: {0}\n", _Debug._Stopwatch.Elapsed);

                    break;
                }

                Thread.Sleep(1);
            }

            Console.WriteLine("Done! Press any key to exit...");
            Console.ReadKey();
        }
Ejemplo n.º 15
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            m = new Mutex(false, "rom2updater");
            if (!m.WaitOne(0, false))
            {
                Application.Current.Shutdown();
            }
            if (IsProcessOpen("warlords.patcher.exe"))
            {
                Application.Current.Shutdown();
            }

            //Da fare gestione config
            string updateIndexFileName = "metaFiles/UpdaterIndex";
            string cleanerFileName     = "metaFiles/UpdateCleaner";
            string baseAddress         = "http://patcher.metin2warlords.net/";
            string argument            = "nonhofantasia";

            UpdateWindow window = new UpdateWindow();

            window.Show();
            WebClient client = new WebClient();

            client.BaseAddress = baseAddress;

            string s = client.DownloadString(updateIndexFileName);
            string c = client.DownloadString(cleanerFileName);


            CleanerExtractor ce          = new CleanerExtractor(c);
            List <PatchFile> toCleanFile = ce.extract();

            foreach (PatchFile f in toCleanFile)
            {
                string path = Path.Combine(f.BasePath, f.Name);
                if (File.Exists(path))
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                    File.Delete(path);
                }
            }
            PipeDelimitedFileManifestParser p = new PipeDelimitedFileManifestParser(s);
            ObsoleteFileFinder scanner        = new ObsoleteFileFinder(p);

            scanner.Search();
            List <PatchFile> toUpdateFiles = scanner.getToUpdateFiles();
            List <PatchFile> sourceFiles   = scanner.getSourceFiles();
            string           exeName       = sourceFiles[0].Name;
            BackgroundWorker bw            = new BackgroundWorker();

            if (toUpdateFiles.Count > 0)
            {
                HTTPDownloader          downloader = new HTTPDownloader(toUpdateFiles, client, "sourceUpdater/");
                UpdaterDownloadListener listener   = new UpdaterDownloadListener(window, downloader);
                downloader.allFileDownloaded += (object ss) =>
                {
                    System.Diagnostics.Process.Start(exeName, argument);
                    Application.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        window.Close();
                    }
                                                                   ));
                };

                bw.DoWork += (object se, DoWorkEventArgs es) =>
                {
                    downloader.startDownload();
                };
                bw.RunWorkerAsync();
            }


            if (bw.IsBusy == false)
            {
                System.Diagnostics.Process.Start(exeName, argument);
                window.Close();
            }
        }