Exemplo n.º 1
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));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Выполнить POST запрос.
 /// </summary>
 /// <param name="url">URL.</param>
 /// <param name="parameters">Параметры запроса.</param>
 /// <param name="webProxy">Хост.</param>
 /// <returns>Результат</returns>
 public static WebCallResult PostCall(string url, IEnumerable <KeyValuePair <string, string> > parameters, IWebProxy webProxy)
 {
     using (var call = new WebCall(url, new Cookies(), webProxy))
     {
         var request = call._request.PostAsync(url, new FormUrlEncodedContent(parameters)).Result;
         return(call.MakeRequest(request, new Uri(url), webProxy));
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Открытие окна авторизацииасинхронно
        /// </summary>
        /// <param name="appId"> id приложения </param>
        /// <param name="settings"> Настройки приложения </param>
        /// <returns> </returns>
        private async Task <WebCallResult> OpenAuthDialogAsync(ulong appId
                                                               , [NotNull]
                                                               Settings settings)
        {
            var url = CreateAuthorizeUrlFor(appId: appId, settings: settings, display: Display.Page);

            return(await WebCall.MakeCallAsync(url : url, webProxy : Proxy));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Получение json по url-адресу
        /// </summary>
        /// <param name="url">Адрес получения json</param>
        /// <returns>Строка в формате json</returns>
        public string GetJson(string url)
        {
            var separatorPosition = url.IndexOf('?');
            var methodUrl         = separatorPosition < 0 ? url : url.Substring(0, separatorPosition);
            var parameters        = separatorPosition < 0 ? string.Empty : url.Substring(separatorPosition + 1);

            return(WebCall.PostCall(methodUrl, parameters, _webProxy).Response);
        }
Exemplo n.º 5
0
Arquivo: WebCall.cs Projeto: vknet/vk
 /// <summary>
 /// Выполнить запрос.
 /// </summary>
 /// <param name="url">URL.</param>
 /// <param name="webProxy">Данные прокси сервера.</param>
 /// <returns>Результат</returns>
 public static WebCallResult MakeCall(string url, IWebProxy webProxy = null)
 {
     using (var call = new WebCall(url, new Cookies(), webProxy))
     {
         var response = call._request.GetAsync(url).Result;
         return call.MakeRequest(response, new Uri(url), webProxy);
     }
 }
Exemplo n.º 6
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(result: loginFormPostResult)
                           .WithField(name: "code")
                           .FilledWith(value: code.Invoke());

            return(await WebCall.PostAsync(form : codeForm, webProxy : Proxy));
        }
Exemplo n.º 7
0
 /// <summary>
 /// Выполнить запрос.
 /// </summary>
 /// <param name="url">URL.</param>
 /// <param name="webProxy">Данные прокси сервера.</param>
 /// <returns>Результат</returns>
 public static WebCallResult MakeCall(string url, IWebProxy webProxy = null)
 {
     using (var call = new WebCall(url, new Cookies(), webProxy))
     {
         var response = call._request.GetAsync(url).Result;
         return(call.MakeRequest(response, new Uri(url), webProxy));
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Заполнить форму двухфакторной авторизации
        /// </summary>
        /// <param name="code">Функция возвращающая код двухфакторной авторизации</param>
        /// <param name="loginFormPostResult">Ответ сервера vk</param>
        /// <returns>Ответ сервера vk</returns>
        private WebCallResult FilledTwoFactorForm(Func <string> code, WebCallResult loginFormPostResult)
        {
            var codeForm = WebForm.From(loginFormPostResult)
                           .WithField("code")
                           .FilledWith(code.Invoke());

            return(WebCall.Post(codeForm, Proxy));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Выполнить запрос асинхронно.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="webProxy">Данные прокси сервера.</param>
        /// <returns>Результат</returns>
        public static async Task <WebCallResult> MakeCallAsync(string url, IWebProxy webProxy = null)
        {
            using (var call = new WebCall(url, new Cookies(), webProxy))
            {
                var response = await call._request.GetAsync(url);

                return(await call.MakeRequestAsync(response, new Uri(url), webProxy));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Асинхронное получение json по url-адресу
        /// </summary>
        /// <param name="url">Адрес получения json</param>
        /// <returns>Строка в формате json</returns>
        public async Task <string> GetJsonAsync(string url)
        {
            // todo refactor this shit
            var    separatorPosition = url.IndexOf('?');
            string methodUrl         = separatorPosition < 0 ? url : url.Substring(0, separatorPosition);
            string parameters        = separatorPosition < 0 ? string.Empty : url.Substring(separatorPosition + 1);

            return(await WebCall.PostCallAsync(url, parameters));
        }
Exemplo n.º 11
0
Arquivo: WebCall.cs Projeto: GooG2e/vk
        /// <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))
            {
                SpecifyHeadersForFormRequest(form, call);

                var request = call._request.PostAsync(form.ActionUrl, new FormUrlEncodedContent(GetParameterList(form))).Result;
                return(call.MakeRequest(request, new Uri(form.ActionUrl), webProxy));
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Выполнить запрос асинхронно.
        /// </summary>
        /// <param name="url"> URL. </param>
        /// <param name="webProxy"> Данные прокси сервера. </param>
        /// <returns> Результат </returns>
        public static async Task <WebCallResult> MakeCallAsync(string url, IWebProxy webProxy = null)
        {
            using (var call = new WebCall(url: url, cookies: new Cookies(), webProxy: webProxy))
            {
                var response = await call._request.GetAsync(requestUri : url);

                return(await call.MakeRequestAsync(response : response, uri : new Uri(uriString: url), webProxy : webProxy)
                       .ConfigureAwait(false));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Выполнить POST запрос.
        /// </summary>
        /// <param name="url"> URL. </param>
        /// <param name="parameters"> Параметры запроса. </param>
        /// <param name="webProxy"> Хост. </param>
        /// <returns> Результат </returns>
        public static WebCallResult PostCall(string url, IEnumerable <KeyValuePair <string, string> > parameters, IWebProxy webProxy)
        {
            using (var call = new WebCall(url: url, cookies: new Cookies(), webProxy: webProxy))
            {
                var request = call._request.PostAsync(requestUri: url, content: new FormUrlEncodedContent(nameValueCollection: parameters))
                              .Result;

                return(call.MakeRequest(response: request, uri: new Uri(uriString: url), webProxy: webProxy));
            }
        }
Exemplo n.º 14
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));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Открытие окна авторизацииасинхронно
        /// </summary>
        /// <param name="appId"> id приложения </param>
        /// <param name="settings"> Настройки приложения </param>
        /// <returns> </returns>
        private Task <WebCallResult> OpenAuthDialogAsync(ulong appId
                                                         , [NotNull]
                                                         Settings settings)
        {
            var url = CreateAuthorizeUrlFor(appId: appId, settings: settings, display: Display.Page);

            var task = WebCall.MakeCallAsync(url: url, webProxy: Proxy);

            task.ConfigureAwait(false);
            return(task);
        }
Exemplo n.º 16
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));
            }
        }
Exemplo n.º 17
0
Arquivo: WebCall.cs Projeto: odugen/vk
        private WebCallResult RedirectTo(string url)
        {
            var call = new WebCall(url, Result.Cookies);

            var request = call.Request;
            request.Method = "GET";
            request.ContentType = "text/html";
            request.Referer = Request.Referer;

            return call.MakeRequest();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Открытие окна авторизацииасинхронно
        /// </summary>
        /// <param name="appId"> id приложения </param>
        /// <param name="settings"> Настройки приложения </param>
        /// <returns> </returns>
        private Task <WebCallResult> OpenAuthDialogAsync(ulong appId
                                                         , [NotNull]
                                                         Settings settings)
        {
            var url = CreateAuthorizeUrl(appId, settings.ToUInt64(), Display.Page, "123456");

            var task = WebCall.MakeCallAsync(url: url.ToString(), webProxy: Proxy);

            task.ConfigureAwait(false);
            return(task);
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Пере адресация.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        private WebCallResult RedirectTo(string url, IWebProxy webProxy = null)
        {
            var call = new WebCall(url, Result.Cookies, webProxy);

            var request = call.Request;

            request.Method      = "GET";
            request.ContentType = "text/html";
            request.Referer     = Request.Referer;

            return(call.MakeRequest(webProxy));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Пере адресация.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <returns>Результат</returns>
        private WebCallResult RedirectTo(string url, string host = null, int?port = null)
        {
            var call = new WebCall(url, Result.Cookies, host, port);

            var request = call.Request;

            request.Method      = "GET";
            request.ContentType = "text/html";
            request.Referer     = Request.Referer;

            return(call.MakeRequest(host, port));
        }
Exemplo n.º 23
0
Arquivo: WebCall.cs Projeto: GooG2e/vk
        private static void SpecifyHeadersForFormRequest(WebForm form, WebCall call)
        {
            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);
        }
Exemplo n.º 24
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(url: form.ActionUrl, cookies: form.Cookies, webProxy: webProxy, allowAutoRedirect: false))
            {
                SpecifyHeadersForFormRequest(form: form, call: call);

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

                return(await call.MakeRequestAsync(response : request, uri : new Uri(uriString: form.ActionUrl), webProxy : webProxy));
            }
        }
Exemplo n.º 25
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)
        {
            var authorizeUrl       = CreateAuthorizeUrlFor(appId, settings, Display.Wap);
            var authorizeUrlResult = WebCall.MakeCall(authorizeUrl, Proxy);

            if (authorizeUrlResult.ResponseUrl.ToString()
                .StartsWith("https://oauth.vk.com/blank.html#access_token=", StringComparison.Ordinal))
            {
                return(EndAuthorize(authorizeUrlResult, Proxy));
            }

            // Заполнить логин и пароль
            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, Proxy);

            // Заполнить код двухфакторной авторизации
            var isOAuthBlank = WebForm.IsOAuthBlank(loginFormPostResult);

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

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

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

            loginFormPostResult = WebCall.Post(codeForm, Proxy);


            return(EndAuthorize(loginFormPostResult, Proxy));
        }
Exemplo n.º 26
0
Arquivo: WebCall.cs Projeto: odugen/vk
        public static WebCallResult PostCall(string url, string parameters)
        {
            var call = new WebCall(url, new Cookies());
            call.Request.Method = "POST";
            call.Request.ContentType = "application/x-www-form-urlencoded";
            var data = Encoding.UTF8.GetBytes(parameters);
            call.Request.ContentLength = data.Length;

            using (var requestStream = call.Request.GetRequestStream())
                requestStream.Write(data, 0, data.Length);                

            return call.MakeRequest();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Асинхронная переадресация.
        /// </summary>
        /// <param name="url"> URL. </param>
        /// <param name="webProxy"> Хост. </param>
        /// <returns> Результат </returns>
        private async Task <WebCallResult> RedirectToAsync(string url, IWebProxy webProxy = null)
        {
            using (var call = new WebCall(url: url, cookies: _result.Cookies, webProxy: webProxy))
            {
                var headers = call._request.DefaultRequestHeaders;
                headers.Add(name: "Method", value: "GET");
                headers.Add(name: "ContentType", value: "text/html");

                var response = await call._request.GetAsync(requestUri : url);

                return(await call.MakeRequestAsync(response : response, uri : new Uri(uriString: url), webProxy : webProxy));
            }
        }
Exemplo n.º 28
0
Arquivo: WebCall.cs Projeto: GooG2e/vk
        /// <summary>
        /// Пере адресация.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        private WebCallResult RedirectTo(string url, IWebProxy webProxy = null)
        {
            using (var call = new WebCall(url, _result.Cookies, webProxy))
            {
                var headers = call._request.DefaultRequestHeaders;
                headers.Add("Method", "GET");
                headers.Add("ContentType", "text/html");

                var response = call._request.GetAsync(url).Result;

                return(call.MakeRequest(response, new Uri(url), webProxy));
            }
        }
Exemplo n.º 29
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));
        }
