static void i_UpdateStatus(object source, ImgurUploaderStatus s) { _f.FilesMessage = s.TotalMessage; _f.FilesProgress = s.TotalProgress; _f.UploadMessage = s.FileBeingProcessed + " " + s.FileProcessMessage; _f.UploadProgress = s.FileProcessProgress; }
#pragma warning restore 0649 void AttemptReauthorize(ImgurUploaderStatus status) { status.FileProcessMessage = "Access token expired, re-authorizing..."; UpdateStatus(this, status); try { Authorize(GrantType.RefreshToken, Settings.Default.RefreshToken); } catch (AuthorizationException aEx) { MessageBox.Show("Could not authorize. Try re-authorizing your account.", "Error"); Application.Exit(); Application.Run(new SettingsForm()); return; } this.UploadFiles(); }
public void UploadFiles() { Dictionary <string, string> fields = new Dictionary <string, string>(); fields.Add("key", ConfigurationManager.AppSettings["APIKey"]); int currentFileNumber = 0; foreach (string file in Files) { currentFileNumber++; string TotalMessage = String.Format("Dealing with file {0}/{1}", currentFileNumber, Files.Count); double TotalProgress = (currentFileNumber - 1) / (Files.Count * 1.0f); ImgurUploaderStatus status = new ImgurUploaderStatus { TotalMessage = TotalMessage, TotalProgress = TotalProgress, FileBeingProcessed = Path.GetFileName(file) }; try { status.FileProcessProgress = 0; status.FileProcessMessage = "Verifying existence"; UpdateStatus(this, status); if (!File.Exists(file)) { throw new InvalidFileException { Message = "File could not be found" } } ; status.FileProcessMessage = "Verifying file integrity"; UpdateStatus(this, status); try { Image i = Image.FromFile(file); } catch (ArgumentException) { throw new InvalidFileException { Message = "File did not appear to be an image" }; } //okee - moving on! now lets compose a webrequest and send it along it's merry way. HttpWebRequest hr = WebRequest.Create(ConfigurationManager.AppSettings["UploadURL"]) as HttpWebRequest; string bound = "----------------------------" + DateTime.Now.Ticks.ToString("x"); hr.ContentType = "multipart/form-data; boundary=" + bound; hr.Method = "POST"; hr.KeepAlive = true; hr.Credentials = CredentialCache.DefaultCredentials; byte[] boundBytes = Encoding.ASCII.GetBytes("\r\n--" + bound + "\r\n"); string formDataTemplate = "\r\n--" + bound + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; //add fields + a boundary MemoryStream fieldData = new MemoryStream(); foreach (string key in fields.Keys) { byte[] formItemBytes = Encoding.UTF8.GetBytes( string.Format(formDataTemplate, key, fields[key])); fieldData.Write(formItemBytes, 0, formItemBytes.Length); } fieldData.Write(boundBytes, 0, boundBytes.Length); //calculate the total length we expect to send string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; long fileBytes = 0; byte[] headerBytes = Encoding.UTF8.GetBytes( String.Format(headerTemplate, "image", file)); FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); fileBytes += headerBytes.Length; fileBytes += fs.Length; fileBytes += boundBytes.Length; hr.ContentLength = fieldData.Length + fileBytes; Stream s = hr.GetRequestStream(); //write the fields to the request stream Debug.WriteLine("sending field data"); fieldData.WriteTo(s); //write the files to the request stream Debug.WriteLine("sending file data"); status.FileProcessMessage = "Sending File..."; UpdateStatus(this, status); s.Write(headerBytes, 0, headerBytes.Length); int bytesRead = 0; long bytesSoFar = 0; byte[] buffer = new byte[10240]; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { bytesSoFar += bytesRead; s.Write(buffer, 0, bytesRead); Debug.WriteLine(String.Format("sending file data {0:0.000}%", (bytesSoFar * 100.0f) / fs.Length)); status.FileProcessProgress = (bytesSoFar * 1.0f) / fs.Length; status.TotalProgress = TotalProgress + 1 / (Files.Count * 1.0f) * status.FileProcessProgress; UpdateStatus(this, status); } s.Write(boundBytes, 0, boundBytes.Length); fs.Close(); s.Close(); status.FileProcessMessage = "File Sent, Waiting for Response..."; UpdateStatus(this, status); HttpWebResponse response = hr.GetResponse() as HttpWebResponse; string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); Debug.Write(responseString); status.FileProcessMessage = "All finished, what's next?"; status.FileProcessProgress = 1; UpdateStatus(this, status); XmlDocument responseXml = new XmlDocument(); responseXml.LoadXml(responseString); if (responseXml["rsp"].Attributes["stat"].Value == "ok") { FileComplete(this, new ImgurUploadInfo { imgur_page = responseXml["rsp"]["imgur_page"].InnerText, original_image = responseXml["rsp"]["original_image"].InnerText, small_thumbnail = responseXml["rsp"]["small_thumbnail"].InnerText, large_thumbnail = responseXml["rsp"]["large_thumbnail"].InnerText, delete_page = responseXml["rsp"]["delete_page"].InnerText, delete_hash = responseXml["rsp"]["delete_hash"].InnerText, image_hash = responseXml["rsp"]["image_hash"].InnerText, file = file }); } else { throw new InvalidFileException { Message = "Imgur didn't like it" } }; hr = null; } catch (InvalidFileException ex) { InvalidFileFound(this, file, ex.Message); } } UpdateStatus(this, new ImgurUploaderStatus { FileBeingProcessed = "All Finished", FileProcessMessage = "", FileProcessProgress = 1, TotalMessage = "All Files Done", TotalProgress = 1 }); }
public void UploadFiles() { string accessToken = Settings.Default.AccessToken; ImgurUploaderStatus status = new ImgurUploaderStatus(); UploadResponse albumResponse = null; HttpWebRequest hr; try { if (Files.Count > 1 && Settings.Default.UploadAlbum) { // Create album status = new ImgurUploaderStatus { FileProcessMessage = "Creating album..." }; UpdateStatus(this, status); hr = WebRequest.Create(Settings.Default.AlbumURL) as HttpWebRequest; hr.Method = "POST"; hr.KeepAlive = true; hr.Credentials = CredentialCache.DefaultCredentials; string authHeader = accessToken != "" ? "Bearer " + accessToken : "Client-ID " + Settings.Default.ClientID; hr.Headers.Add("Authorization", authHeader); using (HttpWebResponse response = hr.GetResponse() as HttpWebResponse) { string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); albumResponse = JsonConvert.DeserializeObject <UploadResponse>(responseString); if (!albumResponse.success) { MessageBox.Show("Imgur didn't like the request.", "Error"); Application.Exit(); return; } } hr = null; } int currentFileNumber = 0; List <UploadResponse> responses = new List <UploadResponse>(); foreach (string file in Files) { currentFileNumber++; string TotalMessage = String.Format("Handling file {0}/{1}", currentFileNumber, Files.Count); double TotalProgress = (currentFileNumber - 1) / (Files.Count * 1.0f); status = new ImgurUploaderStatus { UploadProgress = 0, FilesMessage = TotalMessage, FilesProgress = TotalProgress, FileBeingProcessed = Path.GetFileName(file) }; status.FileProcessMessage = "Verifying existence"; UpdateStatus(this, status); if (!File.Exists(file)) { MessageBox.Show("File could not be found.", "Error"); } status.FileProcessMessage = "Verifying file integrity"; UpdateStatus(this, status); try { Image.FromFile(file); } catch (ArgumentException) { MessageBox.Show("File did not appear to be an image.", "Error"); } hr = WebRequest.Create(Settings.Default.UploadURL) as HttpWebRequest; string bound = "----------------------------" + DateTime.Now.Ticks.ToString("x"); hr.ContentType = "multipart/form-data; boundary=" + bound; hr.Method = "POST"; hr.KeepAlive = true; hr.Credentials = CredentialCache.DefaultCredentials; string authHeader = accessToken != "" ? "Bearer " + accessToken : "Client-ID " + Settings.Default.ClientID; hr.Headers.Add("Authorization", authHeader); byte[] boundBytes = Encoding.ASCII.GetBytes("\r\n--" + bound + "\r\n"); string headerTemplate = "Content-Disposition: form-data; name=\"image\"; filename=\"{0}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; byte[] headerBytes = Encoding.UTF8.GetBytes( String.Format(headerTemplate, Path.GetFileName(file))); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { // Calculate the total length we expect to send long contentLength = 0; contentLength += headerBytes.Length; contentLength += fs.Length; contentLength += boundBytes.Length * 2; byte[] albumData = null; if (albumResponse != null) { albumData = Encoding.UTF8.GetBytes( "Content-Disposition: form-data; name=\"album\"\r\n\r\n" + (accessToken != "" ? albumResponse.data.id : albumResponse.data.deletehash)); contentLength += albumData.Length + boundBytes.Length; } hr.ContentLength = contentLength; using (Stream s = hr.GetRequestStream()) { s.Write(boundBytes, 0, boundBytes.Length); if (albumData != null) { // Add album ID s.Write(albumData, 0, albumData.Length); s.Write(boundBytes, 0, boundBytes.Length); } // Write the file to the request stream status.FileProcessMessage = "Sending File..."; UpdateStatus(this, status); s.Write(headerBytes, 0, headerBytes.Length); int bytesRead = 0; long bytesSoFar = 0; byte[] buffer = new byte[10240]; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { bytesSoFar += bytesRead; s.Write(buffer, 0, bytesRead); Debug.WriteLine(String.Format("sending file data {0:0.000}%", (bytesSoFar * 100.0f) / fs.Length)); status.UploadProgress = (bytesSoFar * 1.0f) / fs.Length; status.FilesProgress = TotalProgress + 1 / (Files.Count * 1.0f) * status.UploadProgress; UpdateStatus(this, status); } s.Write(boundBytes, 0, boundBytes.Length); } } status.FileProcessMessage = "File sent, waiting for response..."; UpdateStatus(this, status); using (HttpWebResponse response = hr.GetResponse() as HttpWebResponse) { string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); UploadResponse imgur = JsonConvert.DeserializeObject <UploadResponse>(responseString); if (!imgur.success) { MessageBox.Show("Imgur didn't like the request.", "Error"); Application.Exit(); return; } else if (albumResponse == null) { responses.Add(imgur); } } status.FileProcessMessage = "All finished, what's next?"; status.UploadProgress = 1; UpdateStatus(this, status); hr = null; } if (albumResponse == null) { foreach (UploadResponse imgur in responses) { if (accessToken == "" && Settings.Default.DeleteWindow) { Process.Start("http://imgur.com/delete/" + imgur.data.deletehash); } Process.Start(imgur.data.link); } } else { // TODO: Figure out deletion for anonymous albums //if (accessToken == "") // Process.Start("http://imgur.com/{???}" + albumResponse.data.deletehash); Process.Start("http://imgur.com/a/" + albumResponse.data.id + "/layout/grid"); } Application.Exit(); } catch (WebException ex) { HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Forbidden) { AttemptReauthorize(status); } else { MessageBox.Show("Something went wrong during upload. Check your network connection.", "Error"); Application.Exit(); } } }