private async Task Start(int attempts)
        {
            if (attempts > 200)
            {
                Status(false, "", "Stopped, too many retry attempts. Click on Start to resume the download");
                return;
            }
            else if (attempts > 1)
                Status(false, "", "Retrying...");
            cancelSrc = new CancellationTokenSource();
            StreamWriter filew = null;
            StreamWriter indexw = null;
            String file = null;
            String dir = null;
            try {
                Validate();
                if (attempts == 1)
                {
                    lbStatus.Items.Clear();
                    lbStatus.Items.Refresh();
                }
                btnStart.Content = "Cancel";
                btnBrowse.IsEnabled = false;
                StringBuilder sb = new StringBuilder();
                bool dldNotDone = false;
                if ((bool)cbDownload.IsChecked)
                {
                    String addr = cbAddr.Text;
                    if (imapAddr.ContainsKey(addr))
                        addr = imapAddr[addr];

                    dir = txtDownload.Text;

                    if (cbResume.IsChecked == true)
                    {
                        if (await Resume(addr) == false)
                            return;
                        dir = Path.GetDirectoryName(dir);
                    }

                    sb.AppendFormat(@"{0}\arch{1}.mbox", dir, DateTime.Now.ToFileTime());
                    file = sb.ToString();
                    String indexFile = Path.Combine(dir, "email_proc1596.index");
                    bool resume = false;
                    String downloadedFile = "";
                    if (File.Exists(indexFile))
                    {
                        using (StreamReader reader = new StreamReader(indexFile))
                        {
                            String line = reader.ReadLine();
                            if (line != null)
                            {
                                Match m = Regex.Match(line, "^([^ ]+) ([^ ]+) (.+)$");
                                if (m.Success && m.Groups[1].Value == addr && m.Groups[2].Value == txtUser.Text)
                                {
                                    downloadedFile = m.Groups[3].Value;
                                    file = downloadedFile;
                                }
                            }
                        }
                    }
                    if (downloadedFile == "")
                    {
                        using (StreamWriter writer = new StreamWriter(indexFile))
                        {
                            writer.WriteLine(addr + " " + txtUser.Text + " " + file);
                        }
                    }
                    else
                    {
                        file = downloadedFile;
                        resume = true;
                    }
                    filew = new StreamWriter(file, resume);
                    StateMachine sm = new StateMachine(cancelSrc.Token, addr, int.Parse(txtPort.Text), txtUser.Text, txtPassword.Password, file);
                    try
                    {
                        await sm.Start(
                            delegate (String format, object[] args)
                            {
                                Status(false, "", format, args);
                            },
                            async delegate (String mailbox, String message, String msgid, String msgnum)
                            {
                                if (indexw == null)
                                    indexw = new StreamWriter(indexFile, true);
                                await SaveMessage(filew, indexw, mailbox, message, msgid, msgnum);
                            },
                            delegate (double progress) { prBar.Value = progress; }
                        );
                    }
                    catch (ServerIOException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (TimeoutException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (FailedException)
                    {
                        Status(false, "", "Failed to download");
                    }
                    catch (ConnectionFailedException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    finally
                    {
                        if (indexw != null)
                            indexw.Close();
                        indexw = null;
                        if (filew != null)
                            filew.Close();
                        filew = null;
                    }
                    if (cancelSrc.Token.IsCancellationRequested)
                    {
                        Status(false, "", "Cancelled");
                        return;
                    }
                    if (sm.mailboxes != null)
                    {
                        Status(false, "", "Downloaded email to {0}", file);
                        foreach (Mailbox mailbox in sm.mailboxes)
                        {
                            if (mailbox.cnt != mailbox.start)
                            {
                                dldNotDone = true;
                                break;
                            }
                        }
                    }
                    else
                        dldNotDone = true;
                    if (dldNotDone)
                    {
                        Status(false, "", "Download is not complete, retrying...");
                        Thread.Sleep(5000);
                        await Start(attempts + 1);
                    }
                    else
                    {
                        TimeSpan span = DateTime.Now - start_time;
                        Status(false, "", "Download time {0} seconds", span.TotalSeconds);
                        File.Delete(indexFile);
                    }
                }
                else
                {
                    file = txtDownload.Text;
                    dir = Path.GetDirectoryName(txtDownload.Text);
                }
                if (dldNotDone == false && (bool)cbStatistics.IsChecked && !cancelSrc.Token.IsCancellationRequested)
                {
                    EmailStats stats = new EmailStats(cancelSrc.Token);
                    await stats.Start(dir, file, Status, delegate(double progress) { prBar.Value = progress; });
                    prBar.Value = 100;
                }
                if (cancelSrc.Token.IsCancellationRequested)
                    Status(false, "", "Cancelled");
            }
            catch (FailedLoginException)
            {
                Status(false, "", "Login failed, invalid user or password");
            }
            catch (FailedException)
            {
                Status(false, "", "Failed to download");
            }
            catch (SslFailedException)
            {
                Status(false, "", "Failed to establish secure connection");
            }
            catch (ValidationException ex)
            {
                Status(false,"",  ex.reason);
            }
            catch (CancelException)
            {
                Status(false, "", "Cancelled");
            }
            catch (Exception ex)
            {
                Status(false, "", ex.Message + " " + ex.StackTrace);
            }
            finally
            {
                prBar.IsIndeterminate = false;
                prBar.Value = 0;
                btnBrowse.IsEnabled = true;
                btnStart.Content = "Start";
                if (filew != null)
                    filew.Close();
                if (indexw != null)
                    indexw.Close();
                
            }
        }
Beispiel #2
0
        private async Task Start(int attempts)
        {
            if (attempts > 200)
            {
                Status(false, "", "Stopped, too many retry attempts. Click on Start to resume the download");
                return;
            }
            else if (attempts > 1)
            {
                Status(false, "", "Retrying...");
            }
            cancelSrc = new CancellationTokenSource();
            StreamWriter filew  = null;
            StreamWriter indexw = null;
            String       file   = null;
            String       dir    = null;

            try {
                Validate();
                if (attempts == 1)
                {
                    lbStatus.Items.Clear();
                    lbStatus.Items.Refresh();
                }
                btnStart.Content    = "Cancel";
                btnBrowse.IsEnabled = false;
                StringBuilder sb         = new StringBuilder();
                bool          dldNotDone = false;
                if ((bool)cbDownload.IsChecked)
                {
                    String addr = cbAddr.Text;
                    if (imapAddr.ContainsKey(addr))
                    {
                        addr = imapAddr[addr];
                    }

                    dir = txtDownload.Text;

                    if (cbResume.IsChecked == true)
                    {
                        if (await Resume(addr) == false)
                        {
                            return;
                        }
                        dir = Path.GetDirectoryName(dir);
                    }

                    sb.AppendFormat(@"{0}\arch{1}.mbox", dir, DateTime.Now.ToFileTime());
                    file = sb.ToString();
                    String indexFile      = Path.Combine(dir, "email_proc1596.index");
                    bool   resume         = false;
                    String downloadedFile = "";
                    if (File.Exists(indexFile))
                    {
                        using (StreamReader reader = new StreamReader(indexFile))
                        {
                            String line = reader.ReadLine();
                            if (line != null)
                            {
                                Match m = Regex.Match(line, "^([^ ]+) ([^ ]+) (.+)$");
                                if (m.Success && m.Groups[1].Value == addr && m.Groups[2].Value == txtUser.Text)
                                {
                                    downloadedFile = m.Groups[3].Value;
                                    file           = downloadedFile;
                                }
                            }
                        }
                    }
                    if (downloadedFile == "")
                    {
                        using (StreamWriter writer = new StreamWriter(indexFile))
                        {
                            writer.WriteLine(addr + " " + txtUser.Text + " " + file);
                        }
                    }
                    else
                    {
                        file   = downloadedFile;
                        resume = true;
                    }
                    filew = new StreamWriter(file, resume);
                    StateMachine sm = new StateMachine(cancelSrc.Token, addr, int.Parse(txtPort.Text), txtUser.Text, txtPassword.Password, file);
                    try
                    {
                        await sm.Start(
                            delegate(String format, object[] args)
                        {
                            Status(false, "", format, args);
                        },
                            async delegate(String mailbox, String message, String msgid, String msgnum)
                        {
                            if (indexw == null)
                            {
                                indexw = new StreamWriter(indexFile, true);
                            }
                            await SaveMessage(filew, indexw, mailbox, message, msgid, msgnum);
                        },
                            delegate(double progress) { prBar.Value = progress; }
                            );
                    }
                    catch (ServerIOException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (TimeoutException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (FailedException)
                    {
                        Status(false, "", "Failed to download");
                    }
                    catch (ConnectionFailedException ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Status(false, "", ex.Message);
                    }
                    finally
                    {
                        if (indexw != null)
                        {
                            indexw.Close();
                        }
                        indexw = null;
                        if (filew != null)
                        {
                            filew.Close();
                        }
                        filew = null;
                    }
                    if (cancelSrc.Token.IsCancellationRequested)
                    {
                        Status(false, "", "Cancelled");
                        return;
                    }
                    if (sm.mailboxes != null)
                    {
                        Status(false, "", "Downloaded email to {0}", file);
                        foreach (Mailbox mailbox in sm.mailboxes)
                        {
                            if (mailbox.cnt != mailbox.start)
                            {
                                dldNotDone = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        dldNotDone = true;
                    }
                    if (dldNotDone)
                    {
                        Status(false, "", "Download is not complete, retrying...");
                        Thread.Sleep(5000);
                        await Start(attempts + 1);
                    }
                    else
                    {
                        TimeSpan span = DateTime.Now - start_time;
                        Status(false, "", "Download time {0} seconds", span.TotalSeconds);
                        File.Delete(indexFile);
                    }
                }
                else
                {
                    file = txtDownload.Text;
                    dir  = Path.GetDirectoryName(txtDownload.Text);
                }
                if (dldNotDone == false && (bool)cbStatistics.IsChecked && !cancelSrc.Token.IsCancellationRequested)
                {
                    EmailStats stats = new EmailStats(cancelSrc.Token);
                    await stats.Start(dir, file, Status, delegate(double progress) { prBar.Value = progress; });

                    prBar.Value = 100;
                }
                if (cancelSrc.Token.IsCancellationRequested)
                {
                    Status(false, "", "Cancelled");
                }
            }
            catch (FailedLoginException)
            {
                Status(false, "", "Login failed, invalid user or password");
            }
            catch (FailedException)
            {
                Status(false, "", "Failed to download");
            }
            catch (SslFailedException)
            {
                Status(false, "", "Failed to establish secure connection");
            }
            catch (ValidationException ex)
            {
                Status(false, "", ex.reason);
            }
            catch (CancelException)
            {
                Status(false, "", "Cancelled");
            }
            catch (Exception ex)
            {
                Status(false, "", ex.Message + " " + ex.StackTrace);
            }
            finally
            {
                prBar.IsIndeterminate = false;
                prBar.Value           = 0;
                btnBrowse.IsEnabled   = true;
                btnStart.Content      = "Start";
                if (filew != null)
                {
                    filew.Close();
                }
                if (indexw != null)
                {
                    indexw.Close();
                }
            }
        }