Exemplo n.º 30
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));
        }
Exemplo n.º 31
0
Arquivo: WebCall.cs Projeto: odugen/vk
        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();
        }
Exemplo n.º 32
0
        public static WebCallResult PostCall(string url, string parameters)
        {
            var call = new WebCall(url, new Cookies());

            call.Request.Method      = "POST";
            call.Request.ContentType = "application/x-www-form-urlencoded";
            var data = Encoding.UTF8.GetBytes(parameters);

            call.Request.ContentLength = data.Length;

            using (var requestStream = call.Request.GetRequestStream())
                requestStream.Write(data, 0, data.Length);

            return(call.MakeRequest());
        }
Exemplo n.º 33
0
        /// <summary>
        /// Post запрос из формы.
        /// </summary>
        /// <param name="form">Форма.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <returns>Результат</returns>
        public static WebCallResult Post(WebForm form, string host = null, int?port = null)
        {
            var call = new WebCall(form.ActionUrl, form.Cookies, host, port);

            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));
        }
Exemplo n.º 34
0
        private VkAuthorization EndAuthorize(WebCallResult result, string host = null, int?port = null, string proxyLogin = null, string proxyPassword = 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, host, port, proxyLogin, proxyPassword);

            return(VkAuthorization.From(authorizationFormPostResult.ResponseUrl));
        }
