Ejemplo n.º 1
0
Archivo: VkApi.cs Proyecto: vknet/vk
        /// <summary>
        /// Инициализирует новый экземпляр класса <see cref="VkApi"/>.
        /// </summary>
        public VkApi(ICaptchaSolver captchaSolver = null)
        {
            Browser = new Browser();

            Users = new UsersCategory(this);
            Friends = new FriendsCategory(this);
            Status = new StatusCategory(this);
            Messages = new MessagesCategory(this);
            Groups = new GroupsCategory(this);
            Audio = new AudioCategory(this);
            Wall = new WallCategory(this);
            Board = new BoardCategory(this);
            Database = new DatabaseCategory(this);
            Utils = new UtilsCategory(this);
            Fave = new FaveCategory(this);
            Video = new VideoCategory(this);
            Account = new AccountCategory(this);
            Photo = new PhotoCategory(this);
            Docs = new DocsCategory(this);
            Likes = new LikesCategory(this);
            Pages = new PagesCategory(this);
            Gifts = new GiftsCategory(this);
            Apps = new AppsCategory(this);
            NewsFeed = new NewsFeedCategory(this);
            Stats = new StatsCategory(this);
            Auth = new AuthCategory(this);
            Markets = new MarketsCategory(this);
            Execute = new ExecuteCategory(this);

            RequestsPerSecond = 3;

            MaxCaptchaRecognitionCount = 5;
            _captchaSolver = captchaSolver;
        }
 public Reddit()
 {
     JsonSerializerSettings = new JsonSerializerSettings();
     JsonSerializerSettings.CheckAdditionalContent = false;
     JsonSerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
     _webAgent = new WebAgent();
     CaptchaSolver = new ConsoleCaptchaSolver();
 }
Ejemplo n.º 3
0
        public Reddit(bool useSsl)
        {
            DefaultWebAgent defaultAgent = new DefaultWebAgent();

            JsonSerializerSettings = new JsonSerializerSettings
            {
                CheckAdditionalContent = false,
                DefaultValueHandling   = DefaultValueHandling.Ignore
            };
            DefaultWebAgent.Protocol = useSsl ? "https" : "http";
            WebAgent      = defaultAgent;
            CaptchaSolver = new ConsoleCaptchaSolver();
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a Reddit instance with the given WebAgent implementation
 /// </summary>
 /// <param name="agent">Implementation of IWebAgent interface. Used to generate requests.</param>
 /// <param name="initUser">Whether to run InitOrUpdateUser, requires <paramref name="agent"/> to have credentials first.</param>
 public Reddit(IWebAgent agent, bool initUser)
 {
     WebAgent = agent;
     JsonSerializerSettings = new JsonSerializerSettings
     {
         CheckAdditionalContent = false,
         DefaultValueHandling   = DefaultValueHandling.Ignore
     };
     CaptchaSolver = new ConsoleCaptchaSolver();
     if (initUser)
     {
         InitOrUpdateUser();
     }
 }
Ejemplo n.º 5
0
        public static void AutoSync(string token, ICaptchaSolver captchaSolver)
        {
            var services = new ServiceCollection();

            services.AddAudioBypass();

            var api = new VkApi(services);

            api.CaptchaSolver = captchaSolver;
            api.Authorize(new ApiAuthParams()
            {
                AccessToken = token
            });

            StaticContent.VkApi = api;
            var userInfo = Users.Info.CurrentUserSync();

            StaticContent.UserId = userInfo.Id;
        }
Ejemplo n.º 6
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));
        }
