Exemple #1
0
        private void UpdateDatabase(BotAccount current)
        {
            current.RaisePropertyChanged("RuntimeTotal");
            current.RaisePropertyChanged("IsRunning");

            using (var db = new LiteDatabase(ACCOUNT_DB_NAME))
            {
                var accountdb = db.GetCollection <BotAccount>("accounts");
                accountdb.Update(current);
            }
        }
Exemple #2
0
        public void StoreAccount(BotAccount account)
        {
            if (GetAllAccounts().Any(a => a.Name == account.Name))
            {
                throw new Exception($"An account with the name '{account.Name}' already exists.");
            }

            var key = account.Name.Trim().Replace(" ", "");

            _storage.Store(account, CredentialsPath, key);
        }
Exemple #3
0
        public void UpdateDatabase(BotAccount current)
        {
            current.RaisePropertyChanged("Nickname");
            current.RaisePropertyChanged("RuntimeTotal");
            current.RaisePropertyChanged("IsRunning");
            current.RaisePropertyChanged("Level");
            current.RaisePropertyChanged("LastLogin");
            current.RaisePropertyChanged("LastLoginTimestamp");

            using (var db = new LiteDatabase(ACCOUNT_DB_NAME))
            {
                var accountdb = db.GetCollection <BotAccount>("accounts");
                accountdb.Update(current);
            }
        }
Exemple #4
0
        private void NewCon()
        {
            progressTurns.Value  = 0;
            linkViewGame.Enabled = false;

            if (_con != null)
            {
                _con.Close();
            }

            Log("Waiting for next game...");
            _account            = GetSelectedAccount();
            _con                = new Connection(textServer.Text, _account.Key);
            _con.MoveRequired  += OnGameStarted;
            _con.GameFinished  += OnGameFinished;
            _con.RequestFailed += OnRequestFailed;
        }
Exemple #5
0
        public BotAccount FindAvailableAccountForPokemonSwitch(string encounterId)
        {
            ISession session = TinyIoCContainer.Current.Resolve <ISession>();

            //set current
            BotAccount switchableAccount = GetSwitchableAccount(null, false); // Don't pause if no switchable account is available.

            if (switchableAccount != null)
            {
                var key = switchableAccount.Username + encounterId;
                if (session.Cache.GetCacheItem(key) == null)
                {
                    // Don't edit the running account until we actually switch.  Just return the pending account.
                    return(switchableAccount);
                }
            }

            return(null);
        }
Exemple #6
0
        public BotAccount GetSwitchableAccount(BotAccount bot = null, bool pauseIfNoSwitchableAccount = true)
        {
            ISession session        = TinyIoCContainer.Current.Resolve <ISession>();
            var      currentAccount = GetCurrentAccount();

            // If the bot to switch to is the same as the current bot then just return.
            if (bot == currentAccount)
            {
                return(bot);
            }

            if (bot != null)
            {
                return(bot);
            }

            using (var db = new LiteDatabase(ACCOUNT_DB_NAME))
            {
                var accountdb = db.GetCollection <BotAccount>("accounts");

                var runnableAccount = Accounts.OrderByDescending(p => p.RuntimeTotal).ThenBy(p => p.Id).LastOrDefault(p => p != currentAccount && p.ReleaseBlockTime < DateTime.Now);

                if (runnableAccount != null)
                {
                    return(runnableAccount);
                }

                if (!pauseIfNoSwitchableAccount)
                {
                    return(null);
                }

                // If we got here all accounts blocked so pause and retry.
                var pauseTime = session.LogicSettings.MultipleBotConfig.OnLimitPauseTimes;
#pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
                SendNotification(session, "All accounts are blocked.", $"None of your accounts are available to switch to, so bot will sleep for {pauseTime} minutes until next account is available to run.", true);
#pragma warning restore 4014

                Task.Delay(pauseTime * 60 * 1000).Wait();
                return(GetSwitchableAccount());
            }
        }
        private void SyncDatabase(List <AuthConfig> accounts)
        {
            using (var db = new LiteDatabase(ACCOUNT_DB_NAME))
            {
                var accountdb = db.GetCollection <BotAccount>("accounts");

                foreach (var item in accounts)
                {
                    var existing = this.Accounts.FirstOrDefault(x => x.GoogleUsername == item.GoogleUsername && x.PtcUsername == item.PtcUsername);

                    if (existing == null)
                    {
                        BotAccount newAcc = new BotAccount(item);
                        newAcc.Id = this.Accounts.Count == 0 ? 1 : this.Accounts.Max(x => x.Id) + 1;
                        accountdb.Insert(newAcc);
                        this.Accounts.Add(newAcc);
                    }
                }
            }
        }
