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); } }
public static APIResponses.AlbumResponse UploadAlbum(Image[] images, string albumTitle, bool anonymous, string[] titles, string[] descriptions) { var url = mEndPoint + "album"; var responseString = ""; using (var t = WebClientFactory.Create()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(anonymous); try { var values = new System.Collections.Specialized.NameValueCollection { { "title", albumTitle }, { "layout", "vertical" } }; responseString = Encoding.ASCII.GetString(t.UploadValues(url, "POST", values)); //responseString = t.UploadString(url + "/ZHPG7sztcWB26YM", "DELETE", ""); } catch (WebException ex) { if (ex.Response == null) { if (NetworkRequestFailed != null) NetworkRequestFailed.Invoke(); } else { 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()); } } APIResponses.AlbumResponse resp = null; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject<APIResponses.AlbumResponse>(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 == "" || responseString == null) resp = new APIResponses.AlbumResponse() { Success = false }; if (resp.Success) Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); else { Log.Error("Failed to create album! (" + resp.Status.ToString() + ")"); return resp; } // sometimes this happens! it's weird. if (anonymous && resp.ResponseData.DeleteHash == null) { Log.Error("Anonymous album creation didn't return deletehash. Can't add to album."); resp.Success = false; resp.ResponseData.Error = "Imgur API error. Try again in a minute."; // can't even be responsible and delete our orphaned album return resp; } // in case I need them later var responses = new List<APIResponses.ImageResponse>(); for (var i = 0; i < images.Count(); ++i) { var image = images[i]; var title = string.Empty; if (i < titles.Count()) title = titles[i]; var description = string.Empty; if (i < descriptions.Count()) description = descriptions[i]; responses.Add(InternalUploadImage(image, false, title, description, anonymous, anonymous ? resp.ResponseData.DeleteHash : resp.ResponseData.Id)); } // since an album creation doesn't return very much in the manner of information, make a request to // get the fully populated album var deletehash = resp.ResponseData.DeleteHash; // save deletehash responseString = ""; using (var t = WebClientFactory.Create()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(anonymous); try { responseString = t.DownloadString(url + "/" + resp.ResponseData.Id); } catch (WebException ex) { if (ex.Response == null) { if (NetworkRequestFailed != null) NetworkRequestFailed.Invoke(); } else { 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()); } } var oldResp = resp; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject<APIResponses.AlbumResponse>(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); } if (resp == null || responseString == "" || responseString == null) resp = new APIResponses.AlbumResponse() { Success = false }; resp.ResponseData.DeleteHash = deletehash; if (resp.Success) { var i = 0; foreach (var response in resp.ResponseData.Images) if (response.Id == resp.ResponseData.Cover) break; else i++; if (i < images.Length) resp.CoverImage = images[i]; else resp.CoverImage = null; } if (resp.Success) Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); else { Log.Error("Created album, but failed to get album information! (" + resp.Status.ToString() + ")"); return oldResp; } return resp; }
static public APIResponses.AlbumResponse UploadAlbum(Image[] _Images, string _AlbumTitle, bool _Anonymous, string[] _Titles, string[] _Descriptions) { string url = m_EndPoint + "album"; string responseString = ""; using (WebClient t = new WebClient()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(_Anonymous); try { var values = new System.Collections.Specialized.NameValueCollection { { "title", _AlbumTitle }, { "layout", "vertical" } }; responseString = System.Text.Encoding.ASCII.GetString(t.UploadValues(url, "POST", values)); //responseString = t.UploadString(url + "/ZHPG7sztcWB26YM", "DELETE", ""); } catch (System.Net.WebException ex) { if (ex.Response == null) { if (networkRequestFailed != null) { networkRequestFailed.Invoke(); } } else { 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()); } } APIResponses.AlbumResponse resp = null; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.AlbumResponse>(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 == "" || responseString == null) { resp = new APIResponses.AlbumResponse() { Success = false } } ; if (resp.Success) { Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); } else { Log.Error("Failed to create album! (" + resp.Status.ToString() + ")"); return(resp); } // sometimes this happens! it's weird. if (_Anonymous && resp.ResponseData.DeleteHash == null) { Log.Error("Anonymous album creation didn't return deletehash. Can't add to album."); resp.Success = false; resp.ResponseData.Error = "Imgur API error. Try again in a minute."; // can't even be responsible and delete our orphaned album return(resp); } // in case I need them later List <APIResponses.ImageResponse> responses = new List <APIResponses.ImageResponse>(); for (int i = 0; i < _Images.Count(); ++i) { Image image = _Images[i]; string title = string.Empty; if (i < _Titles.Count()) { title = _Titles[i]; } string description = string.Empty; if (i < _Descriptions.Count()) { description = _Descriptions[i]; } responses.Add(InternalUploadImage(image, false, title, description, _Anonymous, _Anonymous ? resp.ResponseData.DeleteHash : resp.ResponseData.Id)); } // since an album creation doesn't return very much in the manner of information, make a request to // get the fully populated album string deletehash = resp.ResponseData.DeleteHash; // save deletehash responseString = ""; using (WebClient t = new WebClient()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(_Anonymous); try { responseString = t.DownloadString(url + "/" + resp.ResponseData.Id); } catch (System.Net.WebException ex) { if (ex.Response == null) { if (networkRequestFailed != null) { networkRequestFailed.Invoke(); } } else { 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()); } } APIResponses.AlbumResponse oldResp = resp; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.AlbumResponse>(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); } if (resp == null || responseString == "" || responseString == null) { resp = new APIResponses.AlbumResponse() { Success = false } } ; resp.ResponseData.DeleteHash = deletehash; if (resp.Success) { int i = 0; foreach (var response in resp.ResponseData.Images) { if (response.Id == resp.ResponseData.Cover) { break; } else { i++; } } if (i < _Images.Length) { resp.CoverImage = _Images[i]; } else { resp.CoverImage = null; } } if (resp.Success) { Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); } else { Log.Error("Created album, but failed to get album information! (" + resp.Status.ToString() + ")"); return(oldResp); } 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(); }
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); }
/// <summary> /// Update the data contained in <paramref name="_Album"/> by requesting it from the API and updating in-place /// </summary> static private bool UpdateAlbumResponse(bool _Anonymous, ref APIResponses.AlbumResponse _Album) { string url = m_EndPoint + "album"; // Since album creation doesn't return very much in the manner of information, make a request to get the fully populated album string deletehash = _Album.ResponseData.DeleteHash; // save deletehash string responseString = ""; using (WebClient t = new WebClient()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(_Anonymous); try { responseString = t.DownloadString(url + "/" + _Album.ResponseData.Id); } catch (System.Net.WebException ex) { if (ex.Response == null) { if (networkRequestFailed != null) { networkRequestFailed.Invoke(); } } else { 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()); } } APIResponses.AlbumResponse oldResp = _Album; try { _Album = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.AlbumResponse>(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); } if (_Album == null || responseString == "" || responseString == null) { return(false); } _Album.ResponseData.DeleteHash = deletehash; if (_Album.Success) { int i = 0; foreach (var response in _Album.ResponseData.Images) { if (response.Id == _Album.ResponseData.Cover) { break; } else { i++; } } //_Album.CoverImage = albumCoverImg; } return(true); }
static public APIResponses.AlbumResponse CreateAlbum(string _AlbumTitle, bool _Anonymous) { string url = m_EndPoint + "album"; string responseString = ""; using (WebClient t = new WebClient()) { t.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(_Anonymous); try { var values = new System.Collections.Specialized.NameValueCollection { { "title", _AlbumTitle }, { "layout", "vertical" } }; responseString = System.Text.Encoding.ASCII.GetString(t.UploadValues(url, "POST", values)); } catch (System.Net.WebException ex) { if (ex.Response == null) { if (networkRequestFailed != null) { networkRequestFailed.Invoke(); } } else { 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()); } } APIResponses.AlbumResponse resp = null; try { resp = Newtonsoft.Json.JsonConvert.DeserializeObject <APIResponses.AlbumResponse>(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 == "" || responseString == null) { resp = new APIResponses.AlbumResponse() { Success = false } } ; if (resp.Success) { Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); } else { Log.Error("Failed to create album! (" + resp.Status.ToString() + ")"); return(resp); } // sometimes this happens! it's weird. if (_Anonymous && resp.ResponseData.DeleteHash == null) { Log.Error("Anonymous album creation didn't return deletehash. Can't add to album."); resp.Success = false; resp.ResponseData.Error = new APIResponses.BaseResponse.BaseResponseError("Imgur API error. Try again in a minute."); // can't even be responsible and delete our orphaned album return(resp); } APIResponses.AlbumResponse oldResp = resp; if (UpdateAlbumResponse(_Anonymous, ref resp)) { Log.Info("Successfully created album! (" + resp.Status.ToString() + ")"); } else { Log.Error("Created album, but failed to get album information! (" + resp.Status.ToString() + ")"); return(oldResp); } return(resp); }
static public APIResponses.ImageResponse UploadImage(string _URL, string _Title, string _Description, bool _Anonymous, ref APIResponses.AlbumResponse _Album) { return(InternalUploadImage(_URL, true, _Title, _Description, _Anonymous, ref _Album)); }