Exemple #1
0
        /// <summary>
        /// Post запрос из формы.
        /// </summary>
        /// <param name="form">Форма.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        public static WebCallResult Post(WebForm form, IWebProxy webProxy)
        {
            using (var call = new WebCall(form.ActionUrl, form.Cookies, webProxy, false))
            {
                var formRequest = form.GetRequest();

                var headers = call._request.DefaultRequestHeaders;
                headers.Add("Method", "POST");
                headers.Add("ContentType", "application/x-www-form-urlencoded");

                headers.Add("ContentLength", formRequest.Length.ToString());
                headers.Referrer = new Uri(form.OriginalUrl);

                var paramList = new Dictionary <string, string>();
                foreach (var param in form.GetRequestAsStringArray())
                {
                    if (paramList.ContainsKey(param))
                    {
                        continue;
                    }

                    var paramPair = param.Split('=');
                    var key       = paramPair[0] + "";
                    var value     = paramPair[1] + "";
                    paramList.Add(key, value);
                }

                var request = call._request.PostAsync(form.ActionUrl, new FormUrlEncodedContent(paramList)).Result;
                return(call.MakeRequest(request, new Uri(form.ActionUrl), webProxy));
            }
        }
Exemple #2
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <param name="captcha_sid">Идентификатор капчи</param>
        /// <param name="captcha_key">Текст капчи</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(int appId, string email, string password, Settings settings, long?captcha_sid = null, string captcha_key = null)
        {
            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl);

            var loginForm = WebForm.From(authorizeUrlResult).WithField("email").FilledWith(email).And().WithField("pass").FilledWith(password);

            if (captcha_sid.HasValue)
            {
                loginForm.WithField("captcha_sid").FilledWith(captcha_sid.Value.ToString()).FilledWith("captcha_key").FilledWith(captcha_key);
            }
            var loginFormPostResult = WebCall.Post(loginForm);

            var authorization = VkAuthorization.From(loginFormPostResult.ResponseUrl);

            if (authorization.CaptchaID.HasValue)
            {
                throw new VkNet.Exception.CaptchaNeededException(authorization.CaptchaID.Value, "http://api.vk.com/captcha.php?sid=" + authorization.CaptchaID.Value.ToString());
            }
            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            var authorizationForm           = WebForm.From(loginFormPostResult);
            var authorizationFormPostResult = WebCall.Post(authorizationForm);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #3
0
        /// <summary>
        /// Заполнить форму двухфакторной авторизации асинхронно
        /// </summary>
        /// <param name="code">Функция возвращающая код двухфакторной авторизации</param>
        /// <param name="loginFormPostResult">Ответ сервера vk</param>
        /// <returns>Ответ сервера vk</returns>
        private async Task <WebCallResult> FilledTwoFactorFormAsync(Func <string> code, WebCallResult loginFormPostResult)
        {
            var codeForm = WebForm.From(loginFormPostResult)
                           .WithField("code")
                           .FilledWith(code.Invoke());

            return(await WebCall.PostAsync(codeForm, Proxy));
        }
Exemple #4
0
        /// <summary>
        /// Заполнить форму двухфакторной авторизации асинхронно
        /// </summary>
        /// <param name="code"> Функция возвращающая код двухфакторной авторизации </param>
        /// <param name="loginFormPostResult"> Ответ сервера vk </param>
        /// <returns> Ответ сервера vk </returns>
        private Task <WebCallResult> FilledTwoFactorFormAsync(Func <string> code, WebCallResult loginFormPostResult)
        {
            var codeForm = WebForm.From(result: loginFormPostResult)
                           .WithField(name: "code")
                           .FilledWith(value: code.Invoke());

            var task = WebCall.PostAsync(form: codeForm, webProxy: Proxy);

            task.ConfigureAwait(false);
            return(task);
        }
