Exemple #1
0
        private void SubmitButton_Click(object sender, EventArgs e)
        {
            authParams = new ApiAuthParams
            {
                ApplicationId = appId,
                Login         = LoginBox.Text,
                Password      = PassBox.Text,
                Settings      = VkNet.Enums.Filters.Settings.All
            };
            try
            {
                helper.apiInst.Authorize(authParams);
            }
            catch (VkApiAuthorizationException ex)
            {
                MessageBox.Show("Invalid login&password combination. Try again.");
                this.PassBox.Text = "";
            }

            catch (CaptchaNeededException ex)
            {
                // tested works fine


                using (CaptchaForm cf = new CaptchaForm(ex))
                {
                    cf.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something bad happend. Try again.");
            }

            if (helper.apiInst.IsAuthorized)
            {
                this.SubmitButton.Enabled = false;

                this.PassBox.Text       = "";
                this.LoginBox.Text      = "";
                this.LoginBox.BackColor = Color.Empty;

                this.LoginBox.Enabled = false;
                this.PassBox.Enabled  = false;
                this.IdTextBox.Text   = helper.GetCurrentUserID().ToString();
                this.Text             = String.Format(@"{0} {1}, /id{2}.",
                                                      helper.apiInst.Users.Get(helper.GetCurrentUserID()).FirstName,
                                                      helper.apiInst.Users.Get(helper.GetCurrentUserID()).LastName,
                                                      helper.GetCurrentUserID());
                helper.LoadUserAlbumsToList(this.AlbumsList, helper.GetCurrentUserID());
                if (this.AlbumsList.Items.Count > 0)
                {
                    DownloadButton.Enabled = true;
                }
            }
            else
            {
                this.Text = "VK AlbumSaver Tool";
            }
        }
Exemple #2
0
        private void loginBut_Click(object sender, EventArgs e)
        {
            try
            {
                ApiAuthParams a = new ApiAuthParams();
                a.Login         = login.Text;
                a.Password      = password.Text;
                a.Settings      = Settings.All;
                a.ApplicationId = 5691421;
                api.Authorize(a);
                User user;
                var  agp = new AudioGetParams(true);
                audio = api.Audio.Get(api.UserId.Value, out user);
                foreach (var item in audio)
                {
                    ListViewItem lv = new ListViewItem(item.Title);

                    lv.SubItems.Add(item.Artist.ToString());
                    listView1.Items.Add(lv);
                }
                login.Enabled    = false;
                password.Enabled = false;
                loginBut.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #3
0
        public void Authorize(string login, string password, Func <string, string> inputCaptcha = null)
        {
            var apiAuthParams = new ApiAuthParams
            {
                ApplicationId = APPLICATION_ID,
                Login         = login,
                Password      = password,
                Settings      = Settings.All
            };

            while (true)
            {
                try
                {
                    VkApi.Authorize(apiAuthParams);
                    break;
                }
                catch (CaptchaNeededException e)
                {
                    if (inputCaptcha == null)
                    {
                        throw new CaptchaInputException(new ArgumentNullException(nameof(inputCaptcha)));
                    }

                    var recognizedCaptcha = inputCaptcha(e.Img.AbsoluteUri);
                    apiAuthParams.CaptchaSid = e.Sid;
                    apiAuthParams.CaptchaKey = recognizedCaptcha;
                }
                catch (VkApiException e)
                {
                    throw new AuthorizationException(login, e);
                }
            }
        }
Exemple #4
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Settings      set           = Settings.All;
            ApiAuthParams apiAuthParams = new ApiAuthParams();

            if (ulong.TryParse(TextBox.Text, out ulong res))
            {
                apiAuthParams.ApplicationId = res;
            }

            apiAuthParams.Login    = TextBoxEmail.Text;
            apiAuthParams.Password = TextBoxPass.Text;
            apiAuthParams.Settings = set;
            try
            {
                vkApi.Authorize(apiAuthParams);

                Hide();
                MainPage mainPage = new MainPage();
                mainPage.Owner = this;
                mainPage.Show();
            }
            catch (Exception)
            {
                MessageBox.Show("Неверные данные", "Ошибка");
            }

            // Для выгрузки
            try
            {
            }
            catch (Exception)
            {}
        }
Exemple #5
0
        public KarmaVKbot(string accesToken)
        {
            //Data init
            chatIDs = new List <int>();
            //Connect to VK
            VKConnection = new VkApi();
            ApiAuthParams authParams = new ApiAuthParams();

            authParams.AccessToken = accesToken;
            VKConnection.Authorize(authParams);
            //Connection to DB
            using (SqlConnection db = new SqlConnection("User ID=KarmaVKUser;Password=123456;Initial Catalog=KarmaVKdb;Data Source=URANIUM\\SQLEXPRESS;"))
            {
                db.Open();
                string        query   = "SELECT DISTINCT chatId FROM Users";
                SqlCommand    command = new SqlCommand(query, db);
                SqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    chatIDs.Add(reader.GetInt32(0));
                }

                /*ParameterizedThreadStart param = new par;
                 *
                 * Thread poller = new Thread(new ParameterizedThreadStart(serverPolling, chatIDs.Last())); */
                serverPolling(82);
            }
        }
        public VkApi Authorize(Settings settings = null, ILogger <VkApi> logger = null)
        {
            if (settings == null)
            {
                settings = Settings.All;
            }

            if (_tokenStorage.IsAccessTokenExists())
            {
                try
                {
                    var api        = new VkApi(logger);
                    var authParams = new ApiAuthParams
                    {
                        AccessToken = _tokenStorage.ReadAccessToken(),
                        Settings    = settings
                    };
                    api.Authorize(authParams);
                    api.Database.GetCountriesById(1); // делаем какой-либо запрос, чтобы проверить access_token
                    return(api);
                }
                catch (AccessTokenInvalidException e)
                {
                    Console.WriteLine(e);
                }
                catch (UserAuthorizationFailException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Relogin();
            return(Authorize(settings, logger));
        }
        public bool TryAuthorize()
        {
            var authorizeParams = new ApiAuthParams
            {
                ApplicationId = 6858286,
                Login         = login,
                Password      = password,
                Settings      = Settings.All | Settings.Messages
            };

            try
            {
                vkApi.Authorize(authorizeParams);
                return(true);
            }
            catch (VkApiException e)
            {
                log.Error($"Message: {e.Message}\nStacktrace: {e.StackTrace}");
                return(false);
            }
            catch (Exception e)
            {
                log.Error($"Неизвестная ошибка при авторизации.\nMessage: {e.Message}\nStacktrace: {e.StackTrace}");
                return(false);
            }
        }
Exemple #8
0
        private async Task AuthAsync(ApiAuthParams authParams)
        {
            try
            {
                Api = new VkApi()
                {
                    CaptchaSolver = new CaptchaSolver(userInputService)
                };
                Api.SetLanguage(VkNet.Enums.Language.Ru);

                await Api.AuthorizeAsync(authParams);

                var user = await GetCurrentUserAsync();

                Group group = null;
                if (!string.IsNullOrEmpty(groupIdOrScreenName))
                {
                    group = await GetCurrentGroupAsync(groupIdOrScreenName);

                    GroupId         = group.Id;
                    GroupScreenName = group?.ScreenName;
                }

                RiseAuthStateChanged(CreateUserAuthorizeEventArgs(true, Token, user, group));
            }
            catch (UserAuthorizationFailException)
            {
                RiseAuthStateChanged(CreateUserAuthorizeEventArgs(false, ""));
            }
            catch (NullReferenceException)
            {
                throw new Exception("Ошибка авторизации. Авторизуйтесь через браузер");
            }
        }
Exemple #9
0
 public VkParser()
 {
     vkapi   = new VkApi();
     @params = new GroupsGetMembersParams {
         Fields = UsersFields.All
     };
     apiparams = new ApiAuthParams();
     vkapi.SetLanguage(VkNet.Enums.Language.Ua);
 }
Exemple #10
0
 public void InstallVkParams(ulong _applicationId, string _login, string _password, Settings _settings)
 {
     parametrs = new ApiAuthParams
     {
         ApplicationId = _applicationId,
         Login         = _login,
         Password      = _password,
         Settings      = _settings
     };
 }
Exemple #11
0
        /// <summary>
        /// Constructor, which uses
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="key"></param>
        /// <param name="callback"></param>
        public VkBot(ulong appId, string token, IncomingMessageCallback callback, int exclusivePeerId = 0)
        {
            ApiAuthParams apiParams = new ApiAuthParams
            {
                ApplicationId = appId,

                Settings = Settings.Messages
            };

            Initialize(token, appId, callback, exclusivePeerId);
        }
Exemple #12
0
 public VkProvider()
 {
     this.appId    = 5196540;
     this.userName = "******";
     this.password = "******";
     var authParams = new ApiAuthParams()
     {
         ApplicationId = this.appId, Password = this.password, Login = this.userName
     };
     var token = Resources.AppSettings.AUTH_TOKEN;
 }
Exemple #13
0
        static void Auth()
        {
            ApiAuthParams apiAuthParams = new ApiAuthParams();

            apiAuthParams.ApplicationId = 6493465;
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"/tss.txt";

            apiAuthParams.AccessToken = (File.ReadAllText(path)).ToString();

            vkApi.Authorize(apiAuthParams);
        }
Exemple #14
0
        /// <summary>
        /// Authorize the application.
        /// </summary>
        private static bool _Authorize()
        {
            var authParams = new ApiAuthParams
            {
                ApplicationId          = _applicationId,
                Settings               = Settings.All,
                TwoFactorSupported     = true,
                TwoFactorAuthorization = _GetCode
            };

            if (string.IsNullOrEmpty(_token))
            {
                if (string.IsNullOrEmpty(_username))
                {
                    Console.Write("Enter user name: ");
                    _username = Console.ReadLine();
                }

                if (string.IsNullOrEmpty(_password))
                {
                    Console.Write("Enter password: "******"Token: {_token}");
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    return(false);
                }
            }
            else
            {
                authParams.AccessToken = _token;
                try
                {
                    _api.Authorize(authParams);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    return(false);
                }
            }

            return(true);
        }
Exemple #15
0
        /// <summary>
        /// Simple constructor for a new bot.
        /// </summary>
        /// <param name="appId">application id provided by vk.com</param>
        /// <param name="email">vk.com login</param>
        /// <param name="pass">vk.com password</param>
        /// <param name="callback">Delegate. Executed every time bot recieves incoming message</param>
        public VkBot(ulong appId, string email, string pass, IncomingMessageCallback callback, int exclusivePeerId = 0)
        {
            ApiAuthParams apiParams = new ApiAuthParams
            {
                ApplicationId = appId,
                Login         = email,
                Password      = pass,
                Settings      = Settings.Messages
            };

            Initialize(apiParams, appId, callback, exclusivePeerId);
        }
Exemple #16
0
        public static ApiAuthParams GetCredentials()
        {
            var hData = HierarchicalObject.FromFile(StringConstants.CredentialsFileName);
            var creds = new ApiAuthParams
            {
                ApplicationId = (ulong)hData["ApplicationId"],
                Login         = hData["Login"],
                Password      = hData["Password"],
                Settings      = Settings.All | Settings.Offline
            };

            return(creds);
        }
Exemple #17
0
        private ApiAuthParams GetAuthParams(Account acc)
        {
            var p = new ApiAuthParams()
            {
                ApplicationId =
                    Convert.ToUInt64(acc.ApplicationId),
                Login    = acc.Login,
                Password = acc.Password,
                Settings = Settings.Wall,
            };

            return(p);
        }
Exemple #18
0
    private static ApiAuthParams ReadParams()
    {
        var userParams = new ApiAuthParams()
        {
            ApplicationId = ТВОЙИД,
            Settings      = Settings.All
        };

        Console.Write("E-mail или номер телефона: ");
        userParams.Login = Console.ReadLine();
        Console.Write("Пароль: ");
        userParams.Login = Console.ReadLine();
        return(userParams);
    }
        /// <summary>Метод авторизации. </summary>
        /// <param name="login">Логин</param>
        /// <param name="password">Пароль</param>
        /// <returns>При успешной авторизации возращает <see langword="true"/></returns>
        public Task <bool> AuthorizeTask(string login, string password)
        => Task.Factory.StartNew(() =>
        {
            ApiAuthParams apiAuthParams = new ApiAuthParams
            {
                ApplicationId          = this.ApplicationId,
                Login                  = login,
                Password               = password,
                Settings               = Settings.All,
                TwoFactorAuthorization = InputSmsCode
            };
            VkApi.Authorize(apiAuthParams);

            return(VkApi.IsAuthorized);
        });
Exemple #20
0
        /// <summary>
        /// Конструктор с настройками
        /// </summary>
        /// <param name="options"></param>
        /// <param name="db"></param>
        public VK(Options options, CommentDatabase db)
        {
            this.options = options;
            this.db      = db;
            api          = new VkApi();
            db.LoadAdvertKw(options.AdvertKeywordsFileName);
            prefilter           = new CommentPrefilter(db);
            options.AccessToken = GetToken(options.ApplicationID);
            ApiAuthParams par = new ApiAuthParams
            {
                AccessToken = options.AccessToken
            };

            api.Authorize(par);   //Подключение
        }
Exemple #21
0
        void VkAuthorization(VkPlayerPosition pp = null, bool SourceSelected = true)
        {
            ApiAuthParams Ap = null;

            if (DM.Get_VkUserAuth(out var UserAuth))
            {
                Ap      = UserAuth.ApiAuthParams;
                VkLogin = UserAuth.Login;
                VkPass  = UserAuth.Pass;

                if (DM.Get_VkToken(out var token))
                {
                    try
                    {
                        _vk.Authorize(new ApiAuthParams {
                            AccessToken = token, UserId = Ap.UserId
                        });
                        OnVkAuthorized(pp, SourceSelected);
                        return;
                    }
                    catch
                    {
                        if (Ap != null)
                        {
                            _vk.Authorize(Ap);
                            DM.VkToken = _vk.Token;
                            OnVkAuthorized(pp, SourceSelected);
                            return;
                        }
                    }
                }
                else
                {
                    if (Ap != null)
                    {
                        _vk.Authorize(Ap);
                        DM.VkToken = _vk.Token;
                        OnVkAuthorized(pp, SourceSelected);
                        return;
                    }
                }
            }
            if (SourceSelected)
            {
                Awaited();
            }
        }
Exemple #22
0
        /// <summary>
        /// Constructor. Inputs vk.com account credentials from console
        /// </summary>
        /// <param name="appId">application id provided by vk.com</param>
        /// <param name="callback">Delegate. Executed every time bot recieves incoming message</param>
        public VkBot(ulong appId, IncomingMessageCallback callback, int exclusivePeerId = 0)
        {
            Console.WriteLine("Logging in to vk.com");

            Console.Write("E-mail: ");
            string email = Console.ReadLine();

            string pass = "";

            #region inputing password
            Console.Write("Enter your password: "******"*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                    {
                        pass = pass.Substring(0, (pass.Length - 1));
                        Console.Write("\b \b");
                    }
                }
            }
            // Stops Receving Keys Once Enter is Pressed
            while (key.Key != ConsoleKey.Enter);
            Console.WriteLine();
            #endregion

            ApiAuthParams apiParams = new ApiAuthParams
            {
                ApplicationId = appId,
                Login         = email,
                Password      = pass,
                Settings      = Settings.Messages
            };

            Initialize(apiParams, appId, callback, exclusivePeerId);
        }
Exemple #23
0
        private void Auth_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (AccountBox.Text.Trim() != "" && PasswordBox.Password.Trim() != "")
                {
                    var apia = new ApiAuthParams();
                    apia.Login         = AccountBox.Text;
                    apia.Password      = PasswordBox.Password;
                    apia.ApplicationId = 4551110;
                    apia.Settings      = scope;

                    if (chkRemember.IsChecked == true)              //Если сохранять пароль, то заходим
                    {
                        if (dicSU.ContainsKey(apia.Login))          //проверяем, есть ли такая пара логин/пароль
                        {
                            if (dicSU[apia.Login] != apia.Password) //если есть, и текущий введеный пароль не совпадает с сохранненым, cпрашиваем сохранить ли введенный сейчас.
                            {
                                if (MessageBox.Show("Пароль не совпадает с текущим, сохранить новый пароль?", "Ошибка", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                {
                                    dicSU[apia.Login] = apia.Password;
                                }
                            }
                        }
                        else //иначе просто заносим новую пару
                        {
                            dicSU.Add(apia.Login, apia.Password);
                        }

                        Save(dicSU);
                        Get = dicSU;
                    }

                    App.AuthPublic.Authorize(apia);
                    DialogResult = true;
                }
                else
                {
                    MessageBox.Show("Заполнены не все поля!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private static void Run()
        {
            ApiConfiguration apiConfiguration = GetApiConfiguration();

            var apiAuthParams = new ApiAuthParams
            {
                ApplicationId = apiConfiguration.ApplicationId,
                Login         = apiConfiguration.Login,
                Password      = apiConfiguration.Password,
                Settings      = Settings.All
            };

            using (var api = new VkApi())
            {
                api.Authorize(apiAuthParams);
                EnsureFirstCommentCreationForNewPost(api, apiConfiguration);
            }
        }
Exemple #25
0
        public void ConfigureServices(IServiceCollection services)
        {
            // var connectionString = Configuration.GetConnectionString("MySql" + Env.EnvironmentName);
            // services.AddSingleton<DataBaseContext>(new MySqlDataBase(connectionString));

            var api        = new VkApi();
            var authParams = new ApiAuthParams {
                AccessToken = Configuration["AccessToken"]
            };

            api.Authorize(authParams);
            services.AddSingleton <IVkApi>(api);

            services.AddSingleton <VkEventHandler>();
            services.AddSingleton <SessionsContainer>();

            services.AddControllers().AddNewtonsoftJson();
        }
        public VkUserInfoSource(VkAnalyzerSettings settings, IServiceCollection services = null)
        {
            _vkApi = new VkApi(services);
            var param = new ApiAuthParams
            {
                ApplicationId = ulong.Parse(settings.AppId),
                Login         = settings.VkUserLogin,
                Password      = settings.VkUserPassword,
                Settings      = Settings.Status,
            };

            _vkApi.OnTokenExpires += sender =>
            {
                sender.RefreshToken();
                Debug.WriteLine("Refresh token");
            };

            _vkApi.Authorize(param);
        }
Exemple #27
0
        private void authorizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AuthorizationForm AuthForm = new AuthorizationForm();

            AuthForm.ShowDialog();
            if (AuthForm.ShowDialog() == DialogResult.OK)
            {
                Email = AuthForm.Email;
                Pass  = AuthForm.Pass;
            }

            VkNet.Enums.Filters.Settings scope = VkNet.Enums.Filters.Settings.All;      // Приложение имеет доступ к друзьям
            var vkApi = new VkApi();

            var user = new ApiAuthParams()
            {
                ApplicationId = (ulong)appID,
                Login         = Email,
                Password      = Pass,
                Settings      = scope
            };

            try
            {
                vkApi.Authorize(user);
                tsStatusInfo.Text = "Connected";
                InitializeMenu(true);
            }
            catch (CaptchaNeededException ex)
            {
                CaptchaForm captchForm = new CaptchaForm(ex.Img.AbsoluteUri);
                captchForm.Text = "Capthca error";
                if (DialogResult.OK == captchForm.ShowDialog())
                {
                    user.CaptchaKey = captchForm.UserInfo.CaptchaKey;
                    user.CaptchaSid = ex.Sid;
                    vkApi.Authorize(user);

                    tsStatusInfo.Text = "Подключено...";
                    //InitializeMenu(true);
                }
            }
        }
Exemple #28
0
        static User Authorize(string token)
        {
            try
            {
                var authParams = new ApiAuthParams()
                {
                    AccessToken = token
                };

                Api.Authorize(authParams);
            }
            catch (VkAuthorizationException e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }

            return(Api.Users.Get(Array.Empty <long>()).First());
        }
Exemple #29
0
 private VkApiManager(VkApi api, ulong appId, string login, string password)
 {
     try
     {
         _api = api;
         var apiAuthParams = new ApiAuthParams
         {
             ApplicationId = appId,
             Login         = login,
             Password      = password,
             Settings      = Settings.All
         };
         _api.Authorize(apiAuthParams);
     }
     catch
     {
         Debug.Print("Error VkApi");
     }
 }
Exemple #30
0
        public void Authorization()
        {
            AuthControl authControl = new AuthControl(applicationContract);

            applicationContract.OpenSpecialWindow(authControl);

            if (authControl.IsCanceled)
            {
                return;
            }

            VkApi vk_api = new VkApi();

            ApiAuthParams authParams = new ApiAuthParams();

            authParams.ApplicationId = Convert.ToUInt64(Properties.Resources.client_id);
            authParams.Login         = authControl.GetLogin();
            authParams.Password      = authControl.GetPassword();
            authParams.Settings      = Settings.Friends | Settings.Photos | Settings.Wall | Settings.Messages | Settings.Groups;

            try
            {
                vk_api.Authorize(authParams);
            }
            catch (VkApiException ex)
            {
                applicationContract.OpenSpecialWindow("Vk Auth Error.");
                return;
            }

            for (int i = 0; i < users_count; i++)
            {
                if (users_api[i].UserId.Equals(vk_api.UserId))
                {
                    applicationContract.OpenSpecialWindow("You already authorized.");
                    return;
                }
            }

            users_api.Add(vk_api);
            users_accounts.Add(vk_api.Account.GetProfileInfo());
            users_count++;
        }