예제 #1
0
        public async void DownloadQueue()
        {
            while (true)
            {
                if (Items.Count == 0)
                {
                    if (needToShowFinishedDialog)
                    {
                        DownloadFinished?.Invoke(this, new DownloadFinishArgs(""));
                        //MainPage.Activity.RunOnUiThread(() => DisplayAlert("Download Finished", "Download of the file has finished", "OK"));
                        needToShowFinishedDialog = false;
                    }
                    else
                    {
                        Thread.Sleep(20);
                    }
                }
                else
                {
                    needToShowFinishedDialog = true;
                    var r = await Download(Items[0]);

                    if (!r)
                    {
                        DownloadFinished?.Invoke(this, new DownloadFinishArgs(Items[0].Text));
                    }
                    RemoveQueueItem(0);
                }
            }
        }
예제 #2
0
            public async void StartDownloadCallback()
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_remotePath);

                    request.Method          = "GET";
                    request.Timeout         = REQUEST_TIMEOUT;
                    request.CookieContainer = _cookieJar;
                    request.Headers.Add("X-RequestDigest", _digest);
                    if (request == null)
                    {
                        DownloadFinished?.Invoke(this, new DownloadClientFinishedEventArgs(false)); return;
                    }

                    HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        if (WriteFile(response))
                        {
                            DownloadFinished?.Invoke(this, new DownloadClientFinishedEventArgs(true));
                            return;
                        }
                    }
                }
                catch (Exception) { }

                DownloadFinished?.Invoke(this, new DownloadClientFinishedEventArgs(false));
            }
예제 #3
0
        private void DownloadProcessExited(Process process, VideoConfig video)
        {
            var exitCode = process.ExitCode;

            if (exitCode != 0)
            {
                Log.Warn(_downloadLog.Length > 0 ? _downloadLog : "Empty youtube-dl log");

                video.DownloadState = DownloadState.Cancelled;
            }
            Log.Info($"Download process exited with code {exitCode}");

            if (video.DownloadState == DownloadState.Cancelled)
            {
                Log.Info("Cancelled download");
                VideoLoader.DeleteVideo(video);
                DownloadFinished?.Invoke(video);
            }
            else
            {
                process.Disposed -= DownloadProcessDisposed;
                _downloadProcesses.TryRemove(video, out _);
                video.DownloadState = DownloadState.Downloaded;
                video.NeedsToSave   = true;
                SharedCoroutineStarter.instance.StartCoroutine(WaitForDownloadToFinishCoroutine(video));
                Log.Info("Download finished");
            }
        }
예제 #4
0
		private void Finished()
		{
			string xml = new StreamReader(_receivedData).ReadToEnd();
            _stream.Close();
			_feed.Xml = xml;
			_feed.SetItems();
            DownloadFinished?.Invoke(_feed);
        }
예제 #5
0
        /// <summary>
        /// Triggers when the WebClient finishes the download.
        /// </summary>
        private void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            //Set the percent to exacly 100 (Done)
            Percent = 100;

            //Invoke the DownloadFinished event.
            DownloadFinished?.Invoke(this, new EventArgs());
        }
예제 #6
0
        private IEnumerator WaitForDownloadToFinishCoroutine(VideoConfig video)
        {
            var timeout = new Timeout(3);

            yield return(new WaitUntil(() => timeout.HasTimedOut || File.Exists(video.VideoPath)));

            DownloadFinished?.Invoke(video);
        }
예제 #7
0
 private static void OnDownloadFinished(bool iscanceled, Exception ex)
 {
     try
     {
         DownloadFinished?.Invoke(iscanceled, ex);
     }
     catch (Exception exp)
     {
         OnLogMessage("Internal error: " + exp.Message);
     }
 }
예제 #8
0
 public static void TryReleaseDownload(MusixSongResult Download)
 {
     lock (Downloads)
     {
         int st = Downloads.Count;
         Downloads.RemoveAll(x => x.Key == Download);
         if (Downloads.Count != st)
         {
             new Thread(x => { DownloadFinished?.Invoke(Download); DownloadsChanged?.Invoke(); }).Start();
         }
     }
 }
예제 #9
0
        private void DownloadProcessDisposed(object sender, EventArgs eventArgs)
        {
            var disposedProcess = (Process)sender;

            foreach (var dictionaryEntry in _downloadProcesses.Where(keyValuePair => keyValuePair.Value == disposedProcess).ToList())
            {
                var video   = dictionaryEntry.Key;
                var success = _downloadProcesses.TryRemove(dictionaryEntry.Key, out _);
                if (!success)
                {
                    Log.Error("Failed to remove disposed process from list of processes!");
                }
                else
                {
                    video.DownloadState = DownloadState.NotDownloaded;
                    DownloadFinished?.Invoke(video);
                }
            }
        }