Exemple #5
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <param name="code">Код двухфакторной авторизации</param>
        /// <param name="captchaSid">Идентификатор капчи</param>
        /// <param name="captchaKey">Текст капчи</param>
        /// <param name="host">Имя узла прокси-сервера.</param>
        /// <param name="port">Номер порта используемого Host.</param>
        /// <param name="proxyLogin">Логин для прокси-сервера.</param>
        /// <param name="proxyPassword">Пароль для прокси-сервера</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(ulong appId, string email, string password, Settings settings, Func <string> code = null, long?captchaSid = null, string captchaKey = null,
                                         string host = null, int?port = null, string proxyLogin = null, string proxyPassword = null)
        {
            _host          = string.IsNullOrWhiteSpace(host) ? null : host;
            _port          = port;
            _proxyLogin    = string.IsNullOrWhiteSpace(proxyLogin) ? null : proxyLogin;
            _proxyPassword = string.IsNullOrWhiteSpace(proxyPassword) ? null : proxyPassword;

            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl, host, port, proxyLogin, proxyPassword);

            // Заполнить логин и пароль
            var loginForm = WebForm.From(authorizeUrlResult)
                            .WithField("email")
                            .FilledWith(email)
                            .And()
                            .WithField("pass")
                            .FilledWith(password);

            if (captchaSid.HasValue)
            {
                loginForm.WithField("captcha_sid")
                .FilledWith(captchaSid.Value.ToString())
                .WithField("captcha_key")
                .FilledWith(captchaKey);
            }
            var loginFormPostResult = WebCall.Post(loginForm, host, port, proxyLogin, proxyPassword);

            // Заполнить код двухфакторной авторизации
            if (code != null)
            {
                var codeForm = WebForm.From(loginFormPostResult)
                               .WithField("code")
                               .FilledWith(code());
                loginFormPostResult = WebCall.Post(codeForm, host, port);
            }

            var authorization = VkAuthorization.From(loginFormPostResult.ResponseUrl);

            if (authorization.CaptchaId.HasValue)
            {
                throw new CaptchaNeededException(authorization.CaptchaId.Value, "http://api.vk.com/captcha.php?sid=" + authorization.CaptchaId.Value);
            }
            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            // Отправить данные
            var authorizationForm           = WebForm.From(loginFormPostResult);
            var authorizationFormPostResult = WebCall.Post(authorizationForm, host, port, proxyLogin, proxyPassword);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #6
0
        /// <summary>
        /// Post запрос из формы асинхронно.
        /// </summary>
        /// <param name="form">Форма.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        public static async Task <WebCallResult> PostAsync(WebForm form, IWebProxy webProxy)
        {
            using (var call = new WebCall(form.ActionUrl, form.Cookies, webProxy, false))
            {
                SpecifyHeadersForFormRequest(form, call);

                var request = await call._request.PostAsync(form.ActionUrl, new FormUrlEncodedContent(form.GetFormFields()));

                return(await call.MakeRequestAsync(request, new Uri(form.ActionUrl), webProxy));
            }
        }
Exemple #7
0
        private async Task <VkAuthorization> ValidateInternalAsync(string validateUrl, string phoneNumber)
        {
            var validateUrlResult = await WebCall.MakeCallAsync(url : validateUrl, webProxy : Proxy).ConfigureAwait(false);

            var codeForm = WebForm.From(result: validateUrlResult)
                           .WithField(name: "code")
                           .FilledWith(value: phoneNumber.Substring(startIndex: 1, length: 8));

            var codeFormPostResult = await WebCall.PostAsync(form : codeForm, webProxy : Proxy).ConfigureAwait(false);

            return(await EndAuthorizeAsync(result : codeFormPostResult, webProxy : Proxy).ConfigureAwait(false));
        }