Exemplo n.º 35
0
Arquivo: WebCall.cs Projeto: kadkin/vk
        /// <summary>
        /// Выполнить запрос.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <param name="proxyLogin">Логин прокси-сервера</param>
        /// <param name="proxyPassword">Пароль прокси-сервера</param>
        /// <returns>Результат</returns>
        public static WebCallResult MakeCall(string url, string host = null, int? port = null, string proxyLogin = null, string proxyPassword = null)
        {
            var call = new WebCall(url, new Cookies(), host, port, proxyLogin, proxyPassword);

            return call.MakeRequest(host, port, proxyLogin, proxyPassword);
        }
Exemplo n.º 36
0
Arquivo: WebCall.cs Projeto: vknet/vk
        /// <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);
            }
        }
Exemplo n.º 37
0
Arquivo: WebCall.cs Projeto: kadkin/vk
        /// <summary>
        /// Выполнить POST запрос.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="parameters">Параметры запроса.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <param name="proxyLogin">Логин прокси-сервера</param>
        /// <param name="proxyPassword">Пароль прокси-сервера</param>
        /// <returns>Результат</returns>
        public static WebCallResult PostCall(string url, string parameters, string host = null, int? port = null, string proxyLogin = null, string proxyPassword = null)
        {
            var call = new WebCall(url, new Cookies(), host, port, proxyLogin, proxyPassword)
            {
                Request =
                {
                    Method = "POST",
                    ContentType = "application/x-www-form-urlencoded"
                }
            };

            var data = Encoding.UTF8.GetBytes(parameters);
            call.Request.ContentLength = data.Length;

            using (var requestStream = call.Request.GetRequestStream())
                requestStream.Write(data, 0, data.Length);

            return call.MakeRequest(host, port, proxyLogin, proxyPassword);
        }
