static private APIResponses.ImageResponse InternalUploadImage(object _Obj, bool _URL, string _Title, string _Description, bool _Anonymous, ref APIResponses.AlbumResponse _Album) { APIResponses.ImageResponse resp = InternalUploadImage(_Obj, _URL, _Title, _Description, _Anonymous, _Anonymous ? _Album.ResponseData.DeleteHash : _Album.ResponseData.Id); if (resp.Success) { UpdateAlbumResponse(_Anonymous, ref _Album); } return(resp); }
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); } } }
static public bool DeleteImage(string _DeleteHash, bool _AnonymousImage) { string url = m_EndPoint + "image/" + _DeleteHash; if (!_AnonymousImage && !HasBeenAuthorized()) { Log.Error("Can't delete an image that belongs to an account while the app is no longer authorized!"); return(false); } string responseString = string.Empty; using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(false); try { responseString = wc.UploadString(url, "DELETE", string.Empty); } catch (System.Net.WebException ex) { if (ex.Status != WebExceptionStatus.Success) { if (networkRequestFailed != null) { networkRequestFailed.Invoke(); } } Log.Error("An exception was thrown while trying to delete an image from Imgur (" + ex.Status + ") [deletehash: " + _DeleteHash + "]"); } catch (System.Exception ex) { Log.Error("Unexpected Exception: " + ex.ToString()); } } APIResponses.BaseResponse resp = null; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.BaseResponse>(responseString, new Newtonsoft.Json.JsonSerializerSettings { PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects }); } catch (System.Exception ex) { Log.Error("Newtonsoft.Json.JsonConvert.DeserializeObject threw an exception!: " + ex.Message + "Stack trace:\n\r" + ex.StackTrace); resp = null; } if (resp == null || responseString == null || responseString == string.Empty) { resp = new APIResponses.ImageResponse(); resp.Success = false; } if (resp.Success) { Log.Info("Successfully deleted image! (" + resp.Status.ToString() + ")"); return(true); } Log.Error("Failed to delete image! (" + resp.Status.ToString() + ") [\n\rdeletehash: " + _DeleteHash + "\n\r]"); return(false); }
static private APIResponses.ImageResponse InternalUploadImage(object _Obj, bool _URL, string _Title, string _Description, bool _Anonymous, string album = "") { if (_Obj == null) { throw new System.ArgumentNullException(); } string url = m_EndPoint + "image"; string responseString = string.Empty; byte[] response = null; APIResponses.ImageResponse resp = null; using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { if (!_URL) { Image _Image = _Obj as Image; System.Drawing.Imaging.ImageFormat format = _Image.RawFormat; switch (Properties.Settings.Default.imageFormat) { case 1: { format = System.Drawing.Imaging.ImageFormat.Jpeg; break; } case 2: { format = System.Drawing.Imaging.ImageFormat.Png; break; } case 3: { format = System.Drawing.Imaging.ImageFormat.Gif; break; } case 4: { format = System.Drawing.Imaging.ImageFormat.Bmp; break; } case 5: { format = System.Drawing.Imaging.ImageFormat.Icon; break; } case 6: { format = System.Drawing.Imaging.ImageFormat.Tiff; break; } case 7: { format = System.Drawing.Imaging.ImageFormat.Emf; break; } case 8: { format = System.Drawing.Imaging.ImageFormat.Wmf; break; } case 0: default: // Auto mode. { // Check whether it is a valid format. if (format.Equals(System.Drawing.Imaging.ImageFormat.Bmp) || format.Equals(System.Drawing.Imaging.ImageFormat.Gif) || format.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) || format.Equals(System.Drawing.Imaging.ImageFormat.Icon) || format.Equals(System.Drawing.Imaging.ImageFormat.Png) || format.Equals(System.Drawing.Imaging.ImageFormat.Tiff) || format.Equals(System.Drawing.Imaging.ImageFormat.Emf) || format.Equals(System.Drawing.Imaging.ImageFormat.Wmf)) { // It's fine. } else { // In all other cases, use PNG. format = System.Drawing.Imaging.ImageFormat.Png; } break; } } _Image.Save(memStream, format); } int status = 0; string error = "An unknown error occurred."; using (WebClient t = new WebClient()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(_Anonymous); try { var values = new System.Collections.Specialized.NameValueCollection { { "image", _URL ? _Obj as string : Convert.ToBase64String(memStream.ToArray()) }, { "title", _Title }, { "description", _Description }, { "type", _URL ? "URL" : "base64" } }; if (album != "") { values.Add("album", album); } response = t.UploadValues(url, "POST", values); responseString = System.Text.Encoding.ASCII.GetString(response); } catch (System.Net.WebException ex) { if (ex.Response == null) { if (networkRequestFailed != null) { networkRequestFailed(); } } else { int.TryParse(ex.Message.Split('(')[1].Split(')')[0], out status); // gets status code from message string in case of emergency error = ex.Message.Split('(')[1].Split(')')[1]; // I believe this gets the rest of the error message supplied, but Imgur went back up before I could test it System.IO.Stream stream = ex.Response.GetResponseStream(); int currByte = -1; StringBuilder strBuilder = new StringBuilder(); while ((currByte = stream.ReadByte()) != -1) { strBuilder.Append((char)currByte); } responseString = strBuilder.ToString(); } } catch (System.Exception ex) { Log.Error("Unexpected Exception: " + ex.ToString()); } } try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.ImageResponse>(responseString, new Newtonsoft.Json.JsonSerializerSettings { PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects }); } catch (System.Exception ex) { Log.Error("Newtonsoft.Json.JsonConvert.DeserializeObject threw an exception!: " + ex.Message + "Stack trace:\n\r" + ex.StackTrace); resp = null; } if (resp == null || responseString == null || responseString == string.Empty) { // generally indicates a server failure; on problems such as 502 Proxy Error and 504 Gateway Timeout HTML is returned // which can't be parsed by the JSON converter. resp = new APIResponses.ImageResponse(); resp.Success = false; resp.Status = status; resp.ResponseData = new APIResponses.ImageResponse.Data() { Error = error }; } if (resp.Success) { Log.Info("Successfully uploaded image! (" + resp.Status.ToString() + ")[\n\rid: " + resp.ResponseData.Id + "\n\rlink: " + resp.ResponseData.Link + "\n\rdeletehash: " + resp.ResponseData.DeleteHash + "\n\r]"); ++m_NumUploads; } else { Log.Error("Failed to upload image (" + resp.Status.ToString() + ")"); } } return(resp); }
public static bool DeleteAlbum(string deleteHash, bool anonymousAlbum) { var url = mEndPoint + "album/" + deleteHash; if (!anonymousAlbum && !HasBeenAuthorized()) { Log.Error("Can't delete an album that belongs to an account while the app is no longer authorized!"); return false; } var responseString = string.Empty; using (var wc = WebClientFactory.Create()) { wc.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(false); try { responseString = wc.UploadString(url, "DELETE", string.Empty); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.Success) { if (NetworkRequestFailed != null) NetworkRequestFailed.Invoke(); } Log.Error("An exception was thrown while trying to delete an image from Imgur (" + ex.Status + ") [deletehash: " + deleteHash + "]"); } catch (Exception ex) { Log.Error("Unexpected Exception: " + ex.ToString()); } } APIResponses.BaseResponse resp = null; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject<APIResponses.BaseResponse>(responseString, new Newtonsoft.Json.JsonSerializerSettings { PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects }); } catch (Exception ex) { Log.Error("Newtonsoft.Json.JsonConvert.DeserializeObject threw an exception!: " + ex.Message + "Stack trace:\n\r" + ex.StackTrace); resp = null; } if (resp == null || responseString == null || responseString == string.Empty) { resp = new APIResponses.ImageResponse(); resp.Success = false; } if (resp.Success) { Log.Info("Successfully deleted album! (" + resp.Status.ToString() + ")"); return true; } Log.Error("Failed to delete album! (" + resp.Status.ToString() + ") [\n\rdeletehash: " + deleteHash + "\n\r]"); return false; }
private static APIResponses.ImageResponse InternalUploadImage(object obj, bool _URL, string title, string description, bool anonymous, string album = "") { if (obj == null) { throw new ArgumentNullException(); } var url = mEndPoint + "image"; var responseString = string.Empty; byte[] response = null; APIResponses.ImageResponse resp = null; using (var memStream = new System.IO.MemoryStream()) { if (!_URL) { var image = obj as Image; var format = image.RawFormat; switch (Properties.Settings.Default.imageFormat) { case 1: { format = System.Drawing.Imaging.ImageFormat.Jpeg; break; } case 2: { format = System.Drawing.Imaging.ImageFormat.Png; break; } case 3: { format = System.Drawing.Imaging.ImageFormat.Gif; break; } case 4: { format = System.Drawing.Imaging.ImageFormat.Bmp; break; } case 5: { format = System.Drawing.Imaging.ImageFormat.Icon; break; } case 6: { format = System.Drawing.Imaging.ImageFormat.Tiff; break; } case 7: { format = System.Drawing.Imaging.ImageFormat.Emf; break; } case 8: { format = System.Drawing.Imaging.ImageFormat.Wmf; break; } case 0: default: // Auto mode. { // Check whether it is a valid format. if (format.Equals(System.Drawing.Imaging.ImageFormat.Bmp) || format.Equals(System.Drawing.Imaging.ImageFormat.Gif) || format.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) || format.Equals(System.Drawing.Imaging.ImageFormat.Icon) || format.Equals(System.Drawing.Imaging.ImageFormat.Png) || format.Equals(System.Drawing.Imaging.ImageFormat.Tiff) || format.Equals(System.Drawing.Imaging.ImageFormat.Emf) || format.Equals(System.Drawing.Imaging.ImageFormat.Wmf)) { // It's fine. } else { // In all other cases, use PNG. format = System.Drawing.Imaging.ImageFormat.Png; } break; } } image.Save(memStream, format); } var status = 0; var error = "An unknown error occurred."; using (var t = WebClientFactory.Create()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(anonymous); try { var values = new System.Collections.Specialized.NameValueCollection { { "image", _URL ? obj as string : Convert.ToBase64String(memStream.ToArray()) }, { "title", title }, { "description", description }, { "type", _URL ? "URL" : "base64" } }; if (album != "") values.Add("album", album); response = t.UploadValues(url, "POST", values); responseString = Encoding.ASCII.GetString(response); } catch (WebException ex) { if (ex.Response == null) { if (NetworkRequestFailed != null) NetworkRequestFailed(); } else { int.TryParse(ex.Message.Split('(')[1].Split(')')[0], out status); // gets status code from message string in case of emergency error = ex.Message.Split('(')[1].Split(')')[1]; // I believe this gets the rest of the error message supplied, but Imgur went back up before I could test it var stream = ex.Response.GetResponseStream(); var currByte = -1; var strBuilder = new StringBuilder(); while ((currByte = stream.ReadByte()) != -1) { strBuilder.Append((char)currByte); } responseString = strBuilder.ToString(); } } catch (Exception ex) { Log.Error("Unexpected Exception: " + ex.ToString()); } } try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject<APIResponses.ImageResponse>(responseString, new Newtonsoft.Json.JsonSerializerSettings { PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects }); } catch (Exception ex) { Log.Error("Newtonsoft.Json.JsonConvert.DeserializeObject threw an exception!: " + ex.Message + "Stack trace:\n\r" + ex.StackTrace); resp = null; } if (resp == null || responseString == null || responseString == string.Empty) { // generally indicates a server failure; on problems such as 502 Proxy Error and 504 Gateway Timeout HTML is returned // which can't be parsed by the JSON converter. resp = new APIResponses.ImageResponse(); resp.Success = false; resp.Status = status; resp.ResponseData = new APIResponses.ImageResponse.Data() { Error = error }; } if (resp.Success) { Log.Info("Successfully uploaded image! (" + resp.Status.ToString() + ")[\n\rid: " + resp.ResponseData.Id + "\n\rlink: " + resp.ResponseData.Link + "\n\rdeletehash: " + resp.ResponseData.DeleteHash + "\n\r]"); ++mNumUploads; } else { Log.Error("Failed to upload image (" + resp.Status.ToString() + ")"); } } return resp; }
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(); }