Exemple #8
0
        public async Task <VkAuthorization> AuthorizeAsync(IApiAuthParams authParams)
        {
            _logger?.Debug(message: "Шаг 1. Открытие диалога авторизации");

            var authorizeUrlResult = await OpenAuthDialogAsync(appId : authParams.ApplicationId, settings : authParams.Settings)
                                     .ConfigureAwait(false);

            if (IsAuthSuccessfull(webCallResult: authorizeUrlResult))
            {
                return(await EndAuthorizeAsync(result : authorizeUrlResult, webProxy : Proxy).ConfigureAwait(false));
            }

            _logger?.Debug(message: "Шаг 2. Заполнение формы логина");

            var loginFormPostResult = await FilledLoginFormAsync(email : authParams.Login,
                                                                 password : authParams.Password,
                                                                 captchaSid : authParams.CaptchaSid,
                                                                 captchaKey : authParams.CaptchaKey,
                                                                 authorizeUrlResult : authorizeUrlResult)
                                      .ConfigureAwait(false);

            if (IsAuthSuccessfull(webCallResult: loginFormPostResult))
            {
                return(await EndAuthorizeAsync(result : loginFormPostResult, webProxy : Proxy).ConfigureAwait(false));
            }

            if (HasNotTwoFactor(code: authParams.TwoFactorAuthorization, loginFormPostResult: loginFormPostResult))
            {
                return(await EndAuthorizeAsync(result : loginFormPostResult, webProxy : Proxy).ConfigureAwait(false));
            }

            _logger?.Debug(message: "Шаг 2.5.1. Заполнить код двухфакторной авторизации");

            var twoFactorFormResult =
                await FilledTwoFactorFormAsync(code : authParams.TwoFactorAuthorization, loginFormPostResult : loginFormPostResult);

            if (IsAuthSuccessfull(webCallResult: twoFactorFormResult))
            {
                return(await EndAuthorizeAsync(result : twoFactorFormResult, webProxy : Proxy).ConfigureAwait(false));
            }

            _logger?.Debug(message: "Шаг 2.5.2 Капча");
            var captchaForm = WebForm.From(result: twoFactorFormResult);

            var captcha = await WebCall.PostAsync(form : captchaForm, webProxy : Proxy).ConfigureAwait(false);

            // todo: Нужно обработать капчу

            return(await EndAuthorizeAsync(result : captcha, webProxy : Proxy).ConfigureAwait(false));
        }
Exemple #9
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <param name="code">Код двухфакторной авторизации</param>
        /// <param name="captchaSid">Идентификатор капчи</param>
        /// <param name="captchaKey">Текст капчи</param>
        /// <param name="webProxy">Прокси-сервер.</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(ulong appId, string email, string password, Settings settings, Func <string> code = null, long?captchaSid = null, string captchaKey = null,
                                         IWebProxy webProxy = null)
        {
            _webProxy = webProxy;
            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl, _webProxy);

            // Заполнить логин и пароль
            var loginForm = WebForm.From(authorizeUrlResult)
                            .WithField("email")
                            .FilledWith(email)
                            .And()
                            .WithField("pass")
                            .FilledWith(password);

            if (captchaSid.HasValue)
            {
                loginForm.WithField("captcha_sid")
                .FilledWith(captchaSid.Value.ToString())
                .WithField("captcha_key")
                .FilledWith(captchaKey);
            }
            var loginFormPostResult = WebCall.Post(loginForm, _webProxy);

            // Заполнить код двухфакторной авторизации

            var codeForm = WebForm.From(loginFormPostResult)
                           .WithField("code")
                           .FilledWith(code?.Invoke());

            loginFormPostResult = WebCall.Post(codeForm, _webProxy);

            var authorization = VkAuthorization.From(loginFormPostResult.ResponseUrl);

            if (authorization.CaptchaId.HasValue)
            {
                throw new CaptchaNeededException(authorization.CaptchaId.Value, "http://api.vk.com/captcha.php?sid=" + authorization.CaptchaId.Value);
            }
            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            // Отправить данные
            var authorizationForm           = WebForm.From(loginFormPostResult);
            var authorizationFormPostResult = WebCall.Post(authorizationForm, _webProxy);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #10
0
        public static WebCallResult Post(WebForm form)
        {
            var call = new WebCall(form.ActionUrl, form.Cookies);

            var request = call.Request;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            var formRequest = form.GetRequest();
            request.ContentLength = formRequest.Length;
            request.GetRequestStream().Write(formRequest, 0, formRequest.Length);
            request.AllowAutoRedirect = false;
            request.Referer = form.OriginalUrl;

            return call.MakeRequest();
        }