Exemplo n.º 38
0
Arquivo: WebCall.cs Projeto: ProESM/vk
        public static WebCallResult MakeCall(string url, string host = null, int? port = null)
        {
            var call = new WebCall(url, new Cookies(), host, port);

            return call.MakeRequest(host, port);
        }
Exemplo n.º 39
0
        public static WebCallResult MakeCall(string url, VkApi vk)
        {
            var call = new WebCall(url, new Cookies(), vk);

            return call.MakeRequest(vk);
        }
Exemplo n.º 40
0
Arquivo: WebCall.cs Projeto: kadkin/vk
        /// <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);
        }
Exemplo n.º 41
0
Arquivo: WebCall.cs Projeto: vknet/vk
        /// <summary>
        /// Выполнить запрос.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        public static WebCallResult MakeCall(string url, IWebProxy webProxy = null)
        {
            var call = new WebCall(url, new Cookies(), webProxy);

            return call.MakeRequest(webProxy);
        }
Exemplo n.º 42
0
Arquivo: WebCall.cs Projeto: kadkin/vk
        /// <summary>
        /// Пере адресация.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="host">Хост.</param>
        /// <param name="port">Порт.</param>
        /// <param name="proxyLogin">Логин прокси-сервера</param>
        /// <param name="proxyPassword">Пароль прокси-сервера</param>
        /// <returns>Результат</returns>
        private WebCallResult RedirectTo(string url, string host = null, int? port = null, string proxyLogin = null, string proxyPassword = null)
        {
            var call = new WebCall(url, Result.Cookies, host, port, proxyLogin, proxyPassword);

            var request = call.Request;
            request.Method = "GET";
            request.ContentType = "text/html";
            request.Referer = Request.Referer;

            return call.MakeRequest(host, port, proxyLogin, proxyPassword);
        }
Exemplo n.º 43
0
Arquivo: WebCall.cs Projeto: vknet/vk
        /// <summary>
        /// Выполнить POST запрос.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="parameters">Параметры запроса.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        public static WebCallResult PostCall(string url, string parameters, IWebProxy webProxy)
        {
            using (var call = new WebCall(url, new Cookies(), webProxy))
            {
                var data = Encoding.UTF8.GetBytes(parameters);

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

                var paramList = new Dictionary<string, string>();
                foreach (var param in parameters.Split('&'))
                {
                    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(url, new FormUrlEncodedContent(paramList)).Result;
                return call.MakeRequest(request, new Uri(url), webProxy);
            }
        }
Exemplo n.º 44
0
Arquivo: WebCall.cs Projeto: vknet/vk
        /// <summary>
        /// Пере адресация.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="webProxy">Хост.</param>
        /// <returns>Результат</returns>
        private WebCallResult RedirectTo(string url, IWebProxy webProxy = null)
        {
            using (var call = new WebCall(url, _result.Cookies, webProxy))
            {
                var headers = call._request.DefaultRequestHeaders;
                headers.Add("Method", "GET");
                headers.Add("ContentType", "text/html");

                var response = call._request.GetAsync(url).Result;

                return call.MakeRequest(response, new Uri(url), webProxy);
            }
        }