Exemple #8
0
        public void SwitchAccounts(BotAccount newAccount)
        {
            if (newAccount == null)
            {
                return;
            }

            var runningAccount = GetCurrentAccount();

            if (runningAccount != null)
            {
                runningAccount.IsRunning = false;
                var now = DateTime.Now;
                runningAccount.RuntimeTotal        += (now - runningAccount.LastRuntimeUpdatedAt).TotalMinutes;
                runningAccount.LastRuntimeUpdatedAt = now;
                UpdateDatabase(runningAccount);
            }

            newAccount.IsRunning            = true;
            newAccount.LoggedTime           = DateTime.Now;
            newAccount.LastRuntimeUpdatedAt = newAccount.LoggedTime;
            UpdateDatabase(newAccount);

            // Update current auth config with new account.
            _globalSettings.Auth.CurrentAuthConfig = newAccount;

            string body = "";

            foreach (var item in Accounts)
            {
                body = body + $"{item.Username}     {item.GetRuntime()}\r\n";
            }

            var session = TinyIoCContainer.Current.Resolve <ISession>();

            Logging.Logger.Write($"Account changed to {newAccount.Username}.");

#pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
            SendNotification(session, $"Account changed to {newAccount.Username}", body);
#pragma warning restore 4014
        }
Exemple #9
0
 public void SwitchAccountTo(BotAccount account)
 {
     this.requestedAccount     = account;
     this.switchAccountRequest = true;
 }
Exemple #10
0
        public BotAccount GetSwitchableAccount(BotAccount bot = null)
        {
            var session        = TinyIoCContainer.Current.Resolve <ISession>();
            var currentAccount = this.Accounts.FirstOrDefault(
                x => (x.AuthType == AuthType.Ptc && x.PtcUsername == session.Settings.PtcUsername) ||
                (x.AuthType == AuthType.Google && x.GoogleUsername == session.Settings.GoogleUsername));


            var current = this.Accounts.FirstOrDefault(x => x.IsRunning);

            if (currentAccount != null)
            {
                currentAccount.RuntimeTotal += (DateTime.Now - currentAccount.LoggedTime).TotalMinutes;
                currentAccount.IsRunning     = false;

                if (session.LoggedTime != DateTime.MinValue)
                {
                    var playerStats = (session.Inventory.GetPlayerStats()).FirstOrDefault();
                    currentAccount.Level = playerStats.Level;
                }

                UpdateDatabase(currentAccount);
            }

            if (bot != null)
            {
                runningAccount = bot;
            }
            else
            {
                this.Accounts = this.Accounts.OrderByDescending(p => p.RuntimeTotal).ToList();
                var first = this.Accounts.First();
                if (first.RuntimeTotal >= 100000)
                {
                    first.RuntimeTotal = this.Accounts.Min(p => p.RuntimeTotal);
                }

                runningAccount = Accounts.LastOrDefault(p => p != currentAccount && p.ReleaseBlockTime < DateTime.Now);
                if (runningAccount != null)
                {
                    Logging.Logger.Write($"Switching to {runningAccount.GoogleUsername}{runningAccount.PtcUsername}...");

                    string body = "";
                    foreach (var item in this.Accounts)
                    {
                        int day  = (int)item.RuntimeTotal / 1440;
                        int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                        int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);
                        body = body + $"{item.GoogleUsername}{item.PtcUsername}     {item.GetRuntime()}\r\n";
                    }

#pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
                    SendNotification(session, $"Account changed to {runningAccount.GoogleUsername}{runningAccount.PtcUsername}", body);
#pragma warning restore 4014
                    //DumpAccountList();
                }
                else
                {
                    var pauseTime = session.LogicSettings.MultipleBotConfig.OnLimitPauseTimes;
#pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
                    SendNotification(session, "All accounts are being blocked", $"None of yours account available to switch, bot will sleep for {pauseTime} mins until next acount available to run", true);
#pragma warning restore 4014

                    Task.Delay(pauseTime * 60 * 1000).Wait();
                    return(GetSwitchableAccount());
                }
            }
            //overkill
            foreach (var item in this.Accounts)
            {
                item.IsRunning = false;
                UpdateDatabase(item);
            }
            runningAccount.IsRunning  = true;
            runningAccount.LoggedTime = DateTime.Now;

            UpdateDatabase(runningAccount);

            return(runningAccount);
        }