Exemple #11
0
        private VkAuthorization EndAuthorize(WebCallResult result, IWebProxy webProxy = null)
        {
            var authorization = VkAuthorization.From(result.ResponseUrl);

            if (authorization.CaptchaId.HasValue)
            {
                throw new CaptchaNeededException(authorization.CaptchaId.Value, "http://api.vk.com/captcha.php?sid=" + authorization.CaptchaId.Value);
            }
            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            // Отправить данные
            var authorizationForm           = WebForm.From(result);
            var authorizationFormPostResult = WebCall.Post(authorizationForm, webProxy);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #12
0
        /// <summary>
        /// Закончить авторизацию
        /// </summary>
        /// <param name="result">Результат</param>
        /// <param name="webProxy">Настройки прокси</param>
        /// <returns></returns>
        /// <exception cref="CaptchaNeededException"></exception>
        private VkAuthorization EndAuthorize(WebCallResult result, IWebProxy webProxy = null)
        {
            var tokenUri      = GetTokenUri(result);
            var authorization = VkAuthorization.From(tokenUri.ToString());

            if (!authorization.IsAuthorizationRequired && !authorization.IsCaptchaNeeded)
            {
                _logger?.Debug("Завершение авторизации");
                return(authorization);
            }

            _logger?.Debug("Требуется подтверждение прав или ввод капчи");
            // Отправить данные
            var authorizationForm           = WebForm.From(result);
            var authorizationFormPostResult = WebCall.Post(authorizationForm, webProxy);

            tokenUri = GetTokenUri(authorizationFormPostResult);
            return(VkAuthorization.From(tokenUri.ToString()));
        }
Exemple #13
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <param name="captcha_sid">Идентификатор капчи</param>
        /// <param name="captcha_key">Текст капчи</param>
        /// <param name="host">Имя узла прокси-сервера.</param>
        /// <param name="port">Номер порта используемого Host.</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(ulong appId, string email, string password, Settings settings, Func <string> code = null, long?captcha_sid = null, string captcha_key = null,
                                         string host = null, int?port = null)
        {
            this.host = string.IsNullOrEmpty(host) ? null : host;
            this.port = port;

            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl, host, port);

            // fill email and password
            var loginForm = WebForm.From(authorizeUrlResult).WithField("email").FilledWith(email).And().WithField("pass").FilledWith(password);

            if (captcha_sid.HasValue)
            {
                loginForm.WithField("captcha_sid").FilledWith(captcha_sid.Value.ToString()).WithField("captcha_key").FilledWith(captcha_key);
            }
            var loginFormPostResult = WebCall.Post(loginForm, host, port);

            // fill code
            if (code != null)
            {
                var codeForm = WebForm.From(loginFormPostResult).WithField("code").FilledWith(code());
                loginFormPostResult = WebCall.Post(codeForm, host, port);
            }

            var authorization = VkAuthorization.From(loginFormPostResult.ResponseUrl);

            if (authorization.CaptchaID.HasValue)
            {
                throw new CaptchaNeededException(authorization.CaptchaID.Value, "http://api.vk.com/captcha.php?sid=" + authorization.CaptchaID.Value.ToString());
            }
            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            // press allow button
            var authorizationForm           = WebForm.From(loginFormPostResult);
            var authorizationFormPostResult = WebCall.Post(authorizationForm, host, port);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #14
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(int appId, string email, string password, Settings settings)
        {
            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl);

            var loginForm           = WebForm.From(authorizeUrlResult).WithField("email").FilledWith(email).And().WithField("pass").FilledWith(password);
            var loginFormPostResult = WebCall.Post(loginForm);

            var authorization = VkAuthorization.From(loginFormPostResult.ResponseUrl);

            if (!authorization.IsAuthorizationRequired)
            {
                return(authorization);
            }

            var authorizationForm           = WebForm.From(loginFormPostResult);
            var authorizationFormPostResult = WebCall.Post(authorizationForm);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemple #15