Ejemplo n.º 7
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);

            request.InitWebReqProxy();
            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);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// GET request with bypassing Cloudflare JavaScript challenge.
        /// </summary>
        /// <param name="request">Http request</param>
        /// <param name="uri">Uri Address</param>
        /// <param name="log">Log action</param>
        /// <param name="cancellationToken">Cancel protection</param>
        /// <param name="captchaSolver">Captcha solving provider when Recaptcha required for pass</param>
        /// <exception cref="HttpException">When HTTP request failed</exception>
        /// <exception cref="CloudflareException">When unable to bypass Cloudflare</exception>
        /// <exception cref="CaptchaException">When unable to solve captcha using <see cref="ICaptchaSolver"/> provider.</exception>
        /// <returns>Returns original HttpResponse</returns>
        public static HttpResponse GetThroughCloudflare(this HttpRequest request, Uri uri,
                                                        DLog log = null,
                                                        CancellationToken cancellationToken = default(CancellationToken),
                                                        ICaptchaSolver captchaSolver        = null)
        {
            if (!request.UseCookies)
            {
                throw new CloudflareException($"{LogPrefix}Cookies must be enabled. Please set ${nameof(HttpRequest.UseCookies)} to true.");
            }

            // User-Agent is required
            if (string.IsNullOrEmpty(request.UserAgent))
            {
                request.UserAgent = Http.ChromeUserAgent();
            }

            log?.Invoke($"{LogPrefix}Checking availability at: {uri.AbsoluteUri} ...");

            for (int i = 0; i < MaxRetries; i++)
            {
                string retry = $". Retry {i + 1} / {MaxRetries}.";
                log?.Invoke($"{LogPrefix}Trying to bypass{retry}");

                var response = ManualGet(request, uri);
                if (!response.IsCloudflared())
                {
                    log?.Invoke($"{LogPrefix} OK. Not found at: {uri.AbsoluteUri}");
                    return(response);
                }

                // Remove expired clearance if present
                var cookies = request.Cookies.GetCookies(uri);
                foreach (Cookie cookie in cookies)
                {
                    if (cookie.Name != CfClearanceCookie)
                    {
                        continue;
                    }

                    cookie.Expired = true;
                    break;
                }

                if (cancellationToken != default(CancellationToken))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                // Bypass depend on challenge type: JS / Recaptcha
                //
                if (HasJsChallenge(response))
                {
                    SolveJsChallenge(ref response, request, uri, retry, log, cancellationToken);
                }

                if (HasRecaptchaChallenge(response))
                {
                    SolveRecaptchaChallenge(ref response, request, uri, retry, log, cancellationToken);
                }

                if (response.IsCloudflared())
                {
                    throw new CloudflareException(HasAccessDeniedError(response)
                        ? "Access denied. Try to use another IP address."
                        : "Unknown challenge type");
                }

                return(response);
            }

            throw new CloudflareException(MaxRetries, $"{LogPrefix}ERROR. Rate limit reached.");
        }
Ejemplo n.º 9
0
 /// <inheritdoc />
 public CaptchaHandler(ILogger <CaptchaHandler> logger, ICaptchaSolver captchaSolver)
 {
     _logger        = logger;
     _captchaSolver = captchaSolver;
 }
 public CaptchaService(IInputParser parser, ICaptchaSolver solver)
 {
     _parser = parser;
     _solver = solver;
 }
Ejemplo n.º 11
0
        public async static Task <string> User(string login, string password, Func <string> twoFactorAuth, ICaptchaSolver captchaSolver)
        {
            var services = new ServiceCollection();

            services.AddAudioBypass();
            var api = new VkApi(services);


            api.CaptchaSolver = captchaSolver;


            await api.AuthorizeAsync(new ApiAuthParams()
            {
                Login    = login,
                Password = password,
                TwoFactorAuthorization = twoFactorAuth
            });

            StaticContent.VkApi = api;
            var userInfo = await Users.Info.CurrentUser();

            StaticContent.UserId = userInfo.Id;
            return(api.Token);
        }
Ejemplo n.º 12
0
        public async Task <LoginResponse> LoginAsync(LoginDetails loginDetails, ITwoFactorCodeProvider twoFactorCodeProvider, LoginPriority loginPriority = LoginPriority.Low, ICaptchaSolver captchaSolver = null)
        {
            loginDetails.ThrowIfNullArgument();

            var loginRequest  = RequestFactories.LoginRequestFactory(loginDetails, twoFactorCodeProvider, loginPriority, captchaSolver);
            var loginResponse = await loginRequest.PerformRequestAsync().ConfigureAwait(false);

            RequestFactories.LoginResponse = loginResponse;
            RequestFactories.LoginDetails  = loginDetails;
            var pinEventsHandler = new PinEventsHandler(loginResponse, RequestFactories.HttpClient);

            //await pinEventsHandler.Initialize();
            RequestFactories.PinEventsHandler = pinEventsHandler;

            return(RequestFactories.LoginResponse);
        }