Exemple #11
0
 private void ReInitializeSession(ISession session, GlobalSettings globalSettings, BotAccount requestedAccount = null)
 {
     if (session.LogicSettings.MultipleBotConfig.StartFromDefaultLocation)
     {
         session.ReInitSessionWithNextBot(requestedAccount, globalSettings.LocationConfig.DefaultLatitude, globalSettings.LocationConfig.DefaultLongitude, session.Client.CurrentAltitude);
     }
     else
     {
         session.ReInitSessionWithNextBot(); //current location
     }
 }
Exemple #12
0
        private void HandleAuthorize(RequestMethod method, HttpRequestEventArgs args, Authentication auth)
        {
            //Register the action
            auth.RecordAction("auth:authorize");

            //Make sure its a valid method
            if (method != RequestMethod.Get)
            {
                args.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                args.Response.Close();
                return;
            }

            //Only users may use this endpoing
            if (!auth.IsUser)
            {
                args.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                args.Response.Close();
                return;
            }

            //Prepare the query params
            Query      query = new Query(args.Request);
            string     clientID, redirectURL, responseType, state;
            BotAccount botAccount = null;

            //Get the state
            state = query.GetString("state", "");

            //Validate the clientID
            if (!query.TryGetString("client_id", out clientID) || !API.ScanBotAccounts(clientID, out botAccount))
            {
                args.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                args.Response.WriteText("Invalid client_id. Please do not ever use this service again, it maybe trying to steal your credentials!");
                return;
            }

            //Validate the redirect
            if (!query.TryGetString("redirect_uri", out redirectURL) || !redirectURL.Equals(botAccount.AuthRedirect))
            {
                args.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                args.Response.WriteText("redirect_uri not supplied from auth application or does not match bot account.");
                return;
            }

            //Validate the response tpye
            if (!query.TryGetString("response_type", out responseType) || !(responseType == "code" || responseType == "token"))
            {
                args.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                args.Response.WriteText("response_type not supplied from auth application or is invalid.");
                return;
            }

            //If its a token lets return the token asap
            if (responseType == "token")
            {
                //Only admin bots can get tokens
                if (!botAccount.IsAdmin)
                {
                    args.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    args.Response.WriteText("response_type not supplied from auth application or is invalid.");
                    return;
                }

                //Generate some values
                auth.Token = GenerateToken(TimeSpan.FromHours(1), auth.Name);

                //Return with the token
                Redirect(args, $"{redirectURL}?access_token={auth.Token.Value.AccessToken}&expires_in={auth.Token.Value.Expiry.ToUnixEpoch()}&state={state}");
                return;
            }

            //Its a simple code one.
            if (responseType == "code")
            {
                //Generate some values;
                string code = GenerateRandomString(RNG, 16);
                auth.Token = GenerateToken(TimeSpan.FromHours(24), auth.Name);

                //Add to the list
                lock (_pendingTokenLock) _pendingTokens.Add(code, auth.Token.Value);

                //Redirect
                Redirect(args, $"{redirectURL}?code={code}&state={state}");
                return;
            }
        }
Exemple #13
0
 public void SwitchAccountTo(BotAccount account)
 {
     requestedAccount     = account;
     switchAccountRequest = true;
 }
Exemple #14
0
 public void SwitchAccountTo(BotAccount account)
 {
     this.requestedAccount = account;
 }