Esempio n. 1
0
        public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "")
        {
            if (User == null)
            {
                throw new Exception("User can not be null.");
            }
            var request = WebAgent.CreatePost(ComposeMessageUrl);

            WebAgent.WritePostBody(request.GetRequestStream(), new
            {
                api_type = "json",
                subject,
                text = body,
                to,
                uh      = User.Modhash,
                iden    = captchaId,
                captcha = captchaAnswer
            });
            var response = request.GetResponse();
            var result   = WebAgent.GetResponseString(response.GetResponseStream());
            var json     = JObject.Parse(result);

            ICaptchaSolver solver = CaptchaSolver; // Prevent race condition

            if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
            {
                captchaId = json["json"]["captcha"].ToString();
                CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));

                if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
                {
                    ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer);
                }
            }
        }
Esempio n. 2
0
        private Post Submit(SubmitData data)
        {
            if (Reddit.User == null)
            {
                throw new RedditException("No user logged in.");
            }
            var request = WebAgent.CreatePost(SubmitLinkUrl);

            WebAgent.WritePostBody(request.GetRequestStream(), data);

            var            json   = WebAgent.ExecuteRequest(request);
            ICaptchaSolver solver = Reddit.CaptchaSolver;

            if (json["errors"].Any() && json["errors"][0][0].ToString() == "BAD_CAPTCHA" &&
                solver != null)
            {
                data.Iden = json["captcha"].ToString();
                CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden));

                // We throw exception due to this method being expected to return a valid Post object, but we cannot
                // if we got a Captcha error.
                if (captchaResponse.Cancel)
                {
                    throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post");
                }

                data.Captcha = captchaResponse.Answer;
                return(Submit(data));
            }

            return(new Post(Reddit, json, WebAgent));
        }
Esempio n. 3
0
        private async Task <Post> SubmitAsync(SubmitData data, ICaptchaSolver solver = null)
        {
            var json = await WebAgent.Post(SubmitLinkUrl, data).ConfigureAwait(false);

            if (json["errors"].Any() && json["errors"][0][0].ToString() == "BAD_CAPTCHA")
            {
                if (solver == null)
                {
                    throw new CaptchaFailedException("Captcha required but not ICaptchaSolver provided");
                }

                data.Iden = json["captcha"].ToString();
                CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden));

                // We throw exception due to this method being expected to return a valid Post object, but we cannot
                // if we got a Captcha error.
                if (captchaResponse.Cancel)
                {
                    throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post");
                }

                data.Captcha = captchaResponse.Answer;
                return(await SubmitAsync(data, solver).ConfigureAwait(false));
            }
            else if (json["errors"].Any() && json["errors"][0][0].ToString() == "ALREADY_SUB")
            {
                throw new DuplicateLinkException($"Post failed when submitting.  The following link has already been submitted: {((LinkData)data).URL}");
            }
            else if (json["errors"].Any())
            {
                throw new Exception(json["errors"][0][0].ToString());
            }
            return(new Post(WebAgent, json["data"]));
        }
Esempio n. 4
0
        /// <summary>
        ///

        /// Compose a private message.
        /// </summary>
        /// <param name="subject">message subject</param>
        /// <param name="body">markdown body</param>
        /// <param name="to">target author or subreddit</param>
        /// <param name="fromSubReddit">The subreddit to send the message as (optional).</param>
        /// <param name="captchaId"></param>
        /// <param name="captchaAnswer"></param>
        /// <remarks>If <paramref name="fromSubReddit"/> is passed in then the message is sent from the subreddit. the sender must be a mod of the specified subreddit.</remarks>
        /// <exception cref="AuthenticationException">Thrown when a subreddit is passed in and the user is not a mod of that sub.</exception>
        public void ComposePrivateMessage(string subject, string body, string to, string fromSubReddit = "", string captchaId = "", string captchaAnswer = "")
        {
            if (User == null)
            {
                throw new Exception("User can not be null.");
            }

            if (!string.IsNullOrWhiteSpace(fromSubReddit))
            {
                var subReddit   = this.GetSubreddit(fromSubReddit);
                var modNameList = subReddit.Moderators.Select(b => b.Name).ToList();

                if (!modNameList.Contains(User.Name))
                {
                    throw new AuthenticationException(
                              string.Format(
                                  @"User {0} is not a moderator of subreddit {1}.",
                                  User.Name,
                                  subReddit.Name));
                }
            }

            var request = WebAgent.CreatePost(ComposeMessageUrl);

            WebAgent.WritePostBody(request.GetRequestStream(), new
            {
                api_type = "json",
                subject,
                text = body,
                to,
                from_sr = fromSubReddit,
                uh      = User.Modhash,
                iden    = captchaId,
                captcha = captchaAnswer
            });
            var response = request.GetResponse();
            var result   = WebAgent.GetResponseString(response.GetResponseStream());
            var json     = JObject.Parse(result);

            ICaptchaSolver solver = CaptchaSolver; // Prevent race condition

            if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
            {
                captchaId = json["json"]["captcha"].ToString();
                CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));

                if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
                {
                    ComposePrivateMessage(subject, body, to, fromSubReddit, captchaId, captchaResponse.Answer);
                }
            }
            else if (json["json"]["errors"].Any())
            {
                throw new Exception("Error when composing message. Error: " + json["json"]["errors"][0][0].ToString());
            }
        }
Esempio n. 5
0
        private async Task <Post> SubmitAsync(SubmitData data)
        {
            if (Reddit.User == null)
            {
                throw new RedditException("No user logged in.");
            }
            var request = WebAgent.CreatePost(SubmitLinkUrl);

            WebAgent.WritePostBody(await request.GetRequestStreamAsync(), data);

            var response = await request.GetResponseAsync();

            var result = WebAgent.GetResponseString(response.GetResponseStream());
            var json   = JToken.Parse(result);

            ICaptchaSolver solver = Reddit.CaptchaSolver;

            if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" &&
                solver != null)
            {
                data.Iden = json["json"]["captcha"].ToString();
                CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden));

                // We throw exception due to this method being expected to return a valid Post object, but we cannot
                // if we got a Captcha error.
                if (captchaResponse.Cancel)
                {
                    throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post");
                }

                data.Captcha = captchaResponse.Answer;
                return(await SubmitAsync(data));
            }
            else if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "ALREADY_SUB")
            {
                throw new DuplicateLinkException(string.Format("Post failed when submitting.  The following link has already been submitted: {0}", SubmitLinkUrl));
            }

            return(new Post().Init(Reddit, json["json"], WebAgent));
        }