예제 #10
0
        private void ExecuteDownloadClientPoll(object timerState)
        {
            var seen     = new List <string>();
            var complete = new List <DownloadEventArgs>();
            var progress = new List <DownloadEventArgs>();

            var downloadClients = _provider.GetServices <IDownloadClient>();

            foreach (var downloadClient in downloadClients.Where(d => d.Enabled))
            {
                var changes = downloadClient.Poll();
                foreach (var change in changes)
                {
                    var download = _downloads.FirstOrDefault(d => d.Client.DownloadEqual(change, d));
                    if (download == null)
                    {
                        continue;
                    }
                    switch (change.State)
                    {
                    case DownloadNotificationType.Done:
                        _downloads.Remove(download);
                        complete.Add(new DownloadEventArgs(download, DownloadNotificationType.Done));
                        break;

                    case DownloadNotificationType.Progress:
                        download.Percentage = change.Percentage;
                        download.TotalGb    = change.TotalGb;
                        progress.Add(new DownloadEventArgs(download, DownloadNotificationType.Progress));
                        break;
                    }
                }
            }

            DownloadProgress?.Invoke(this, progress);

            complete.AddRange(_downloads.Where(d => !seen.Contains(d.Id)).Select(d => new DownloadEventArgs(d, DownloadNotificationType.Abort)));
            foreach (var completedDownload in complete)
            {
                _downloads.Remove(completedDownload.Download);
            }
            DownloadFinished?.Invoke(this, complete);
        }
        public void startDownload()
        {
            ThreadStart act = () =>
            {
                string dpath = null;
                while (true)
                {
                    using (var c = new WebClient())
                    {
                        try
                        {
                            c.DownloadFile(_url, _destPath);
                            dpath = _destPath;
                        }
                        catch (ThreadAbortException) {}
                        catch (Exception e)
                        {
                            var reply =
                                MessageBox.Show(
                                    "Couldn't download image from " + _url + ". Copy URL to clipboard? Press cancel to retry. Reason: " + e.Message,
                                    "failed download", MessageBoxButtons.YesNoCancel);
                            switch (reply)
                            {
                            case DialogResult.Yes:
                                var t = new Thread(() => Clipboard.SetText(_url));
                                t.SetApartmentState(ApartmentState.STA);
                                t.Start();
                                break;

                            case DialogResult.Cancel:
                                continue;
                            }
                        }
                        break;
                    }
                }
                DownloadFinished.Invoke(this, new DownloadJobFinishedEventArgs(dpath));
            };

            _dThread = new Thread(act);
            _dThread.Start();
        }
예제 #12
0
        void Initialize(VideoDownloader downloader, Video video)
        {
            var inflater = (LayoutInflater)this.Context.GetSystemService(Context.LayoutInflaterService);
            var view     = inflater.Inflate(Resource.Layout.DownloadItem, this, true);

            var titleView = view.FindViewById <TextView>(Resource.Id.titleTextView);

            titleView.Text = downloader.Video.Title;

            var progressBar = view.FindViewById <ProgressBar>(Resource.Id.downloadProgressBar);

            downloader.DownloadProgressChanged += (sender, e) =>
            {
                progressBar.SetProgress((int)e.ProgressPercentage, true);
                ProgressChanged?.Invoke(this, video);
            };

            downloader.DownloadFinished += (sender, e) =>
            {
                DownloadFinished?.Invoke(this, video);
            };
        }
예제 #13
0
        /// <summary>
        /// Download's the client
        /// </summary>
        public void DownloadFile()
        {
            //Initialize the web client
            WebClient downloadClient = new WebClient();

            //Webclient events
            downloadClient.DownloadFileCompleted += (obj, args) =>
            {
                DownloadFinished?.Invoke(this, new EventArgs());
            };
            downloadClient.DownloadProgressChanged += (obj, args) =>
            {
                //Get event args
                DownloadProgressChangedEventArgs DoubleArgs = (DownloadProgressChangedEventArgs)args;

                //Sets progress percentage as a int
                DownloadPercent = DoubleArgs.ProgressPercentage;

                Console.WriteLine("Local Download Percent : " + DownloadPercent);

                //Changes the download progress bar
                if (DownloadProgressBar != null)
                {
                    DownloadProgressBar.Value = DownloadPercent;
                }

                //Triggers event
                DownloadProgressChanged?.Invoke(this, new EventArgs());
            };

            //Creates the directory
            Directory.CreateDirectory(TempDirectory + "\\" + "MoonByte" + "\\");

            //Download's the file.
            downloadClient.DownloadFileAsync(new Uri(DownloadURL), TempDirectory + "\\MoonByte\\" + ZipName);
        }
        public async void ReceiveData(byte[] data)
        {
            _fileStream.Write(data, 0, data.Length);
            if (_fileStream.Length == TotalBytesToReceive)
            {
                if (_fileHash == null)
                {
                    await Task.Run(() => _autoResetEvent.WaitOne());
                }

                _fileStream.Position = 0;
                byte[] fileHash;
                using (var sha256 = new SHA256Managed())
                    fileHash = sha256.ComputeHash(_fileStream);

                _fileStream.Close();
                _fileStream = null;

                if (fileHash.SequenceEqual(_fileHash))
                {
                    ViewData.DataManagerType.ModifyDownloadedFile(FileName);
                    DownloadFinished?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    File.Delete(FileName);
                    DownloadFailed?.Invoke(this, null);
                }
                IsFinished = true;
                return;
            }

            BytesReceived = _fileStream.Length;
            Progress      = BytesReceived / TotalBytesToReceive;
            ProgressChanged?.Invoke(this, EventArgs.Empty);
        }
