Ejemplo n.º 1
0
        /// <summary>
        /// Connects imgur's upload/checkcaptcha endpoint to check if a captcha has to be solved before uploading an image, will return false if a captcha has to be solved or if any exceptions ocurred
        /// </summary>
        /// <param name="cookies">Cookies needed to complete the request</param>
        /// <param name="imgurData">Imgur album data to be collected from the endpoint if no captcha is required</param>
        /// <param name="errorMessage">Error message to be reported to the user if any exceptions were thrown</param>
        /// <returns></returns>
        private bool checkCaptcha(CookieContainer cookies, ref ImgurAlbumData imgurData, ref string errorMessage)
        {
            const string captchaUrl = "http://imgur.com/upload/checkcaptcha";
            var          data       = new ImgurAlbumData();

            try
            {
                var task = Task.Factory.StartNew(() =>
                {
                    var captchaRequest = WebRequest.Create(captchaUrl) as HttpWebRequest;

                    if (captchaRequest != null)
                    {
                        var captchaPostString                 = "total_uploads=1&create_album=true";
                        captchaRequest.ContentType            = "application/x-www-form-urlencoded; charset=UTF-8";
                        captchaRequest.Method                 = "POST";
                        captchaRequest.CookieContainer        = cookies;
                        captchaRequest.Accept                 = "*/*";
                        captchaRequest.AutomaticDecompression = DecompressionMethods.GZip |
                                                                DecompressionMethods.Deflate;
                        captchaRequest.UserAgent =
                            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
                        captchaRequest.Referer   = "http://imgur.com";
                        captchaRequest.KeepAlive = true;

                        var captchaCustomHeaders = captchaRequest.Headers;

                        captchaCustomHeaders.Add("Accept-Language", "en;q=0.8");
                        captchaCustomHeaders.Add("origin", "http://imgur.com");
                        captchaCustomHeaders.Add("x-requested-with", "XMLHttpRequest");

                        var captchaBytes = Encoding.ASCII.GetBytes(captchaPostString);

                        captchaRequest.ContentLength = captchaBytes.Length;

                        using (var os = captchaRequest.GetRequestStream())
                        {
                            os.Write(captchaBytes, 0, captchaBytes.Length);
                        }

                        var adS3Response = captchaRequest.GetResponse() as HttpWebResponse;


                        if (adS3Response != null && adS3Response.StatusCode == HttpStatusCode.OK)
                        {
                            using (var s = adS3Response.GetResponseStream())
                            {
                                if (s != null)
                                {
                                    using (
                                        // ReSharper disable once AssignNullToNotNullAttribute
                                        var sr = new StreamReader(s, Encoding.UTF8)
                                        )
                                    {
                                        data = JsonConvert.DeserializeObject <ImgurAlbumData>(sr.ReadToEnd());
                                    }
                                }
                            }
                        }
                    }
                });

                try
                {
                    task.Wait();
                }
                catch (AggregateException ae)
                {
                    if (ae.InnerException != null)
                    {
                        errorMessage = ae.InnerException.Message + Environment.NewLine + ae.StackTrace;
                    }
                    else
                    {
                        errorMessage = ae.Message + Environment.NewLine + ae.StackTrace;
                    }

                    ae.Handle(x => false);
                }
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    errorMessage = e.InnerException.Message + Environment.NewLine + e.StackTrace;
                }
                else
                {
                    errorMessage = e.Message + Environment.NewLine + e.StackTrace;
                }

                return(false);
            }

            if (data == null)
            {
                return(false);
            }

            imgurData = data;

            return(imgurData.Success);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Upload image to Imgur.
        /// </summary>
        /// <param name="isSocial">Sets if the string is for a social network post.</param>
        /// <returns>A Task object to be used in async methods</returns>
        private async Task UploadImage(bool isSocial)
        {
            //If string.IsNullOrEmpty(_imgurUrl) == true it means that user hasn't uploaded any images while current program's execution
            if (string.IsNullOrEmpty(_imgurUrl))
            {
                var cookies        = GetCookies();
                var imgurData      = new ImgurAlbumData();
                var imgurImageData = new ImgurImageData();
                var errorMessage   = string.Empty;

                ProgressLabel.Content         = "Checking captcha";
                ProgressLabel.Visibility      = Visibility.Visible;
                GeneralProgressBar.Visibility = Visibility.Visible;

                //Check if imgur asks for captcha first
                if (!checkCaptcha(cookies, ref imgurData, ref errorMessage))
                {
                    MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    //We have an OK and album data from imgur to upload images
                    if (imgurData.Success)
                    {
                        //Generate image
                        ProgressLabel.Content = "Generating image";
                        var file = new FileInfo(CreateImage(true));

                        if (File.Exists(file.FullName))
                        {
                            ProgressLabel.Content = "Uploading image";

                            //Upload image using as a multipart form
                            var task = Task.Factory.StartNew(() =>
                            {
                                using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                                {
                                    var data = new byte[fs.Length];
                                    fs.Read(data, 0, data.Length);

                                    var postParameters = new Dictionary <string, object>
                                    {
                                        { "new_album_id", imgurData.Data.NewAlbumId },
                                        {
                                            "file",
                                            new FormUpload.FileParameter(data, file.Name,
                                                                         MimeMapping.GetMimeMapping(file.FullName))
                                        }
                                    };

                                    using (var s = FormUpload.MultipartFormDataPost("http://imgur.com/upload",
                                                                                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                                                                                    postParameters, cookies)
                                                   .GetResponseStream())
                                    {
                                        if (s != null)
                                        {
                                            using (var sr = new StreamReader(s, Encoding.UTF8))
                                            {
                                                imgurImageData =
                                                    JsonConvert.DeserializeObject <ImgurImageData>(sr.ReadToEnd());
                                            }
                                        }
                                    }
                                }
                            });

                            //Wait for task completion
                            await task;

                            //If it isn't for a social site, show a textbox to allow the user to copy imgur's URL
                            if (!isSocial)
                            {
                                ImgurDataGrid.Visibility = Visibility.Visible;
                                ImgurUrlTxtBx.Text       = $"http://imgur.com/{imgurImageData.Data.Hash}";
                                _imgurUrl = ImgurUrlTxtBx.Text;
                            }
                            //Otherwise store it for future use (to avoid unneeded HTTP calls)
                            else
                            {
                                ImgurUrlTxtBx.Text = $"http://imgur.com/{imgurImageData.Data.Hash}";
                                _imgurUrl          = ImgurUrlTxtBx.Text;
                            }

                            File.Delete(file.FullName);
                        }
                        else
                        {
                            MessageBox.Show("File does not exist on the specified directory!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Try again later!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

                ProgressLabel.Content         = "";
                ProgressLabel.Visibility      = Visibility.Hidden;
                GeneralProgressBar.Visibility = Visibility.Hidden;
            }
            else
            {
                //Just show a textbox to allow the user to copy imgur's URL
                if (!isSocial)
                {
                    ImgurDataGrid.Visibility = Visibility.Visible;
                }
            }
        }