H4x0

ASync Snippet

Feb 11th, 2013
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.85 KB | None | 0 0
  1. using DevExpress.XtraWizard;
  2. using Facebook;
  3. using FDown.Properties;
  4. using Microsoft.WindowsAPICodePack.Taskbar;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.Dynamic;
  10. using System.IO;
  11. using System.Net;
  12. using System.Runtime.InteropServices;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15.  
  16. namespace FDown
  17. {
  18.     public partial class Form1 : Form
  19.     {
  20.         #region P/Invoke
  21.  
  22.         [DllImport("user32.dll")]
  23.         private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
  24.  
  25.         [DllImport("user32.dll")]
  26.         private static extern bool InsertMenu(IntPtr hMenu,
  27.             Int32 wPosition, Int32 wFlags, Int32 wIDNewItem,
  28.             string lpNewItem);
  29.  
  30.         #endregion
  31.  
  32.         #region Globals
  33.  
  34.         bool isBusy = false;
  35.         bool isLoggedIn = false;
  36.         bool isOverwrite = false;
  37.         bool isInfoLoaded = false;
  38.         string accessToken = null;
  39.         string SaveLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\ASync";
  40.         Dictionary<string, int> AlbumCount = new Dictionary<string, int>();
  41.         FacebookClient Client;
  42.         TaskbarManager ITaskbar;
  43.         WebBrowserEx Browser = new WebBrowserEx();
  44.  
  45.         public const Int32 WM_SYSCOMMAND = 0x112;
  46.         public const Int32 MF_SEPARATOR = 0x800;
  47.         public const Int32 MF_BYPOSITION = 0x400;
  48.         public const Int32 MF_STRING = 0x0;
  49.         public const Int32 IDM_CUSTOMITEM1 = 1000;
  50.         public const Int32 IDM_CUSTOMITEM2 = 1001;
  51.  
  52.         #endregion
  53.  
  54.         #region WndProc
  55.  
  56.         protected override void WndProc(ref Message m)
  57.         {
  58.             if (m.Msg == WM_SYSCOMMAND)
  59.             {
  60.                 switch (m.WParam.ToInt32())
  61.                 {
  62.                     case IDM_CUSTOMITEM1:
  63.                         CheckUpdate(true);
  64.                         return;
  65.                     case IDM_CUSTOMITEM2:
  66.                         ShowAbout();
  67.                         return;
  68.                     default:
  69.                         break;
  70.                 }
  71.             }
  72.             base.WndProc(ref m);
  73.         }
  74.  
  75.         #endregion
  76.  
  77.         #region Properties
  78.  
  79.         public static bool IsInternetConnected
  80.         {
  81.             get
  82.             {
  83.                 try
  84.                 {
  85.                     using (var client = new WebClient())
  86.                     using (var stream = client.OpenRead("http://www.facebook.com"))
  87.                     {
  88.                         return true;
  89.                     }
  90.                 }
  91.                 catch
  92.                 {
  93.                     return false;
  94.                 }
  95.             }
  96.         }
  97.  
  98.         #endregion
  99.  
  100.         #region Helpers
  101.  
  102.         private Uri GenerateLoginUrl(string appId, string extendedPermissions)
  103.         {
  104.             dynamic parameters = new ExpandoObject();
  105.             parameters.client_id = appId;
  106.             parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
  107.             parameters.response_type = "token";
  108.             parameters.display = "popup";
  109.             if (!string.IsNullOrWhiteSpace(extendedPermissions))
  110.                 parameters.scope = extendedPermissions;
  111.  
  112.             var fb = new FacebookClient();
  113.             return fb.GetLoginUrl(parameters);
  114.         }
  115.  
  116.         private void FlashMessage(string Msg)
  117.         {
  118.             label3.Text = Msg;
  119.             label3.Visible = true;
  120.  
  121.             Timer UIx = new Timer()
  122.             {
  123.                 Interval = 1000
  124.             };
  125.  
  126.             UIx.Tick += delegate
  127.             {
  128.                 UIx.Stop();
  129.                 label3.Visible = false;
  130.             };
  131.  
  132.             UIx.Start();
  133.         }
  134.  
  135.         string ValidatePath(string invpath)
  136.         {
  137.             Array.ForEach(Path.GetInvalidFileNameChars(), c => invpath = invpath.Replace(c.ToString(), ""));
  138.             invpath = invpath.TrimEnd('.');
  139.             return invpath.Trim();
  140.         }
  141.  
  142.         public Image DownloadImage(string _URL)
  143.         {
  144.             Image _tmpImage = null;
  145.  
  146.             try
  147.             {
  148.                 System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);
  149.  
  150.                 _HttpWebRequest.AllowWriteStreamBuffering = true;
  151.                 _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
  152.                 _HttpWebRequest.Referer = "http://www.google.com/";
  153.                 _HttpWebRequest.Timeout = 20000;
  154.  
  155.                 System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();
  156.                 System.IO.Stream _WebStream = _WebResponse.GetResponseStream();
  157.  
  158.                 _tmpImage = Image.FromStream(_WebStream);
  159.                 _WebResponse.Close();
  160.                 _WebResponse.Close();
  161.             }
  162.             catch (Exception _Exception)
  163.             {
  164.                 Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
  165.                 return null;
  166.             }
  167.  
  168.             return _tmpImage;
  169.         }
  170.  
  171.         void CheckUpdate(bool Interface = false)
  172.         {
  173.             if (File.Exists("Updater.exe"))
  174.             {
  175.                 ProcessStartInfo PStartInf = new ProcessStartInfo()
  176.                 {
  177.                     FileName = "Updater.exe"
  178.                 };
  179.  
  180.                 if (Interface)
  181.                 {
  182.                     PStartInf.Verb = "runas";
  183.                     PStartInf.UseShellExecute = true;
  184.                     PStartInf.Arguments += "--ui";
  185.                 }
  186.  
  187.                 Process.Start(PStartInf);
  188.             }
  189.         }
  190.  
  191.         void FBLogin()
  192.         {
  193.             isBusy = true;
  194.             var loginUrl = GenerateLoginUrl("<REMOVED>", "user_photos");
  195.             Browser.Navigate(loginUrl);
  196.  
  197.             Timer tX = new Timer()
  198.             {
  199.                 Interval = 100
  200.             };
  201.  
  202.             tX.Tick += delegate
  203.             {
  204.                 if ((isLoggedIn == true) && (accessToken != null))
  205.                 {
  206.                     tX.Stop();
  207.                     isBusy = false;
  208.                     if (!isInfoLoaded) { LoadInfo(); }
  209.                     isInfoLoaded = true;
  210.                     wizardControl1.SelectedPageIndex = wizardControl1.SelectedPageIndex + 1;
  211.                 }
  212.             };
  213.  
  214.             tX.Start();
  215.         }
  216.  
  217.         void ShowAbout()
  218.         {
  219.             MessageBox.Show("ASync was created by H4x0, it was first developed " +
  220.                         "for his fiance and later rewritten for general use because " +
  221.                         "she was a dumb bitch.\n\nCurrent Version: " +
  222.                         Application.ProductVersion +
  223.                         "\nRelease: 2/11/13\nStage: Beta", "About ASync", MessageBoxButtons.OK, MessageBoxIcon.Information);
  224.         }
  225.  
  226.         #endregion
  227.  
  228.         public Form1()
  229.         {
  230.             InitializeComponent();
  231.  
  232.             ITaskbar = TaskbarManager.Instance;
  233.  
  234.             #region System Menu
  235.  
  236.             IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false);
  237.             InsertMenu(sysMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
  238.             InsertMenu(sysMenuHandle, 6, MF_BYPOSITION, IDM_CUSTOMITEM1, "Check For Updates");
  239.             InsertMenu(sysMenuHandle, 7, MF_BYPOSITION, IDM_CUSTOMITEM2, "About ASync");
  240.  
  241.             #endregion
  242.  
  243.             #region Column Positioning
  244.  
  245.             this.columnHeader2.Width = 75;
  246.             this.columnHeader1.Width = listView1.Width - 75;
  247.  
  248.             #endregion
  249.  
  250.             #region Extended Browser
  251.  
  252.             Browser.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
  253.             Browser.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
  254.             Browser.NavigateError += new WebBrowserNavigateErrorEventHandler(webBrowser1_Error);
  255.             Browser.Dock = DockStyle.Fill;
  256.             wizardControl1.Pages[1].Controls.Add(Browser);
  257.  
  258.             #endregion
  259.         }
  260.  
  261.         #region Facebook Login
  262.  
  263.         private void webBrowser1_Error(object sender, WebBrowserNavigateErrorEventArgs e)
  264.         {
  265.             pictureBox1.Visible = true;
  266.             pictureBox1.Image = Resources.Exclamation;
  267.  
  268.             DialogResult Result = MessageBox.Show("Cannot connect to the internet", "ASync", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
  269.  
  270.             if (Result == System.Windows.Forms.DialogResult.Retry)
  271.             {
  272.                 isBusy = false;
  273.                 FBLogin();
  274.                 pictureBox1.Image = Resources.Loader;
  275.             }
  276.             else
  277.             {
  278.                 this.Close();
  279.             }
  280.         }
  281.  
  282.         private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
  283.         {
  284.             pictureBox1.Visible = true;
  285.         }
  286.  
  287.         private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
  288.         {
  289.             pictureBox1.Visible = false;
  290.             var fb = new FacebookClient();
  291.             FacebookOAuthResult oauthResult;
  292.  
  293.             if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
  294.             {
  295.                 if (oauthResult.IsSuccess)
  296.                 {
  297.                     var accesstoken = oauthResult.AccessToken;
  298.                     isLoggedIn = true;
  299.                     accessToken = accesstoken;
  300.                     fb.AccessToken = accessToken;
  301.                     Client = fb;
  302.                 }
  303.                 else
  304.                 {
  305.                     var errorDescription = oauthResult.ErrorDescription;
  306.                     var errorReason = oauthResult.ErrorReason;
  307.  
  308.                     pictureBox1.Visible = true;
  309.                     pictureBox1.Image = Resources.Exclamation;
  310.                    
  311.                     DialogResult Result = MessageBox.Show("Failed to login to Facebook", "ASync", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
  312.  
  313.                     if (Result == System.Windows.Forms.DialogResult.Retry)
  314.                     {
  315.                         isBusy = false;
  316.                         FBLogin();
  317.                         pictureBox1.Image = Resources.Loader;
  318.                     }
  319.                     else
  320.                     {
  321.                         this.Close();
  322.                     }
  323.                 }
  324.             }
  325.             else
  326.             {
  327.                
  328.             }
  329.         }
  330.  
  331.         #endregion
  332.  
  333.         #region Wizard Page Changing
  334.  
  335.         private void wizardControl1_SelectedPageChanging(object sender, DevExpress.XtraWizard.WizardPageChangingEventArgs e)
  336.         {
  337.             if (e.Page.Text == "Facebook Login")
  338.             {
  339.                 FBLogin();
  340.             }
  341.             else if (e.Page.Text == "Options")
  342.             {
  343.                 textBox1.Text = SaveLocation;
  344.  
  345.                 button1.Click += delegate
  346.                 {
  347.                     FolderBrowserDialog Diag = new FolderBrowserDialog();
  348.                     Diag.RootFolder = Environment.SpecialFolder.MyPictures;
  349.                     Diag.ShowNewFolderButton = true;
  350.  
  351.                     DialogResult Res = Diag.ShowDialog();
  352.                     if (Res == System.Windows.Forms.DialogResult.OK)
  353.                     {
  354.                         textBox1.Text = Diag.SelectedPath;
  355.                     }
  356.                 };
  357.             }
  358.  
  359.             if (e.PrevPage.Text == "Options")
  360.             {
  361.                 if (!Directory.Exists(textBox1.Text))
  362.                 {
  363.                     e.Cancel = true;
  364.                     MessageBox.Show("Invalid Directory\n\n" + textBox1.Text, "ASync", MessageBoxButtons.OK, MessageBoxIcon.Error);
  365.                 }
  366.                 else
  367.                 {
  368.                     SaveLocation = textBox1.Text;
  369.                 }
  370.             }
  371.         }
  372.  
  373.         private void wizardControl1_SelectedPageChanged(object sender, DevExpress.XtraWizard.WizardPageChangedEventArgs e)
  374.         {
  375.             if (e.Page.Text == "Downloading Photos")
  376.             {
  377.                 List<String> toDl = new List<String>();
  378.  
  379.                 isBusy = true;
  380.  
  381.                 foreach (ListViewItem i in listView1.Items)
  382.                 {
  383.                     if (i.Checked)
  384.                     {
  385.                         toDl.Add(i.Text);
  386.                     }
  387.                 }
  388.  
  389.                 isBusy = false;
  390.  
  391.                 Download(toDl);
  392.             }
  393.         }
  394.  
  395.         #endregion
  396.  
  397.         #region Wizard Buttons
  398.  
  399.         private void wizardControl1_PrevClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
  400.         {
  401.             if (isBusy)
  402.             {
  403.                 e.Handled = true;
  404.                 FlashMessage("Please Wait");
  405.             }
  406.             else
  407.             {
  408.                 if (e.Page.Text == "Choose Albums")
  409.                 {
  410.                     e.Handled = true;
  411.                     wizardControl1.SelectedPage = wizardControl1.Pages[0];
  412.                 }
  413.                 else if (e.Page.Text == "All Done")
  414.                 {
  415.                     e.Handled = true;
  416.                     wizardControl1.SelectedPage = wizardControl1.Pages[3];
  417.                 }
  418.             }
  419.         }
  420.  
  421.         private void wizardControl1_NextClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
  422.         {
  423.             if (isBusy)
  424.             {
  425.                 e.Handled = true;
  426.                 FlashMessage("Please Wait");
  427.             }
  428.         }
  429.  
  430.         private void wizardControl1_CancelClick(object sender, System.ComponentModel.CancelEventArgs e)
  431.         {
  432.             if (isBusy)
  433.             {
  434.                 DialogResult Result = MessageBox.Show("Closing ASync will cancel the current operation\n\nAre you sure you want to close ASync?", "Async", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  435.  
  436.                 if (Result == System.Windows.Forms.DialogResult.Yes)
  437.                 {
  438.                     this.Close();
  439.                 }
  440.             }
  441.             else
  442.             {
  443.                 this.Close();
  444.             }
  445.         }
  446.  
  447.         private void wizardControl1_FinishClick(object sender, System.ComponentModel.CancelEventArgs e)
  448.         {
  449.             if (checkBox2.Checked)
  450.             {
  451.                 Process.Start(SaveLocation);
  452.             }
  453.  
  454.             this.Close();
  455.         }
  456.  
  457.         #endregion
  458.  
  459.         #region Download Photos Async
  460.  
  461.         async void Download(List<String> toDl)
  462.         {
  463.             isBusy = true;
  464.             List<int> Counts = new List<int>();
  465.             dynamic albums = Client.Get("me/albums?fields=name,id");
  466.  
  467.             int PROG_ALB = 1;
  468.             int TPROG_ALB = toDl.Count;
  469.             int PROG_PHO = 1;
  470.             int TPROG_PHO = 0;
  471.             int PROG_TOT = 1;
  472.             int TPROG_TOT = 0;
  473.  
  474.             Timer x = new Timer()
  475.             {
  476.                 Interval = 100
  477.             };
  478.  
  479.             x.Tick += delegate
  480.             {
  481.                 if (isBusy)
  482.                 {
  483.                     try
  484.                     {
  485.                         ALBProg.Maximum = TPROG_ALB;
  486.                         ALBProg.Value = PROG_ALB;
  487.                         label4.Text = string.Format("Downloading {0} of {1} Albums", PROG_ALB, TPROG_ALB);
  488.                         PHOProg.Maximum = Counts[PROG_ALB];
  489.                         PHOProg.Value = PROG_PHO;
  490.                         label5.Text = string.Format("Downloading {0} of {1} Photos", PROG_PHO, Counts[PROG_ALB]);
  491.                         ITaskbar.SetProgressValue(PROG_ALB, TPROG_ALB);
  492.                     }
  493.                     catch { }
  494.                 }
  495.                 else
  496.                 {
  497.                     x.Stop();
  498.                     ALBProg.Value = 0;
  499.                     PHOProg.Value = 0;
  500.                     label4.Text = string.Format("Downloading 0 of 0 Albums");
  501.                     label5.Text = string.Format("Downloading 0 of 0 Photos");
  502.                     ITaskbar.SetProgressState(TaskbarProgressBarState.NoProgress);
  503.                 }
  504.             };
  505.  
  506.             x.Start();
  507.  
  508.             List<string> DownloadPhotos = await Task<List<string>>.Run(() =>
  509.             {
  510.                 #region Count Photos
  511.  
  512.                 foreach (KeyValuePair<string, int> z in AlbumCount)
  513.                 {
  514.                     if (toDl.Contains(z.Key))
  515.                     {
  516.                         Counts.Add(z.Value);
  517.                         TPROG_TOT = TPROG_TOT + z.Value;
  518.                     }
  519.                 }
  520.  
  521.                 #endregion
  522.  
  523.                 List<string> log = new List<string>();
  524.  
  525.                 foreach (dynamic albumInfo in albums.data)
  526.                 {
  527.                     if (toDl.Contains(albumInfo.name))
  528.                     {
  529.                         string albName = albumInfo.name;
  530.                         dynamic albumsPhotos = Client.Get(albumInfo.id + "/photos");
  531.  
  532.                         PROG_PHO = 0;
  533.                         foreach (dynamic photoInfo in albumsPhotos.data)
  534.                         {
  535.                             string imgName = photoInfo.name ?? photoInfo.id;
  536.  
  537.                             if (imgName.Length > 30)
  538.                             {
  539.                                 imgName = imgName.Substring(0, 30);
  540.                             }
  541.  
  542.                             imgName = ValidatePath(imgName);
  543.                             albName = ValidatePath(albName);
  544.  
  545.                             string savLoca = SaveLocation + "\\" + albName + "\\" + imgName + ".jpg";
  546.                             string webLoca = photoInfo.source;
  547.  
  548.                             if (!Directory.Exists(Path.GetDirectoryName(savLoca)))
  549.                             {
  550.                                 Directory.CreateDirectory(Path.GetDirectoryName(savLoca));
  551.                             }
  552.  
  553.                             if (isOverwrite)
  554.                             {
  555.                                 if (File.Exists(savLoca))
  556.                                 {
  557.                                     File.Delete(savLoca);
  558.                                 }
  559.                             }
  560.  
  561.                             if (!File.Exists(savLoca))
  562.                             {
  563.                                 Image _Image = null;
  564.                                 _Image = DownloadImage(webLoca);
  565.  
  566.                                 if (_Image != null)
  567.                                 {
  568.                                     _Image.Save(savLoca);
  569.                                 }
  570.                                 else { log.Add(string.Format("ERROR: Cannot Download {0}", imgName)); }
  571.                             }
  572.  
  573.                             PROG_PHO++;
  574.                             PROG_TOT++;
  575.                         }
  576.  
  577.                         PROG_ALB++;
  578.                     }
  579.                 }
  580.  
  581.                 return log;
  582.             });
  583.  
  584.             foreach (string l in DownloadPhotos)
  585.             {
  586.                 richTextBox1.Text += Environment.NewLine + l;
  587.             }
  588.  
  589.             wizardControl1.SelectedPageIndex = wizardControl1.SelectedPageIndex + 1;
  590.             isBusy = false;
  591.         }
  592.  
  593.         #endregion
  594.  
  595.         #region First Load
  596.  
  597.         async void LoadInfo()
  598.         {
  599.             isBusy = true;
  600.             ITaskbar.SetProgressState(TaskbarProgressBarState.Indeterminate);
  601.             String UI_Status = "Awaiting Connection";
  602.  
  603.             Timer TX = new Timer()
  604.             {
  605.                 Interval = 10
  606.             };
  607.  
  608.             TX.Tick += delegate
  609.             {
  610.                 if (panel1.Visible)
  611.                 {
  612.                     label2.Text = "Loading..\n" + UI_Status;
  613.                 }
  614.                 else
  615.                 {
  616.                     TX.Stop();
  617.                     isBusy = false;
  618.                     label2.Text = "Loading..";
  619.                     ITaskbar.SetProgressState(TaskbarProgressBarState.NoProgress);
  620.                 }
  621.             };
  622.  
  623.             TX.Start();
  624.  
  625.             Dictionary<string, int> ListAlbums = await Task<Dictionary<string, int>>.Run(() =>
  626.             {
  627.                 Dictionary<string, int> RetVal = new Dictionary<string, int>();
  628.  
  629.                 dynamic albums = Client.Get("me/albums?fields=name,id");
  630.  
  631.                 foreach (dynamic albumInfo in albums.data)
  632.                 {
  633.                     string albName = albumInfo.name;
  634.                     UI_Status = string.Format("{0}", albName);
  635.  
  636.                     dynamic albumsPhotos = Client.Get(albumInfo.id + "/photos");
  637.  
  638.                     int Cur = 0;
  639.                     foreach (dynamic photoInfo in albumsPhotos.data)
  640.                     {
  641.                         Cur++;
  642.                     }
  643.  
  644.                     RetVal.Add(albName, Cur);
  645.                 }
  646.  
  647.                 return RetVal;
  648.             });
  649.  
  650.             isBusy = true;
  651.             AlbumCount = ListAlbums;
  652.             foreach (KeyValuePair<string, int> x in AlbumCount)
  653.             {
  654.                 listView1.Items.Add(new ListViewItem(new string[] { x.Key, x.Value.ToString() }) { Checked = true });
  655.             }
  656.  
  657.             panel1.Visible = false;
  658.             isBusy = false;
  659.         }
  660.  
  661.         #endregion
  662.  
  663.         private void checkBox1_CheckedChanged(object sender, EventArgs e)
  664.         {
  665.             isOverwrite = checkBox1.Checked;
  666.         }
  667.  
  668.         private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  669.         {
  670.             CheckUpdate();
  671.         }
  672.  
  673.         #region UI Status
  674.  
  675.         private void timer1_Tick(object sender, EventArgs e)
  676.         {
  677.             BaseWizardPage CurrentPage = wizardControl1.SelectedPage;
  678.  
  679.             if (isBusy)
  680.             {
  681.                 CurrentPage.AllowBack = false;
  682.                 CurrentPage.AllowNext = false;
  683.                 return;
  684.             }
  685.  
  686.             CurrentPage.AllowBack = true;
  687.             CurrentPage.AllowNext = true;
  688.         }
  689.  
  690.         #endregion
  691.     }
  692. }
Advertisement
Add Comment
Please, Sign In to add comment