예제 #15
0
 public void DownloadFinish()
 {
     DownloadFinished?.Invoke();
 }
 private void OnDownloadFinished()
 {
     DownloadFinished.Invoke();
 }
예제 #17
0
 /// <summary>
 /// Passes the internal event in the protocol handler to the outward-facing
 /// event.
 /// </summary>
 /// <param name="sender">Sender.</param>
 /// <param name="e">E.</param>
 private void OnModuleInstallationFinished(object sender, ModuleInstallationFinishedArgs e)
 {
     DownloadFinished?.Invoke(sender, e);
 }
예제 #18
0
 /// <summary>
 /// Event für das Ende der Downloads auslösen
 /// </summary>
 protected virtual void OnDownloadFinished()
 {
     DownloadFinished?.Invoke(this, new EventArgs());
 }
예제 #19
0
 private void DownloadFinish(DownloadFinishedEventArgs e)
 {
     StopPackageDownload();
     DownloadFinished?.Invoke(e);
 }
예제 #20
0
 internal static void Finish(ProgressJob job)
 {
     DownloadFinished?.Invoke(job);
 }
예제 #21
0
        async Task StartDownloading()
        {
            while (toDownload.Count > 0)
            {
                if (IsStarted == false || IsStopped)
                {
                    if (IsStopped)
                    {
                        break;
                    }
                    await Task.Delay(300);

                    continue;
                }

                // get next work
                var work = toDownload.Dequeue();

                // go through each page
                for (int i = 0; i < work.PageCount; i++)
                {
start:
                    try
                    {
                        if (IsStarted == false || IsStopped)
                        {
                            while (true)
                            {
                                if (IsStarted)
                                {
                                    break;
                                }
                                await Task.Delay(300);

                                continue;
                            }

                            if (IsStopped)
                            {
                                break;
                            }
                        }

                        var uri = work.GetImageUri(work.OriginalImageUrl, i);

                        // determine extension
                        var extension = uri.Substring(uri.LastIndexOf('.') + 1).ToLower();
                        if (extension != "png" && extension != "gif")
                        {
                            extension = "jpg";
                        }

                        // determine download path
                        //var filename = GetValidFilename(work.Id.Value.ToString(), i, extension);  // <--- this method get's a new filename - ignoring existing ones
                        var filename = $"{work.Id.Value.ToString()}_p{i}.{extension}";
                        var fullpath = Path.Combine(Destination, filename);
                        DownloadProgress?.Report(new DownloaderProgress(work, i, fullpath, 0.0, Percentage)); // report progress

                        // only download if image doesn't exist already
                        if (File.Exists(fullpath) == false)
                        {
                            // download image
                            byte[] buffer = null;
                            using (var client = new WebClient())
                            {
                                client.Headers.Add("Referer", "http://spapi.pixiv.net/");
                                client.Headers.Add("User-Agent", "PixivIOSApp/5.8.0");
                                client.UseDefaultCredentials = true;

                                client.DownloadProgressChanged += (a, b) =>
                                {
                                    DownloadProgress?.Report(new DownloaderProgress(work, i, fullpath, b.ProgressPercentage, Percentage));
                                };

                                buffer = await client.DownloadDataTaskAsync(uri);
                            }

                            // write image
                            File.WriteAllBytes(fullpath, buffer);
                            GC.Collect();
                        }

                        DownloadedImagesCount++;
                        DownloadProgress?.Report(new DownloaderProgress(work, i, fullpath, 100.0, Percentage));
                        DownloadFinished?.Invoke(this, new Tuple <long, int>(work.Id.Value, i));
                    }
                    catch (WebException)
                    {
                        while (true)
                        {
                            // just wait and check if there is internet connection
                            await Task.Delay(2000);

                            if (MainWindow.CheckForInternetConnection())
                            {
                                break;
                            }
                            continue;
                        }
                        goto start;  // oh boi, never thought I would be using this :D
                    }
                    catch (Exception ex)
                    {
                        DownloadedImagesCount++;
                        ErrorEncountered?.Invoke(this, new Tuple <long, int, string>(work.Id.Value, i, ex.Message));
                    }
                }
            }

            IsRunning = false;
            Finished?.Invoke(this, EventArgs.Empty);
        }
 protected virtual void OnDownloadFinished(DownloadFinishedEventArgs e)
 {
     DownloadFinished?.Invoke(this, e);
 }
 private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     DownloadFinished?.Invoke();
 }
예제 #24
0
 private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
 {
     Threading.SetComponentText(this, status, Properties.Strings.UpdateDone);
     DownloadFinished?.Invoke(this, SavePath);
 }
예제 #25
0
 private void DownloadFinish(DownloadFinishedEventArgs e)
 {
     DownloadFinished?.Invoke(e);
 }