0
        /// <summary>
        /// Авторизация на сервере ВК
        /// </summary>
        /// <param name="appId">Идентификатор приложения</param>
        /// <param name="email">Логин - телефон или эл. почта</param>
        /// <param name="password">Пароль</param>
        /// <param name="settings">Уровень доступа приложения</param>
        /// <param name="code">Код двухфакторной авторизации</param>
        /// <param name="captchaSid">Идентификатор капчи</param>
        /// <param name="captchaKey">Текст капчи</param>
        /// <returns>Информация об авторизации приложения</returns>
        public VkAuthorization Authorize(ulong appId, string email, string password, Settings settings,
                                         Func <string> code = null, long?captchaSid = null, string captchaKey = null)
        {
            _logger?.Debug("Шаг 1. Открытие диалога авторизации");
            var authorizeUrlResult = OpenAuthDialog(appId, settings);

            if (IsAuthSuccessfull(authorizeUrlResult))
            {
                return(EndAuthorize(authorizeUrlResult, Proxy));
            }

            _logger?.Debug("Шаг 2. Заполнение формы логина");
            var loginFormPostResult = FilledLoginForm(email, password, captchaSid, captchaKey, authorizeUrlResult);

            if (IsAuthSuccessfull(loginFormPostResult))
            {
                return(EndAuthorize(loginFormPostResult, Proxy));
            }

            if (HasNotTwoFactor(code, loginFormPostResult))
            {
                return(EndAuthorize(loginFormPostResult, Proxy));
            }

            _logger?.Debug("Шаг 2.5.1. Заполнить код двухфакторной авторизации");
            var twoFactorFormResult = FilledTwoFactorForm(code, loginFormPostResult);

            if (IsAuthSuccessfull(twoFactorFormResult))
            {
                return(EndAuthorize(twoFactorFormResult, Proxy));
            }

            _logger?.Debug("Шаг 2.5.2 Капча");
            var captchaForm = WebForm.From(twoFactorFormResult);

            var captcha = WebCall.Post(captchaForm, Proxy);

            // todo: Нужно обработать капчу

            return(EndAuthorize(captcha, Proxy));
        }
Exemple #16
0
        /// <summary>
        /// Post запрос из формы.
        /// </summary>
        /// <param name="form">Форма.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        public static WebCallResult Post(WebForm form, IWebProxy webProxy)
        {
            using (var call = new WebCall(form.ActionUrl, form.Cookies, webProxy, false))
            {
                var formRequest = form.GetRequest();

                var headers = call._request.DefaultRequestHeaders;
                headers.Add("Method", "POST");
                headers.Add("ContentType", "application/x-www-form-urlencoded");

                headers.Add("ContentLength", formRequest.Length.ToString());
                headers.Referrer = new Uri(form.OriginalUrl);

                var paramList = new Dictionary<string, string>();
                foreach (var param in form.GetRequestAsStringArray())
                {
                    if (paramList.ContainsKey(param))
                    {
                        continue;
                    }

                    var paramPair = param.Split('=');
                    var key = paramPair[0] + "";
                    var value = paramPair[1] + "";
                    paramList.Add(key, value);
                }

                var request = call._request.PostAsync(form.ActionUrl, new FormUrlEncodedContent(paramList)).Result;
                return call.MakeRequest(request, new Uri(form.ActionUrl), webProxy);
            }
        }
Exemple #17
0
        /// <summary>
        /// Post запрос из формы.
        /// </summary>
        /// <param name="form">Форма.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <param name="proxyLogin">Логин прокси-сервера</param>
        /// <param name="proxyPassword">Пароль прокси-сервера</param>
        /// <returns>Результат</returns>
        public static WebCallResult Post(WebForm form, string host = null, int? port = null, string proxyLogin = null, string proxyPassword = null)
        {
            var call = new WebCall(form.ActionUrl, form.Cookies, host, port, proxyLogin, proxyPassword);

            var request = call.Request;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            var formRequest = form.GetRequest();
            request.ContentLength = formRequest.Length;
            request.Referer = form.OriginalUrl;
            request.GetRequestStream().Write(formRequest, 0, formRequest.Length);
            request.AllowAutoRedirect = false;

            return call.MakeRequest(host, port, proxyLogin, proxyPassword);
        }