Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using DevExpress.XtraWizard;
- using Facebook;
- using FDown.Properties;
- using Microsoft.WindowsAPICodePack.Taskbar;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Drawing;
- using System.Dynamic;
- using System.IO;
- using System.Net;
- using System.Runtime.InteropServices;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace FDown
- {
- public partial class Form1 : Form
- {
- #region P/Invoke
- [DllImport("user32.dll")]
- private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
- [DllImport("user32.dll")]
- private static extern bool InsertMenu(IntPtr hMenu,
- Int32 wPosition, Int32 wFlags, Int32 wIDNewItem,
- string lpNewItem);
- #endregion
- #region Globals
- bool isBusy = false;
- bool isLoggedIn = false;
- bool isOverwrite = false;
- bool isInfoLoaded = false;
- string accessToken = null;
- string SaveLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\ASync";
- Dictionary<string, int> AlbumCount = new Dictionary<string, int>();
- FacebookClient Client;
- TaskbarManager ITaskbar;
- WebBrowserEx Browser = new WebBrowserEx();
- public const Int32 WM_SYSCOMMAND = 0x112;
- public const Int32 MF_SEPARATOR = 0x800;
- public const Int32 MF_BYPOSITION = 0x400;
- public const Int32 MF_STRING = 0x0;
- public const Int32 IDM_CUSTOMITEM1 = 1000;
- public const Int32 IDM_CUSTOMITEM2 = 1001;
- #endregion
- #region WndProc
- protected override void WndProc(ref Message m)
- {
- if (m.Msg == WM_SYSCOMMAND)
- {
- switch (m.WParam.ToInt32())
- {
- case IDM_CUSTOMITEM1:
- CheckUpdate(true);
- return;
- case IDM_CUSTOMITEM2:
- ShowAbout();
- return;
- default:
- break;
- }
- }
- base.WndProc(ref m);
- }
- #endregion
- #region Properties
- public static bool IsInternetConnected
- {
- get
- {
- try
- {
- using (var client = new WebClient())
- using (var stream = client.OpenRead("http://www.facebook.com"))
- {
- return true;
- }
- }
- catch
- {
- return false;
- }
- }
- }
- #endregion
- #region Helpers
- private Uri GenerateLoginUrl(string appId, string extendedPermissions)
- {
- dynamic parameters = new ExpandoObject();
- parameters.client_id = appId;
- parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
- parameters.response_type = "token";
- parameters.display = "popup";
- if (!string.IsNullOrWhiteSpace(extendedPermissions))
- parameters.scope = extendedPermissions;
- var fb = new FacebookClient();
- return fb.GetLoginUrl(parameters);
- }
- private void FlashMessage(string Msg)
- {
- label3.Text = Msg;
- label3.Visible = true;
- Timer UIx = new Timer()
- {
- Interval = 1000
- };
- UIx.Tick += delegate
- {
- UIx.Stop();
- label3.Visible = false;
- };
- UIx.Start();
- }
- string ValidatePath(string invpath)
- {
- Array.ForEach(Path.GetInvalidFileNameChars(), c => invpath = invpath.Replace(c.ToString(), ""));
- invpath = invpath.TrimEnd('.');
- return invpath.Trim();
- }
- public Image DownloadImage(string _URL)
- {
- Image _tmpImage = null;
- try
- {
- System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);
- _HttpWebRequest.AllowWriteStreamBuffering = true;
- _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
- _HttpWebRequest.Referer = "http://www.google.com/";
- _HttpWebRequest.Timeout = 20000;
- System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();
- System.IO.Stream _WebStream = _WebResponse.GetResponseStream();
- _tmpImage = Image.FromStream(_WebStream);
- _WebResponse.Close();
- _WebResponse.Close();
- }
- catch (Exception _Exception)
- {
- Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
- return null;
- }
- return _tmpImage;
- }
- void CheckUpdate(bool Interface = false)
- {
- if (File.Exists("Updater.exe"))
- {
- ProcessStartInfo PStartInf = new ProcessStartInfo()
- {
- FileName = "Updater.exe"
- };
- if (Interface)
- {
- PStartInf.Verb = "runas";
- PStartInf.UseShellExecute = true;
- PStartInf.Arguments += "--ui";
- }
- Process.Start(PStartInf);
- }
- }
- void FBLogin()
- {
- isBusy = true;
- var loginUrl = GenerateLoginUrl("<REMOVED>", "user_photos");
- Browser.Navigate(loginUrl);
- Timer tX = new Timer()
- {
- Interval = 100
- };
- tX.Tick += delegate
- {
- if ((isLoggedIn == true) && (accessToken != null))
- {
- tX.Stop();
- isBusy = false;
- if (!isInfoLoaded) { LoadInfo(); }
- isInfoLoaded = true;
- wizardControl1.SelectedPageIndex = wizardControl1.SelectedPageIndex + 1;
- }
- };
- tX.Start();
- }
- void ShowAbout()
- {
- MessageBox.Show("ASync was created by H4x0, it was first developed " +
- "for his fiance and later rewritten for general use because " +
- "she was a dumb bitch.\n\nCurrent Version: " +
- Application.ProductVersion +
- "\nRelease: 2/11/13\nStage: Beta", "About ASync", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- #endregion
- public Form1()
- {
- InitializeComponent();
- ITaskbar = TaskbarManager.Instance;
- #region System Menu
- IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false);
- InsertMenu(sysMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
- InsertMenu(sysMenuHandle, 6, MF_BYPOSITION, IDM_CUSTOMITEM1, "Check For Updates");
- InsertMenu(sysMenuHandle, 7, MF_BYPOSITION, IDM_CUSTOMITEM2, "About ASync");
- #endregion
- #region Column Positioning
- this.columnHeader2.Width = 75;
- this.columnHeader1.Width = listView1.Width - 75;
- #endregion
- #region Extended Browser
- Browser.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
- Browser.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
- Browser.NavigateError += new WebBrowserNavigateErrorEventHandler(webBrowser1_Error);
- Browser.Dock = DockStyle.Fill;
- wizardControl1.Pages[1].Controls.Add(Browser);
- #endregion
- }
- #region Facebook Login
- private void webBrowser1_Error(object sender, WebBrowserNavigateErrorEventArgs e)
- {
- pictureBox1.Visible = true;
- pictureBox1.Image = Resources.Exclamation;
- DialogResult Result = MessageBox.Show("Cannot connect to the internet", "ASync", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
- if (Result == System.Windows.Forms.DialogResult.Retry)
- {
- isBusy = false;
- FBLogin();
- pictureBox1.Image = Resources.Loader;
- }
- else
- {
- this.Close();
- }
- }
- private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
- {
- pictureBox1.Visible = true;
- }
- private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
- {
- pictureBox1.Visible = false;
- var fb = new FacebookClient();
- FacebookOAuthResult oauthResult;
- if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
- {
- if (oauthResult.IsSuccess)
- {
- var accesstoken = oauthResult.AccessToken;
- isLoggedIn = true;
- accessToken = accesstoken;
- fb.AccessToken = accessToken;
- Client = fb;
- }
- else
- {
- var errorDescription = oauthResult.ErrorDescription;
- var errorReason = oauthResult.ErrorReason;
- pictureBox1.Visible = true;
- pictureBox1.Image = Resources.Exclamation;
- DialogResult Result = MessageBox.Show("Failed to login to Facebook", "ASync", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
- if (Result == System.Windows.Forms.DialogResult.Retry)
- {
- isBusy = false;
- FBLogin();
- pictureBox1.Image = Resources.Loader;
- }
- else
- {
- this.Close();
- }
- }
- }
- else
- {
- }
- }
- #endregion
- #region Wizard Page Changing
- private void wizardControl1_SelectedPageChanging(object sender, DevExpress.XtraWizard.WizardPageChangingEventArgs e)
- {
- if (e.Page.Text == "Facebook Login")
- {
- FBLogin();
- }
- else if (e.Page.Text == "Options")
- {
- textBox1.Text = SaveLocation;
- button1.Click += delegate
- {
- FolderBrowserDialog Diag = new FolderBrowserDialog();
- Diag.RootFolder = Environment.SpecialFolder.MyPictures;
- Diag.ShowNewFolderButton = true;
- DialogResult Res = Diag.ShowDialog();
- if (Res == System.Windows.Forms.DialogResult.OK)
- {
- textBox1.Text = Diag.SelectedPath;
- }
- };
- }
- if (e.PrevPage.Text == "Options")
- {
- if (!Directory.Exists(textBox1.Text))
- {
- e.Cancel = true;
- MessageBox.Show("Invalid Directory\n\n" + textBox1.Text, "ASync", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- else
- {
- SaveLocation = textBox1.Text;
- }
- }
- }
- private void wizardControl1_SelectedPageChanged(object sender, DevExpress.XtraWizard.WizardPageChangedEventArgs e)
- {
- if (e.Page.Text == "Downloading Photos")
- {
- List<String> toDl = new List<String>();
- isBusy = true;
- foreach (ListViewItem i in listView1.Items)
- {
- if (i.Checked)
- {
- toDl.Add(i.Text);
- }
- }
- isBusy = false;
- Download(toDl);
- }
- }
- #endregion
- #region Wizard Buttons
- private void wizardControl1_PrevClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
- {
- if (isBusy)
- {
- e.Handled = true;
- FlashMessage("Please Wait");
- }
- else
- {
- if (e.Page.Text == "Choose Albums")
- {
- e.Handled = true;
- wizardControl1.SelectedPage = wizardControl1.Pages[0];
- }
- else if (e.Page.Text == "All Done")
- {
- e.Handled = true;
- wizardControl1.SelectedPage = wizardControl1.Pages[3];
- }
- }
- }
- private void wizardControl1_NextClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
- {
- if (isBusy)
- {
- e.Handled = true;
- FlashMessage("Please Wait");
- }
- }
- private void wizardControl1_CancelClick(object sender, System.ComponentModel.CancelEventArgs e)
- {
- if (isBusy)
- {
- 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);
- if (Result == System.Windows.Forms.DialogResult.Yes)
- {
- this.Close();
- }
- }
- else
- {
- this.Close();
- }
- }
- private void wizardControl1_FinishClick(object sender, System.ComponentModel.CancelEventArgs e)
- {
- if (checkBox2.Checked)
- {
- Process.Start(SaveLocation);
- }
- this.Close();
- }
- #endregion
- #region Download Photos Async
- async void Download(List<String> toDl)
- {
- isBusy = true;
- List<int> Counts = new List<int>();
- dynamic albums = Client.Get("me/albums?fields=name,id");
- int PROG_ALB = 1;
- int TPROG_ALB = toDl.Count;
- int PROG_PHO = 1;
- int TPROG_PHO = 0;
- int PROG_TOT = 1;
- int TPROG_TOT = 0;
- Timer x = new Timer()
- {
- Interval = 100
- };
- x.Tick += delegate
- {
- if (isBusy)
- {
- try
- {
- ALBProg.Maximum = TPROG_ALB;
- ALBProg.Value = PROG_ALB;
- label4.Text = string.Format("Downloading {0} of {1} Albums", PROG_ALB, TPROG_ALB);
- PHOProg.Maximum = Counts[PROG_ALB];
- PHOProg.Value = PROG_PHO;
- label5.Text = string.Format("Downloading {0} of {1} Photos", PROG_PHO, Counts[PROG_ALB]);
- ITaskbar.SetProgressValue(PROG_ALB, TPROG_ALB);
- }
- catch { }
- }
- else
- {
- x.Stop();
- ALBProg.Value = 0;
- PHOProg.Value = 0;
- label4.Text = string.Format("Downloading 0 of 0 Albums");
- label5.Text = string.Format("Downloading 0 of 0 Photos");
- ITaskbar.SetProgressState(TaskbarProgressBarState.NoProgress);
- }
- };
- x.Start();
- List<string> DownloadPhotos = await Task<List<string>>.Run(() =>
- {
- #region Count Photos
- foreach (KeyValuePair<string, int> z in AlbumCount)
- {
- if (toDl.Contains(z.Key))
- {
- Counts.Add(z.Value);
- TPROG_TOT = TPROG_TOT + z.Value;
- }
- }
- #endregion
- List<string> log = new List<string>();
- foreach (dynamic albumInfo in albums.data)
- {
- if (toDl.Contains(albumInfo.name))
- {
- string albName = albumInfo.name;
- dynamic albumsPhotos = Client.Get(albumInfo.id + "/photos");
- PROG_PHO = 0;
- foreach (dynamic photoInfo in albumsPhotos.data)
- {
- string imgName = photoInfo.name ?? photoInfo.id;
- if (imgName.Length > 30)
- {
- imgName = imgName.Substring(0, 30);
- }
- imgName = ValidatePath(imgName);
- albName = ValidatePath(albName);
- string savLoca = SaveLocation + "\\" + albName + "\\" + imgName + ".jpg";
- string webLoca = photoInfo.source;
- if (!Directory.Exists(Path.GetDirectoryName(savLoca)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(savLoca));
- }
- if (isOverwrite)
- {
- if (File.Exists(savLoca))
- {
- File.Delete(savLoca);
- }
- }
- if (!File.Exists(savLoca))
- {
- Image _Image = null;
- _Image = DownloadImage(webLoca);
- if (_Image != null)
- {
- _Image.Save(savLoca);
- }
- else { log.Add(string.Format("ERROR: Cannot Download {0}", imgName)); }
- }
- PROG_PHO++;
- PROG_TOT++;
- }
- PROG_ALB++;
- }
- }
- return log;
- });
- foreach (string l in DownloadPhotos)
- {
- richTextBox1.Text += Environment.NewLine + l;
- }
- wizardControl1.SelectedPageIndex = wizardControl1.SelectedPageIndex + 1;
- isBusy = false;
- }
- #endregion
- #region First Load
- async void LoadInfo()
- {
- isBusy = true;
- ITaskbar.SetProgressState(TaskbarProgressBarState.Indeterminate);
- String UI_Status = "Awaiting Connection";
- Timer TX = new Timer()
- {
- Interval = 10
- };
- TX.Tick += delegate
- {
- if (panel1.Visible)
- {
- label2.Text = "Loading..\n" + UI_Status;
- }
- else
- {
- TX.Stop();
- isBusy = false;
- label2.Text = "Loading..";
- ITaskbar.SetProgressState(TaskbarProgressBarState.NoProgress);
- }
- };
- TX.Start();
- Dictionary<string, int> ListAlbums = await Task<Dictionary<string, int>>.Run(() =>
- {
- Dictionary<string, int> RetVal = new Dictionary<string, int>();
- dynamic albums = Client.Get("me/albums?fields=name,id");
- foreach (dynamic albumInfo in albums.data)
- {
- string albName = albumInfo.name;
- UI_Status = string.Format("{0}", albName);
- dynamic albumsPhotos = Client.Get(albumInfo.id + "/photos");
- int Cur = 0;
- foreach (dynamic photoInfo in albumsPhotos.data)
- {
- Cur++;
- }
- RetVal.Add(albName, Cur);
- }
- return RetVal;
- });
- isBusy = true;
- AlbumCount = ListAlbums;
- foreach (KeyValuePair<string, int> x in AlbumCount)
- {
- listView1.Items.Add(new ListViewItem(new string[] { x.Key, x.Value.ToString() }) { Checked = true });
- }
- panel1.Visible = false;
- isBusy = false;
- }
- #endregion
- private void checkBox1_CheckedChanged(object sender, EventArgs e)
- {
- isOverwrite = checkBox1.Checked;
- }
- private void Form1_FormClosed(object sender, FormClosedEventArgs e)
- {
- CheckUpdate();
- }
- #region UI Status
- private void timer1_Tick(object sender, EventArgs e)
- {
- BaseWizardPage CurrentPage = wizardControl1.SelectedPage;
- if (isBusy)
- {
- CurrentPage.AllowBack = false;
- CurrentPage.AllowNext = false;
- return;
- }
- CurrentPage.AllowBack = true;
- CurrentPage.AllowNext = true;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment