private void buttonRemoveFromImgur_Click(object sender, EventArgs e) { int count = listBoxHistory.SelectedItems.Count; bool isMultipleImages = count > 1; int currentCount = 0; listBoxHistory.BeginUpdate(); List <HistoryItem> selectedItems = new List <HistoryItem>(listBoxHistory.SelectedItems.Cast <HistoryItem>()); foreach (HistoryItem item in selectedItems) { ++currentCount; if (item == null) { return; } string balloon_image_counter_text = (isMultipleImages ? (currentCount.ToString() + "/" + count.ToString()) : string.Empty); string balloon_text = "Attempting to remove " + (item.album ? "album" : "image") + " " + balloon_image_counter_text + " from Imgur..."; ShowBalloonTip(2000, "Hold on...", balloon_text, ToolTipIcon.None); if (item.album ? ImgurAPI.DeleteAlbum(item.deletehash, item.anonymous) : ImgurAPI.DeleteImage(item.deletehash, item.anonymous)) { ShowBalloonTip(2000, "Success!", "Removed " + (item.album ? "album" : "image") + " " + balloon_image_counter_text + " from Imgur and history", ToolTipIcon.None); History.RemoveHistoryItem(item); } else { ShowBalloonTip(2000, "Failed", "Failed to remove " + (item.album ? "album" : "image") + " " + balloon_image_counter_text + " from Imgur", ToolTipIcon.Error); } } listBoxHistory.EndUpdate(); }
public Form1(SingleInstance _SingleInstance, string[] _Args) { InitializeComponent(); ImplementPortableMode(); CreateHandle(); // force the handle to be created so Invoke succeeds; see issue #8 for more detail this.notifyIcon1.ContextMenu = this.trayMenu; Application.ApplicationExit += new System.EventHandler(this.ApplicationExit); InitializeEventHandlers(); History.BindData(historyItemBindingSource); // to use the designer with data binding, we have to pass History our BindingSource, instead of just getting one from History History.InitializeFromDisk(); // if we have arguments, we're going to show a tip when we handle those arguments. if (_Args.Length == 0) { ShowBalloonTip(2000, "EasyImgur is ready for use!", "Right-click EasyImgur's icon in the tray to use it!", ToolTipIcon.Info); } ImgurAPI.AttemptRefreshTokensFromDisk(); Statistics.GatherAndSend(); _SingleInstance.ArgumentsReceived += singleInstance_ArgumentsReceived; if (_Args.Length > 0) // handle initial arguments { singleInstance_ArgumentsReceived(this, new ArgumentsReceivedEventArgs() { Args = _Args }); } }
private void buttonForgetTokens_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to discard the tokens?\n\nWithout tokens, the app can no longer use your Imgur account.", "Forget tokens", MessageBoxButtons.YesNo) == DialogResult.Yes) { ImgurAPI.ForgetTokens(); MessageBox.Show("Tokens have been forgotten. Remember that the app has still technically been authorized on the Imgur website, we can't change this for you!\n\nGo to http://imgur.com/account/settings/apps to revoke access.", "Tokens discarded", MessageBoxButtons.OK); } }
private void ApplicationExit(object sender, EventArgs e) { ImgurAPI.OnMainThreadExit(); if (notifyIcon1 != null) { notifyIcon1.Visible = false; } }
private void AccountCredentialsForm_Load(object sender, EventArgs e) { //CredentialsHelper.Credentials credentials = CredentialsHelper.RetrieveCredentials(); //textBoxPIN.Text = credentials.name; //maskedTextBoxAccountPassword.Text = credentials.p; ImgurAPI.OpenAuthorizationPage(); }
private void buttonOK_Click(object sender, EventArgs e) { // Store credentials. // CredentialsHelper.StoreCredentials(textBoxPIN.Text, maskedTextBoxAccountPassword.Text); // Do stuff with the PIN number (requesting access tokens and such). ImgurAPI.RequestTokens(textBoxPIN.Text); this.Close(); }
private void buttonChangeCredentials_Click(object sender, EventArgs e) { AuthorizeForm accountCredentialsForm = new AuthorizeForm(); DialogResult res = accountCredentialsForm.ShowDialog(this); if (ImgurAPI.HasBeenAuthorized()) { buttonForceTokenRefresh.Enabled = true; } else { buttonForceTokenRefresh.Enabled = false; } }
void singleInstance_ArgumentsReceived(object sender, ArgumentsReceivedEventArgs e) { // Using "/exit" anywhere in the command list will cause EasyImgur to exit after uploading; // this will happen regardless of the execution sending the exit command was the execution that // launched the initial instance of EasyImgur. bool exitWhenFinished = false; bool anonymous = false; // mappings of switch names to actions Dictionary <string, Action> handlers = new Dictionary <string, Action>() { { "anonymous", () => anonymous = true }, { "noinfo", () => Verbosity = (MessageVerbosity)Math.Max((int)Verbosity, (int)MessageVerbosity.NoInfo) }, { "q", () => Verbosity = (MessageVerbosity)Math.Max((int)Verbosity, (int)MessageVerbosity.NoInfo) }, { "noerr", () => Verbosity = (MessageVerbosity)Math.Max((int)Verbosity, (int)MessageVerbosity.NoError) }, { "qq", () => Verbosity = (MessageVerbosity)Math.Max((int)Verbosity, (int)MessageVerbosity.NoError) }, { "exit", () => exitWhenFinished = true }, { "portable", () => { } } // ignore }; try { // First scan for switches int badSwitchCount = 0; foreach (String str in e.Args.Where(s => s != null && s.StartsWith("/"))) { String param = str.Remove(0, 1); // Strip the leading '/' from the switch. if (handlers.ContainsKey(param)) { Log.Warning("Consuming command-line switch '" + param + "'."); handlers[param](); } else { ++badSwitchCount; Log.Warning("Ignoring unrecognized command-line switch '" + param + "'."); } } if (badSwitchCount > 0 && ShouldShowMessage(MessageVerbosity.NoError)) { ShowBalloonTip(2000, "Invalid switch", badSwitchCount.ToString() + " invalid switch" + (badSwitchCount > 1 ? "es were" : " was") + " passed to EasyImgur (see log for details). No files were uploaded.", ToolTipIcon.Error, true); return; } // Process actual arguments foreach (string path in e.Args.Where(s => s != null && !s.StartsWith("/"))) { if (!anonymous && !ImgurAPI.HasBeenAuthorized()) { ShowBalloonTip(2000, "Not logged in", "You aren't logged in but you're trying to upload to an account. Authorize EasyImgur and try again.", ToolTipIcon.Error, true); return; } if (Directory.Exists(path)) { string[] fileTypes = new[] { ".jpg", ".jpeg", ".png", ".apng", ".bmp", ".gif", ".tiff", ".tif", ".xcf" }; List <string> files = new List <string>(); foreach (string s in Directory.GetFiles(path)) { bool cont = false; foreach (string filetype in fileTypes) { if (s.EndsWith(filetype, true, null)) { cont = true; break; } } if (!cont) { continue; } files.Add(s); } UploadAlbum(anonymous, files.ToArray(), path.Split('\\').Last()); } else if (File.Exists(path)) { UploadFile(anonymous, new string[] { path }); } } } catch (Exception ex) { Log.Error("Unhandled exception in context menu thread: " + ex.ToString()); ShowBalloonTip(2000, "Error", "An unknown exception occurred during upload. Check the log for further information.", ToolTipIcon.Error, true); } if (exitWhenFinished) { Application.Exit(); } // reset verbosity Verbosity = MessageVerbosity.Normal; }
private void buttonForceTokenRefresh_Click(object sender, EventArgs e) { ImgurAPI.ForceRefreshTokens(); SetAuthorizationStatusUI(ImgurAPI.HasBeenAuthorized()); }
private void SelectedHistoryItemChanged() { HistoryItem item = listBoxHistory.SelectedItem as HistoryItem; if (item == null) { buttonRemoveFromImgur.Enabled = false; buttonRemoveFromHistory.Enabled = false; btnOpenImageLinkInBrowser.Enabled = false; } else { buttonRemoveFromImgur.Enabled = item.anonymous || (!item.anonymous && ImgurAPI.HasBeenAuthorized()); buttonRemoveFromHistory.Enabled = true; btnOpenImageLinkInBrowser.Enabled = true; } }
private void UploadFile(bool _Anonymous, string[] _Paths = null) { if (_Paths == null) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Multiselect = true; DialogResult res = dialog.ShowDialog(); if (res == DialogResult.OK) { _Paths = dialog.FileNames; } } if (_Paths != null) { if (_Paths.Length > 1 && Properties.Settings.Default.uploadMultipleImagesAsGallery) { UploadAlbum(_Anonymous, _Paths, ""); return; } int success = 0; int failure = 0; int i = 0; foreach (string fileName in _Paths) { ++i; if (fileName == null || fileName == string.Empty) { continue; } string fileCounterString = (_Paths.Length > 1) ? (" (" + i.ToString() + "/" + _Paths.Length.ToString() + ") ") : (string.Empty); try { ShowBalloonTip(2000, "Hold on..." + fileCounterString, "Attempting to upload image to Imgur...", ToolTipIcon.None); Image img; APIResponses.ImageResponse resp; using (System.IO.FileStream stream = System.IO.File.Open(fileName, System.IO.FileMode.Open)) { // a note to the future: ImgurAPI.UploadImage called Image.Save(); Image.Save() // requires that the stream it was loaded from still be open, or else you get // an immensely generic error. img = System.Drawing.Image.FromStream(stream); FormattingHelper.FormattingContext format_context = new FormattingHelper.FormattingContext(); format_context.m_Filepath = fileName; resp = ImgurAPI.UploadImage(img, GetTitleString(format_context), GetDescriptionString(format_context), _Anonymous); } if (resp.success) { success++; if (Properties.Settings.Default.copyLinks) { // clipboard calls can only be made on an STA thread, threading model is MTA when invoked from context menu if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA) { this.Invoke(new Action(delegate { Clipboard.SetText(resp.data.link); })); } else { Clipboard.SetText(resp.data.link); } } ShowBalloonTip(2000, "Success!" + fileCounterString, Properties.Settings.Default.copyLinks ? "Link copied to clipboard" : "Upload placed in history: " + resp.data.link, ToolTipIcon.None); HistoryItem item = new HistoryItem(); item.timestamp = DateTime.Now; item.id = resp.data.id; item.link = resp.data.link; item.deletehash = resp.data.deletehash; item.title = resp.data.title; item.description = resp.data.description; item.anonymous = _Anonymous; item.thumbnail = img.GetThumbnailImage(pictureBox1.Width, pictureBox1.Height, null, System.IntPtr.Zero); Invoke(new Action(() => { History.StoreHistoryItem(item); })); } else { failure++; ShowBalloonTip(2000, "Failed" + fileCounterString, "Could not upload image (" + resp.status + "): " + resp.data.error, ToolTipIcon.None, true); } } catch (System.IO.FileNotFoundException) { failure++; ShowBalloonTip(2000, "Failed" + fileCounterString, "Could not find image file on disk (" + fileName + "):", ToolTipIcon.Error, true); } catch (IOException) { ShowBalloonTip(2000, "Failed" + fileCounterString, "Image is in use by another program (" + fileName + "):", ToolTipIcon.Error, true); } } if (_Paths.Length > 1) { ShowBalloonTip(2000, "Done", "Successfully uploaded " + success.ToString() + " files" + ((failure > 0) ? (" (Warning: " + failure.ToString() + " failed)") : (string.Empty)), ToolTipIcon.Info, failure > 0); } } }
private void UploadAlbum(bool _Anonymous, string[] _Paths, string _AlbumTitle) { ShowBalloonTip(2000, "Hold on...", "Attempting to upload album to Imgur (this may take a while)...", ToolTipIcon.None); List <Image> images = new List <Image>(); List <string> titles = new List <string>(); List <string> descriptions = new List <string>(); int i = 0; foreach (string path in _Paths) { try { images.Add(Image.FromStream(new MemoryStream(File.ReadAllBytes(path)))); //ìmages.Add(System.Drawing.Image.FromStream(stream)); string title = string.Empty; string description = string.Empty; FormattingHelper.FormattingContext format_context = new FormattingHelper.FormattingContext(); format_context.m_Filepath = path; format_context.m_AlbumIndex = ++i; titles.Add(GetTitleString(format_context)); descriptions.Add(GetDescriptionString(format_context)); } catch (FileNotFoundException) { ShowBalloonTip(2000, "Failed", "Could not find image file on disk (" + path + "):", ToolTipIcon.Error, true); } catch (IOException) { ShowBalloonTip(2000, "Failed", "Image is in use by another program (" + path + "):", ToolTipIcon.Error, true); } } APIResponses.AlbumResponse response = ImgurAPI.UploadAlbum(images.ToArray(), _AlbumTitle, _Anonymous, titles.ToArray(), descriptions.ToArray()); if (response.success) { // clipboard calls can only be made on an STA thread, threading model is MTA when invoked from context menu if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA) { this.Invoke(new Action(delegate { Clipboard.SetText(response.data.link); })); } else { Clipboard.SetText(response.data.link); } ShowBalloonTip(2000, "Success!", Properties.Settings.Default.copyLinks ? "Link copied to clipboard" : "Upload placed in history: " + response.data.link, ToolTipIcon.None); HistoryItem item = new HistoryItem(); item.timestamp = DateTime.Now; item.id = response.data.id; item.link = response.data.link; item.deletehash = response.data.deletehash; item.title = response.data.title; item.description = response.data.description; item.anonymous = _Anonymous; item.album = true; item.thumbnail = response.CoverImage.GetThumbnailImage(pictureBox1.Width, pictureBox1.Height, null, System.IntPtr.Zero); Invoke(new Action(() => { History.StoreHistoryItem(item); })); } else { ShowBalloonTip(2000, "Failed", "Could not upload album (" + response.status + "): " + response.data.error, ToolTipIcon.None, true); } }
private void UploadClipboard(bool _Anonymous) { APIResponses.ImageResponse resp = null; Image clipboardImage = null; string clipboardURL = string.Empty; //bool anonymous = !Properties.Settings.Default.useAccount || !ImgurAPI.HasBeenAuthorized(); bool anonymous = _Anonymous; if (Clipboard.ContainsImage()) { clipboardImage = Clipboard.GetImage(); ShowBalloonTip(4000, "Hold on...", "Attempting to upload image to Imgur...", ToolTipIcon.None); resp = ImgurAPI.UploadImage(clipboardImage, GetTitleString(null), GetDescriptionString(null), _Anonymous); } else if (Clipboard.ContainsText()) { clipboardURL = Clipboard.GetText(TextDataFormat.UnicodeText); Uri uriResult; if (Uri.TryCreate(clipboardURL, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)) { ShowBalloonTip(4000, "Hold on...", "Attempting to upload image to Imgur...", ToolTipIcon.None); resp = ImgurAPI.UploadImage(clipboardURL, GetTitleString(null), GetDescriptionString(null), _Anonymous); } else { ShowBalloonTip(2000, "Can't upload clipboard!", "There's text on the clipboard but it's not a valid URL", ToolTipIcon.Error, true); return; } } else { ShowBalloonTip(2000, "Can't upload clipboard!", "There's no image or URL there", ToolTipIcon.Error, true); return; } if (resp.success) { // this doesn't need an invocation guard because this function can't be called from the context menu if (Properties.Settings.Default.copyLinks) { Clipboard.SetText(resp.data.link); } ShowBalloonTip(2000, "Success!", Properties.Settings.Default.copyLinks ? "Link copied to clipboard" : "Upload placed in history: " + resp.data.link, ToolTipIcon.None); HistoryItem item = new HistoryItem(); item.timestamp = DateTime.Now; item.id = resp.data.id; item.link = resp.data.link; item.deletehash = resp.data.deletehash; item.title = resp.data.title; item.description = resp.data.description; item.anonymous = anonymous; if (clipboardImage != null) { item.thumbnail = clipboardImage.GetThumbnailImage(pictureBox1.Width, pictureBox1.Height, null, System.IntPtr.Zero); } History.StoreHistoryItem(item); } else { ShowBalloonTip(2000, "Failed", "Could not upload image (" + resp.status + "):", ToolTipIcon.None, true); } if (!Properties.Settings.Default.clearClipboardOnUpload) { if (clipboardImage != null) { Clipboard.SetImage(clipboardImage); } else { Clipboard.SetText(clipboardURL, TextDataFormat.UnicodeText); } } }
private void SelectedHistoryItemChanged() { groupBoxHistorySelection.Text = String.Format("Selection: {0} {1}", listBoxHistory.SelectedItems.Count, listBoxHistory.SelectedItems.Count == 1 ? "item" : "items"); HistoryItem item = listBoxHistory.SelectedItem as HistoryItem; if (item == null) { buttonRemoveFromImgur.Enabled = false; buttonRemoveFromHistory.Enabled = false; btnOpenImageLinkInBrowser.Enabled = false; } else { buttonRemoveFromImgur.Enabled = item.Anonymous || (!item.Anonymous && ImgurAPI.HasBeenAuthorized()); buttonRemoveFromHistory.Enabled = true; btnOpenImageLinkInBrowser.Enabled = true; } }
private void UploadAlbum(bool _Anonymous, string[] _Paths, string _AlbumTitle) { ShowBalloonTip(2000, "Hold on...", "Attempting to upload album to Imgur (this may take a while)...", ToolTipIcon.None); // Create the album APIResponses.AlbumResponse album_response = ImgurAPI.CreateAlbum(_AlbumTitle, _Anonymous); if (!album_response.Success) { ShowBalloonTip(2000, "Failed", "Could not create album (" + album_response.Status + "): " + album_response.ResponseData.Error.Message, ToolTipIcon.None, true); Statistics.GatherAndSend(); return; } // If we did manage to create the album we can now try to add images to it int succeeded_count = 0; int failed_count = 0; int image_idx = 0; Image album_thumbnail = null; foreach (string path in _Paths) { // Instead of loading every file into memory, peek only their header to check if they are valid images try { Image img = Image.FromStream(new MemoryStream(File.ReadAllBytes(path))); string title = string.Empty; string description = string.Empty; FormattingHelper.FormattingContext format_context = new FormattingHelper.FormattingContext(); format_context.FilePath = path; format_context.AlbumIndex = ++image_idx; APIResponses.ImageResponse resp = ImgurAPI.UploadImage(img, GetTitleString(format_context), GetDescriptionString(format_context), _Anonymous, ref album_response); // If we haven't selected any thumbnail yet, or if the currently uploaded image has been turned into the cover image of the album, turn it into a thumbnail for the history view. if (album_thumbnail == null || resp.ResponseData.Id == album_response.ResponseData.Cover) { album_thumbnail = GenerateThumbnailImage(img, pictureBoxHistoryThumb.Width, pictureBoxHistoryThumb.Height); } if (resp.Success) { succeeded_count++; } else { failed_count++; } } catch (ArgumentException) { ShowBalloonTip(2000, "Failed", "File (" + path + ") is not a valid image file.", ToolTipIcon.Error, true); } catch (FileNotFoundException) { ShowBalloonTip(2000, "Failed", "Could not find image file on disk (" + path + "):", ToolTipIcon.Error, true); } catch (IOException) { ShowBalloonTip(2000, "Failed", "Image is in use by another program (" + path + "):", ToolTipIcon.Error, true); } } // If no images managed to upload to the album we should delete it again if (failed_count == _Paths.Count()) { ShowBalloonTip(2000, "Album upload cancelled", "All images failed to upload! Check the log for more info.", ToolTipIcon.Error, true); // Delete the album because we couldn't upload anything ImgurAPI.DeleteAlbum(album_response.ResponseData.DeleteHash, _Anonymous); Statistics.GatherAndSend(); return; } // Did we succeed in uploading the album? if (album_response.Success) { // Clipboard calls can only be made on an STA thread, threading model is MTA when invoked from context menu if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA) { this.Invoke(new Action(() => Clipboard.SetText(Properties.Settings.Default.copyHttpsLinks ? album_response.ResponseData.Link.Replace("http://", "https://") : album_response.ResponseData.Link))); } else { Clipboard.SetText(Properties.Settings.Default.copyHttpsLinks ? album_response.ResponseData.Link.Replace("http://", "https://") : album_response.ResponseData.Link); } ShowBalloonTip(2000, "Success!", Properties.Settings.Default.copyLinks ? "Link copied to clipboard" : "Upload placed in history: " + album_response.ResponseData.Link, ToolTipIcon.None); HistoryItem item = new HistoryItem(); item.Timestamp = DateTime.Now; item.Id = album_response.ResponseData.Id; item.Link = album_response.ResponseData.Link; item.Deletehash = album_response.ResponseData.DeleteHash; item.Title = album_response.ResponseData.Title; item.Description = album_response.ResponseData.Description; item.Anonymous = _Anonymous; item.Album = true; item.Thumbnail = album_thumbnail; Invoke(new Action(() => History.StoreHistoryItem(item))); } else { ShowBalloonTip(2000, "Failed", "Could not upload album (" + album_response.Status + "): " + album_response.ResponseData.Error.Message, ToolTipIcon.None, true); } Statistics.GatherAndSend(); }