예제 #1
0
        public async Task <MethodResult <bool> > DoLogin(ISettings settings)
        {
            SetSettings(settings);
            Configuration.Hasher            = new PokeHashHasher(Settings.AuthAPIKey);
            Configuration.HasherUrl         = new Uri(Settings.HashHost.ToString());
            Configuration.IgnoreHashVersion = true;

            ILoginProvider loginProvider;

            switch (Settings.AuthType)
            {
            case AuthType.Google:
                loginProvider = new GoogleLoginProvider(Settings.GoogleUsername, Settings.GooglePassword);
                break;

            case AuthType.Ptc:
                loginProvider = new PtcLoginProvider(Settings.PtcUsername, Settings.PtcPassword);
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            ClientSession = await GetSession(loginProvider, Settings.DefaultLatitude, Settings.DefaultLongitude, true);

            SaveAccessToken(ClientSession.AccessToken);

            ClientSession.AccessTokenUpdated += SessionOnAccessTokenUpdated;
            ClientSession.InventoryUpdate    += InventoryOnUpdate;
            ClientSession.MapUpdate          += MapOnUpdate;
            ClientSession.CaptchaReceived    += SessionOnCaptchaReceived;

            // Send initial requests and start HeartbeatDispatcher.
            // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
            string msgStr = null;

            if (!await ClientSession.StartupAsync())
            {
                msgStr   = "Session couldn't start up.";
                LoggedIn = false;
            }
            else
            {
                LoggedIn = true;
                msgStr   = "Successfully logged into server.";
            }
            return(new MethodResult <bool>()
            {
                Success = LoggedIn,
                Message = msgStr
            });
        }
예제 #2
0
        public static Session SignIn(PoGoAccount account, Location defaultLocation)
        {
            if ((account.PTCUsername.IsNullOrEmpty() || account.PTCPassword.IsNullOrEmpty()) && (account.GAPassword.IsNullOrEmpty() || account.GAUsername.IsNullOrEmpty()))
            {
                PokewatchLogger.Log("[-]Username and password must be supplied for either PTC or Google.", GetAccountName(account));
                return(null);
            }

            if (!account.PTCUsername.IsNullOrEmpty() && !account.PTCPassword.IsNullOrEmpty())
            {
                try
                {
                    PokewatchLogger.Log("[!]Attempting to sign in to PokemonGo as " + account.PTCUsername + " using PTC.", GetAccountName(account));
                    var loginProvider = new PtcLoginProvider(account.PTCUsername, account.PTCPassword);
                    var pogoSession   = Login.GetSession(loginProvider, defaultLocation.Latitude, defaultLocation.Longitude).Result;
                    PokewatchLogger.Log("[+]Sucessfully logged in to PokemonGo using PTC.", GetAccountName(account));
                    return(pogoSession);
                }
                catch
                {
                    PokewatchLogger.Log("[-]Unable to log in using PTC.", GetAccountName(account));
                }
            }
            if (!account.GAUsername.IsNullOrEmpty() && !account.GAPassword.IsNullOrEmpty())
            {
                PokewatchLogger.Log("[-]Google login is disabled for a bit, sorry! - AeonLucid", GetAccountName(account));
                //				try
                //				{
                //					PokewatchLogger.Log("[!]Attempting to sign in to PokemonGo as " + account.GAUsername + " using Google.", GetAccountName(account));
                //					var pogoSession = Login.GetSession(account.GAUsername, account.GAPassword, LoginProvider.GoogleAuth, defaultLocation.Latitude, defaultLocation.Longitude);
                //					PokewatchLogger.Log("[+]Sucessfully logged in to PokemonGo using Google.", GetAccountName(account));
                //					return pogoSession;
                //				}
                //				catch
                //				{
                //					PokewatchLogger.Log("[-]Unable to log in using Google.", GetAccountName(account));
                //				}
            }
            return(null);
        }
예제 #3
0
        async Task ExecuteLogin()
        {
            MessengerInstance.Send(new Message("Logging in"));

            if (main.Settings.AuthType == AuthType.Google)
            {
                MessengerInstance.Send(new Message(Colors.Red, "Google Login is not supported at the moment."));
            }
            else
            {
                loginProvider = new PtcLoginProvider(main.Settings.Username, main.Settings.Password);
                session       = await POGOLib.Net.Authentication.Login.GetSession(loginProvider, main.Player.Position.Latitude, main.Player.Position.Longitude);

                IsLoggedIn = await session.Startup();

                main.Settings.UpdateWith(session.GlobalSettings);
                var templates = await DownloadItemTemplates();

                main.Settings.UpdateWith(templates);
                main.Player.UpdateWith(session.Player.Data);

                // update after the settings have been downloaded
                session.Map.Update += Map_Update;
                session.Player.Inventory.Update += Inventory_Update;
                Map_Update(null, null);
                Inventory_Update(null, null);
            }

            if (IsLoggedIn)
            {
                MessengerInstance.Send(new Message(Colors.Green, "Login successfull."));
            }
            else
            {
                MessengerInstance.Send(new Message(Colors.Red, "Login unsuccessfull."));
            }
        }
예제 #4
0
        private static void Run(IEnumerable <Account> accounts)
        {
            foreach (var account in accounts)
            {
                Task.Run(async() =>
                {
                    try
                    {
                        // Login
                        ILoginProvider loginProvider;

                        switch (account.LoginProvider)
                        {
                        case "google":
                            loginProvider = new GoogleLoginProvider(account.Username, account.Password);
                            break;

                        case "ptc":
                            loginProvider = new PtcLoginProvider(account.Username, account.Password);
                            break;

                        default:
                            throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
                        }

                        var locRandom = new Random();
                        var latitude  = 51.507352 + locRandom.NextDouble(-0.000030, 0.000030); // Somewhere in London
                        var longitude = -0.127758 + locRandom.NextDouble(-0.000030, 0.000030);
                        var session   = await GetSession(loginProvider, latitude, longitude, true);

                        SaveAccessToken(session.AccessToken);

                        session.AccessTokenUpdated += SessionOnAccessTokenUpdated;
                        session.InventoryUpdate    += InventoryOnUpdate;
                        session.MapUpdate          += MapOnUpdate;

                        // Send initial requests and start HeartbeatDispatcher.
                        // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
                        if (!await session.StartupAsync())
                        {
                            throw new Exception("Session couldn't start up.");
                        }

                        // Retrieve the closest fort to your current player coordinates.
                        var closestFort = session.Map.GetFortsSortedByDistance().FirstOrDefault();
                        if (closestFort != null)
                        {
                            for (var i = 0; i < 50; i++)
                            {
                                Task.Run(async() =>
                                {
                                    var request = new Request
                                    {
                                        RequestType    = RequestType.FortDetails,
                                        RequestMessage = new FortDetailsMessage
                                        {
                                            FortId    = closestFort.Id,
                                            Latitude  = closestFort.Latitude,
                                            Longitude = closestFort.Longitude
                                        }.ToByteString()
                                    };

                                    await session.RpcClient.GetRequestEnvelopeAsync(new[] { request }, true);
                                });
                            }
                        }
                        else
                        {
                            Logger.Info("No fort found nearby.");
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error($"Username '{account.Username}' had exception: {e.Message}");
                    }
                }, CancellationTokenSource.Token);
            }
        }
예제 #5
0
        public async Task <MethodResult <bool> > DoLogin(Manager manager)
        {
            SetSettings(manager);
            // TODO: see how do this only once better.
            if (!(Configuration.Hasher is PokeHashHasher))
            {
                // By default Configuration.Hasher is LegacyHasher type  (see Configuration.cs in the pogolib source code)
                // -> So this comparation only will run once.
                if (Settings.UseOnlyOneKey)
                {
                    Configuration.Hasher       = new PokeHashHasher(Settings.AuthAPIKey);
                    Configuration.HasherUrl    = Settings.HashHost;
                    Configuration.HashEndpoint = Settings.HashEndpoint;
                }
                else
                {
                    Configuration.Hasher = new PokeHashHasher(Settings.HashKeys.ToArray());
                }

                // TODO: make this configurable. To avoid bans (may be with a checkbox in hash keys tab).
                //Configuration.IgnoreHashVersion = true;
                VersionStr = Configuration.Hasher.PokemonVersion;
                //Revise sleeping line 118
                //((PokeHashHasher)Configuration.Hasher).PokehashSleeping += OnPokehashSleeping;
            }
            // *****

            ILoginProvider loginProvider;

            switch (Settings.AuthType)
            {
            case AuthType.Google:
                loginProvider = new GoogleLoginProvider(Settings.Username, Settings.Password);
                break;

            case AuthType.Ptc:
                loginProvider = new PtcLoginProvider(Settings.Username, Settings.Password, Proxy.AsWebProxy());
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            ClientSession = await GetSession(loginProvider, Settings.DefaultLatitude, Settings.DefaultLongitude, true);

            // Send initial requests and start HeartbeatDispatcher.
            // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
            string msgStr = null;

            if (!await ClientSession.StartupAsync())
            {
                msgStr   = "Session couldn't start up.";
                LoggedIn = false;
            }
            else
            {
                LoggedIn = true;
                msgStr   = "Successfully logged into server.";

                ClientSession.AccessTokenUpdated         += SessionOnAccessTokenUpdated;
                ClientSession.CaptchaReceived            += SessionOnCaptchaReceived;
                ClientSession.InventoryUpdate            += SessionInventoryUpdate;
                ClientSession.MapUpdate                  += MapUpdate;
                ClientSession.CheckAwardedBadgesReceived += OnCheckAwardedBadgesReceived;
                ClientSession.HatchedEggsReceived        += OnHatchedEggsReceived;

                SaveAccessToken(ClientSession.AccessToken);
            }

            return(new MethodResult <bool>()
            {
                Success = LoggedIn,
                Message = msgStr
            });
        }
예제 #6
0
        private static async Task Run(string[] args)
        {
            // Configure Logger
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(Directory.GetCurrentDirectory(), "nlog.config"));

            Logging.Logger.RegisterLogOutput((level, message) =>
            {
                switch (level)
                {
                case LogLevel.Debug:
                    Logger.Debug(message);
                    break;

                case LogLevel.Info:
                    Logger.Info(message);
                    break;

                case LogLevel.Notice:
                case LogLevel.Warn:
                    Logger.Warn(message);
                    break;

                case LogLevel.Error:
                    Logger.Error(message);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
            });

            // Initiate console
            Logger.Info("Booting up.");
            Logger.Info("Type 'q', 'quit' or 'exit' to exit.");
            Console.Title = "POGO Demo";

            // Configure hasher - DO THIS BEFORE ANYTHING ELSE!!
            //
            //  If you want to use the latest POGO version, you have
            //  to use the PokeHashHasher. For more information:
            //  https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer
            //
            //  You may also not use the PokeHashHasher, it will then use
            //  the built-in hasher which was made for POGO 0.45.0.
            //  Don't forget to use "Configuration.IgnoreHashVersion = true;" too.
            //
            //  Expect some captchas in that case..

            var pokeHashAuthKey = Environment.GetEnvironmentVariable("POKEHASH_AUTHKEY") ?? "";

            Configuration.Hasher = new PokeHashHasher(pokeHashAuthKey);
            // Configuration.IgnoreHashVersion = true;

            // Settings
            var loginProviderStr = "ptc";
            var usernameStr      = Environment.GetEnvironmentVariable("PTC_USERNAME") ?? ""; // Your PTC username
            var passwordStr      = Environment.GetEnvironmentVariable("PTC_PASSWORD") ?? ""; // Your PTC password

            // Login
            ILoginProvider loginProvider;

            switch (loginProviderStr)
            {
            case "google":
                loginProvider = new GoogleLoginProvider(usernameStr, passwordStr);
                break;

            case "ptc":
                loginProvider = new PtcLoginProvider(usernameStr, passwordStr);
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            var locRandom = new Random();
            var latitude  = 51.507352 + locRandom.NextDouble(-0.000030, 0.000030); // Somewhere in London
            var longitude = -0.127758 + locRandom.NextDouble(-0.000030, 0.000030);
            var session   = await GetSession(loginProvider, latitude, longitude, true);

            SaveAccessToken(session.AccessToken);

            session.AccessTokenUpdated += SessionOnAccessTokenUpdated;
            session.InventoryUpdate    += InventoryOnUpdate;
            session.MapUpdate          += MapOnUpdate;
            session.CaptchaReceived    += SessionOnCaptchaReceived;

            // Send initial requests and start HeartbeatDispatcher.
            // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
            if (!await session.StartupAsync())
            {
                throw new Exception("Session couldn't start up.");
            }

            // Retrieve the closest fort to your current player coordinates.
            var closestFort = session.Map.GetFortsSortedByDistance().FirstOrDefault();

            if (closestFort != null)
            {
                var fortDetailsBytes = await session.RpcClient.SendRemoteProcedureCallAsync(new Request
                {
                    RequestType    = RequestType.FortDetails,
                    RequestMessage = new FortDetailsMessage
                    {
                        FortId    = closestFort.Id,
                        Latitude  = closestFort.Latitude,
                        Longitude = closestFort.Longitude
                    }.ToByteString()
                });

                if (fortDetailsBytes != null)
                {
                    var fortDetailsResponse = FortDetailsResponse.Parser.ParseFrom(fortDetailsBytes);

                    Console.WriteLine(JsonConvert.SerializeObject(fortDetailsResponse, Formatting.Indented));
                }
                else
                {
                    Console.WriteLine("Couldn't print fort info, we probably had a captcha.");
                }
            }
            else
            {
                Logger.Info("No fort found nearby.");
            }

            // Handle quit commands.
            HandleCommands();
        }
예제 #7
0
        public async Task <MethodResult <bool> > DoLogin(Manager manager)
        {
            SetSettings(manager);
            // TODO: see how do this only once better.
            if (!(Configuration.Hasher is PokeHashHasher))
            {
                // By default Configuration.Hasher is LegacyHasher type  (see Configuration.cs in the pogolib source code)
                // -> So this comparation only will run once.
                if (ClientManager.UserSettings.UseOnlyOneKey)
                {
                    Configuration.Hasher       = new PokeHashHasher(ClientManager.UserSettings.AuthAPIKey);
                    Configuration.HasherUrl    = ClientManager.UserSettings.HashHost;
                    Configuration.HashEndpoint = ClientManager.UserSettings.HashEndpoint;
                }
                else
                {
                    Configuration.Hasher = new PokeHashHasher(ClientManager.UserSettings.HashKeys.ToArray());
                }

                // TODO: make this configurable. To avoid bans (may be with a checkbox in hash keys tab).
                //Configuration.IgnoreHashVersion = true;
                VersionStr = Configuration.Hasher.PokemonVersion;
                AppVersion = Configuration.Hasher.AppVersion;
                // TODO: Revise sleeping
                // Used on Windows phone background app
                //((PokeHashHasher)Configuration.Hasher).PokehashSleeping += OnPokehashSleeping;
            }
            // *****

            ILoginProvider loginProvider;

            switch (ClientManager.UserSettings.AuthType)
            {
            case AuthType.Google:
                loginProvider = new GoogleLoginProvider(ClientManager.UserSettings.Username, ClientManager.UserSettings.Password);
                break;

            case AuthType.Ptc:
                loginProvider = new PtcLoginProvider(ClientManager.UserSettings.Username, ClientManager.UserSettings.Password, Proxy.AsWebProxy());
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            ClientSession = await GetSession(loginProvider, ClientManager.UserSettings.Location.Latitude, ClientManager.UserSettings.Location.Longitude, true);

            // Send initial requests and start HeartbeatDispatcher.
            // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
            var msgStr = "Session couldn't start up.";

            LoggedIn = false;
            try
            {
                ClientSession.AssetDigestUpdated         += OnAssetDisgestReceived;
                ClientSession.ItemTemplatesUpdated       += OnItemTemplatesReceived;
                ClientSession.UrlsUpdated                += OnDownloadUrlsReceived;
                ClientSession.RemoteConfigVersionUpdated += OnLocalConfigVersionReceived;
                ClientSession.AccessTokenUpdated         += SessionAccessTokenUpdated;
                ClientSession.CaptchaReceived            += SessionOnCaptchaReceived;
                ClientSession.InventoryUpdate            += SessionInventoryUpdate;
                ClientSession.MapUpdate += SessionMapUpdate;
                ClientSession.CheckAwardedBadgesReceived += OnCheckAwardedBadgesReceived;
                ClientSession.HatchedEggsReceived        += OnHatchedEggsReceived;
                ClientSession.Logger.RegisterLogOutput(LoggerFucntion);

                if (await ClientSession.StartupAsync(ClientManager.UserSettings.DownloadResources))
                {
                    LoggedIn = true;
                    msgStr   = "Successfully logged into server.";

                    ClientManager.LogCaller(new LoggerEventArgs("Succefully added all events to the client.", LoggerTypes.Debug));

                    if (ClientSession.Player.Warn)
                    {
                        ClientManager.AccountState = AccountState.Flagged;
                        ClientManager.LogCaller(new LoggerEventArgs("The account is flagged.", LoggerTypes.Warning));

                        if (ClientManager.UserSettings.StopAtMinAccountState == AccountState.Flagged)
                        {
                            //Remove proxy
                            ClientManager.RemoveProxy();
                            ClientManager.Stop();

                            msgStr = "The account is flagged.";
                        }
                    }


                    //Closes bot on captcha received need utils for solve
                    if (ClientManager.AccountState == AccountState.CaptchaReceived)
                    {
                        ClientManager.LogCaller(new LoggerEventArgs("Captcha ceceived.", LoggerTypes.Warning));

                        //Remove proxy
                        ClientManager.RemoveProxy();

                        ClientManager.Stop();

                        msgStr = "Captcha ceceived.";
                    }

                    SaveAccessToken(ClientSession.AccessToken);
                }
                else
                {
                    if (ClientSession.Player.Banned)
                    {
                        ClientManager.AccountState = AccountState.PermanentBan;
                        ClientManager.LogCaller(new LoggerEventArgs("The account is banned.", LoggerTypes.FatalError));

                        //Remove proxy
                        ClientManager.RemoveProxy();

                        ClientManager.Stop();

                        msgStr = "The account is banned.";
                    }
                    if (ClientSession.State == SessionState.TemporalBanned)
                    {
                        ClientManager.AccountState = AccountState.TemporalBan;
                        ClientManager.LogCaller(new LoggerEventArgs("The account is temporal banned.", LoggerTypes.FatalError));

                        //Remove proxy
                        ClientManager.RemoveProxy();

                        ClientManager.Stop();

                        msgStr = "The account is temporal banned.";
                    }
                }
            }
            catch (PtcOfflineException)
            {
                ClientManager.Stop();

                ClientManager.LogCaller(new LoggerEventArgs("Ptc server offline. Please try again later.", LoggerTypes.Warning));

                msgStr = "Ptc server offline.";
            }
            catch (AccountNotVerifiedException)
            {
                ClientManager.Stop();
                ClientManager.RemoveProxy();

                ClientManager.LogCaller(new LoggerEventArgs("Account not verified. Stopping ...", LoggerTypes.Warning));

                ClientManager.AccountState = Enums.AccountState.NotVerified;

                msgStr = "Account not verified.";
            }
            catch (WebException ex)
            {
                ClientManager.Stop();

                if (ex.Status == WebExceptionStatus.Timeout)
                {
                    if (String.IsNullOrEmpty(ClientManager.Proxy))
                    {
                        ClientManager.LogCaller(new LoggerEventArgs("Login request has timed out.", LoggerTypes.Warning));
                    }
                    else
                    {
                        ClientManager._proxyIssue = true;
                        ClientManager.LogCaller(new LoggerEventArgs("Login request has timed out. Possible bad proxy.", LoggerTypes.ProxyIssue));
                    }

                    msgStr = "Request has timed out.";
                }

                if (!String.IsNullOrEmpty(ClientManager.Proxy))
                {
                    if (ex.Status == WebExceptionStatus.ConnectionClosed)
                    {
                        ClientManager._proxyIssue = true;
                        ClientManager.LogCaller(new LoggerEventArgs("Potential http proxy detected. Only https proxies will work.", LoggerTypes.ProxyIssue));

                        msgStr = "Http proxy detected";
                    }
                    else if (ex.Status == WebExceptionStatus.ConnectFailure || ex.Status == WebExceptionStatus.ProtocolError || ex.Status == WebExceptionStatus.ReceiveFailure ||
                             ex.Status == WebExceptionStatus.ServerProtocolViolation)
                    {
                        ClientManager._proxyIssue = true;
                        ClientManager.LogCaller(new LoggerEventArgs("Proxy is offline", LoggerTypes.ProxyIssue));

                        msgStr = "Proxy is offline";
                    }
                }

                ClientManager._proxyIssue |= !String.IsNullOrEmpty(ClientManager.Proxy);

                ClientManager.LogCaller(new LoggerEventArgs("Failed to login due to request error", LoggerTypes.Exception, ex.InnerException));

                msgStr = "Failed to login due to request error";
            }
            catch (TaskCanceledException)
            {
                ClientManager.Stop();

                if (String.IsNullOrEmpty(ClientManager.Proxy))
                {
                    ClientManager.LogCaller(new LoggerEventArgs("Login request has timed out", LoggerTypes.Warning));
                }
                else
                {
                    ClientManager._proxyIssue = true;
                    ClientManager.LogCaller(new LoggerEventArgs("Login request has timed out. Possible bad proxy", LoggerTypes.ProxyIssue));
                }

                msgStr = "Login request has timed out";
            }
            catch (InvalidCredentialsException ex)
            {
                //Puts stopping log before other log.
                ClientManager.Stop();
                ClientManager.RemoveProxy();

                ClientManager.LogCaller(new LoggerEventArgs("Invalid credentials or account lockout. Stopping bot...", LoggerTypes.Warning, ex));

                msgStr = "Username or password incorrect";
            }
            catch (IPBannedException)
            {
                if (ClientManager.UserSettings.StopOnIPBan)
                {
                    ClientManager.Stop();
                }

                string message = String.Empty;

                if (!String.IsNullOrEmpty(ClientManager.Proxy))
                {
                    if (ClientManager.CurrentProxy != null)
                    {
                        ClientManager.ProxyHandler.MarkProxy(ClientManager.CurrentProxy, true);
                    }

                    message = "Proxy IP is banned.";
                }
                else
                {
                    message = "IP address is banned.";
                }

                ClientManager._proxyIssue = true;

                ClientManager.LogCaller(new LoggerEventArgs(message, LoggerTypes.ProxyIssue));

                msgStr = message;
            }
            catch (GoogleLoginException ex)
            {
                ClientManager.Stop();
                ClientManager.RemoveProxy();

                ClientManager.LogCaller(new LoggerEventArgs(ex.Message, LoggerTypes.Warning));

                msgStr = "Failed to login";
            }
            catch (PokeHashException phe)
            {
                ClientManager.AccountState = AccountState.HashIssues;

                msgStr = "Hash issues";
                ClientManager.LogCaller(new LoggerEventArgs(phe.Message, LoggerTypes.FatalError, phe));
            }
            catch (Exception ex)
            {
                ClientManager.Stop();
                //RemoveProxy();

                ClientManager.LogCaller(new LoggerEventArgs("Failed to login", LoggerTypes.Exception, ex));

                msgStr = "Failed to login";
            }

            return(new MethodResult <bool>()
            {
                Success = LoggedIn,
                Message = msgStr
            });
        }
예제 #8
0
        private static async Task Run(string[] args)
        {
            // Configure Logger
            Logger.RegisterLogOutput((logLevel, message) => {
                if (logLevel < LoggerConfiguration.MinimumLogLevel)
                {
                    return;
                }

                var foregroundColor = LoggerConfiguration.DefaultForegroundColor;
                var backgroundColor = LoggerConfiguration.DefaultBackgroundColor;
                var timestamp       = DateTime.Now.ToString("HH:mm:ss");

                if (LoggerConfiguration.LogLevelColors.ContainsKey(logLevel))
                {
                    var colors = LoggerConfiguration.LogLevelColors[logLevel];

                    foregroundColor = colors.ForegroundColor;
                    backgroundColor = colors.BackgroundColor;
                }

                Console.ForegroundColor = foregroundColor;
                Console.BackgroundColor = backgroundColor;
                Console.WriteLine($"{timestamp,-10}{logLevel,-8}{message}");
                Console.ResetColor();
            });

            // Initiate console
            Logger.Info("Booting up.");
            Logger.Info("Type 'q', 'quit' or 'exit' to exit.");
            Console.Title = "POGO Demo";

            // Settings
            const string loginProviderStr = "ptc";
            const string usernameStr      = "";
            const string passwordStr      = "";

            // Login
            ILoginProvider loginProvider;

//            if (loginProviderStr == "google")
//                loginProvider = new GoogleLoginProvider(usernameStr, passwordStr);
//            else
            if (loginProviderStr == "ptc")
            {
                loginProvider = new PtcLoginProvider(usernameStr, passwordStr);
            }
            else
            {
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\"");
            }

            var locRandom = new Random();
            var latitude  = 51.507352 + locRandom.NextDouble(-0.000030, 0.000030); // Somewhere in London
            var longitude = -0.127758 + locRandom.NextDouble(-0.000030, 0.000030);
            var session   = await GetSession(loginProvider, latitude, longitude, true);

            SaveAccessToken(session.AccessToken);

//            session.DataCache = new FileDataCache();
            session.AccessTokenUpdated      += SessionOnAccessTokenUpdated;
            session.Player.Inventory.Update += InventoryOnUpdate;
            session.Map.Update += MapOnUpdate;

            // Send initial requests and start HeartbeatDispatcher
            await session.StartupAsync();

            var fortDetailsBytes = await session.RpcClient.SendRemoteProcedureCallAsync(new Request
            {
                RequestType    = RequestType.FortDetails,
                RequestMessage = new FortDetailsMessage
                {
                    FortId    = "e4a5b5a63cf34100bd620c598597f21c.12",
                    Latitude  = 51.507335,
                    Longitude = -0.127689
                }.ToByteString()
            });

            var fortDetailsResponse = FortDetailsResponse.Parser.ParseFrom(fortDetailsBytes);

            Console.WriteLine(JsonConvert.SerializeObject(fortDetailsResponse, Formatting.Indented));

            HandleCommands();
        }
예제 #9
0
        private static async Task Run()
        {
            if (cooldown > POGOLib.Official.Util.TimeUtil.GetCurrentTimestampInMilliseconds())
            {
                Console.WriteLine("======> cool down");
                return;
            }

            var pokeHashAuthKey = config.hashkey;

            Configuration.Hasher = new PokeHashHasher(pokeHashAuthKey);
            // Configuration.IgnoreHashVersion = true;

            // Settings
            var loginProviderStr = config.auth_service;
            var usernameStr      = config.username;
            var passwordStr      = config.password;

            // Login
            ILoginProvider loginProvider;

            switch (loginProviderStr)
            {
            case "google":
                loginProvider = new GoogleLoginProvider(usernameStr, passwordStr);
                break;

            case "ptc":
                loginProvider = new PtcLoginProvider(usernameStr, passwordStr);
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            var         locRandom = new Random();
            var         latitude  = pokemon.Latitude;
            var         longitude = pokemon.Longtitude;
            CultureInfo culture   = (CultureInfo)CultureInfo.CurrentCulture.Clone();

            culture.NumberFormat.NumberDecimalSeparator = ".";
            double start_latitude   = Convert.ToDouble(Regex.Split(config.startlocation, ",")[0], culture);
            double start_longtitude = Convert.ToDouble(Regex.Split(config.startlocation, ",")[1], culture);

            if (session == null)
            {
                //Console.WriteLine("==>Creating session/logging in. ");
                session = await GetSession(loginProvider, start_latitude, start_longtitude, true);

                SaveAccessToken(session.AccessToken);
                session.AccessTokenUpdated += SessionOnAccessTokenUpdated;
                //session.Player.Inventory.Update += InventoryOnUpdate;
                session.Map.Update += MapOnUpdate;
                Console.WriteLine("connecting to PokemonGo servers through hashing servers");
                // Send initial requests and start HeartbeatDispatcher.
                // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
                if (!await session.StartupAsync())
                {
                    throw new Exception("Session couldn't start up.");
                }
            }
            //Console.WriteLine("==>Teleporting to pokemon");
            session.Player.SetCoordinates(latitude, longitude);
            System.Threading.Thread.Sleep(3000);
            //var closestFort = session.Map.GetFortsSortedByDistance().FirstOrDefault();
            int i = 1;
            //do {
            //Console.Write(String.Format("\rPokemon {0} attemp {1} of {2}",pokemon.PokemonName, i.ToString(),config.tryforseconds.ToString()));
            await session.RpcClient.RefreshMapObjectsAsync();

            // Retrieve the closest fort to your current player coordinates.
            var closestFort = session.Map.GetFortsSortedByDistance().FirstOrDefault();

            if (closestFort != null)
            {
                //Console.Write(String.Format("\rPokemon {0} attemp {1} of {2}",pokemon.PokemonName, i.ToString(),config.tryforseconds.ToString()));
                cooldown = closestFort.CooldownCompleteTimestampMs;
                IEnumerable <POGOProtos.Map.Pokemon.MapPokemon> catchable = session.Map.Cells.SelectMany(c => c.CatchablePokemons);
                SearchForPokemon(catchable).GetAwaiter().GetResult();
                if (pokemon.EncounterId == 0)
                {
                    //int i=1;
                    do
                    {
                        //System.Threading.Thread.Sleep(5000);
                        Console.Write(String.Format("\rPokemon {0} attemp {1} of {2}", pokemon.PokemonName, i.ToString(), config.tryforseconds.ToString()));
                        await session.RpcClient.RefreshMapObjectsAsync();

                        catchable = session.Map.Cells.SelectMany(c => c.CatchablePokemons);
                        SearchForPokemon(catchable).GetAwaiter().GetResult();
                        i++;
                    } while    (i <= config.tryforseconds & (pokemon.EncounterId == 0));
                    //} while    (pokemon.EncounterId==0 );
                }
                //i++;
                //} while  (i<=config.tryforseconds & (pokemon.EncounterId==0) );
            }
            else
            // if (closestFort == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                Console.WriteLine("======> No Fort data found. Captcha soft/ip/hard ban? Check account, take a rest , etc. ");
                Console.ForegroundColor = ConsoleColor.White;
                //session.Player.SetCoordinates (start_latitude,start_longtitude);
                //session.Shutdown();
                //session.Dispose();
                //session = null;
            }
            //Console.WriteLine("Teleporting back to startup");
            session.Player.SetCoordinates(start_latitude, start_longtitude);
            System.Threading.Thread.Sleep(500);
            //session.Shutdown();
            //session.Dispose();

            // Handle quit commands.
            //HandleCommands();
        }
예제 #10
0
파일: Program.cs 프로젝트: xythos1/POGOLib
        private static async Task Run(string[] args)
        {
            // Configure Logger
            Logger.RegisterLogOutput((logLevel, message) => {
                if (logLevel < LoggerConfiguration.MinimumLogLevel)
                {
                    return;
                }

                var foregroundColor = LoggerConfiguration.DefaultForegroundColor;
                var backgroundColor = LoggerConfiguration.DefaultBackgroundColor;
                var timestamp       = DateTime.Now.ToString("HH:mm:ss");

                if (LoggerConfiguration.LogLevelColors.ContainsKey(logLevel))
                {
                    var colors = LoggerConfiguration.LogLevelColors[logLevel];

                    foregroundColor = colors.ForegroundColor;
                    backgroundColor = colors.BackgroundColor;
                }

                Console.ForegroundColor = foregroundColor;
                Console.BackgroundColor = backgroundColor;
                Console.WriteLine($"{timestamp,-10}{logLevel,-8}{message}");
                Console.ResetColor();
            });

            // Initiate console
            Logger.Info("Booting up.");
            Logger.Info("Type 'q', 'quit' or 'exit' to exit.");
            Console.Title = "POGO Demo";

            // Settings
            var loginProviderStr = "ptc";
            var usernameStr      = Environment.GetEnvironmentVariable("PTC_USERNAME") ?? ""; // Your PTC username
            var passwordStr      = Environment.GetEnvironmentVariable("PTC_PASSWORD") ?? ""; // Your PTC password

            // Login
            ILoginProvider loginProvider;

            switch (loginProviderStr)
            {
            case "google":
                loginProvider = new GoogleLoginProvider(usernameStr, passwordStr);
                break;

            case "ptc":
                loginProvider = new PtcLoginProvider(usernameStr, passwordStr);
                break;

            default:
                throw new ArgumentException("Login provider must be either \"google\" or \"ptc\".");
            }

            var locRandom = new Random();
            var latitude  = 51.507352 + locRandom.NextDouble(-0.000030, 0.000030); // Somewhere in London
            var longitude = -0.127758 + locRandom.NextDouble(-0.000030, 0.000030);
            var session   = await GetSession(loginProvider, latitude, longitude, true);

            SaveAccessToken(session.AccessToken);

            session.AccessTokenUpdated      += SessionOnAccessTokenUpdated;
            session.Player.Inventory.Update += InventoryOnUpdate;
            session.Map.Update += MapOnUpdate;

            // Send initial requests and start HeartbeatDispatcher.
            // This makes sure that the initial heartbeat request finishes and the "session.Map.Cells" contains stuff.
            if (!await session.StartupAsync())
            {
                throw new Exception("Session couldn't start up.");
            }

            // Retrieve the closest fort to your current player coordinates.
            var closestFort = session.Map.GetFortsSortedByDistance().FirstOrDefault();

            if (closestFort != null)
            {
                var fortDetailsBytes = await session.RpcClient.SendRemoteProcedureCallAsync(new Request
                {
                    RequestType    = RequestType.FortDetails,
                    RequestMessage = new FortDetailsMessage
                    {
                        FortId    = closestFort.Id,
                        Latitude  = closestFort.Latitude,
                        Longitude = closestFort.Longitude
                    }.ToByteString()
                });

                var fortDetailsResponse = FortDetailsResponse.Parser.ParseFrom(fortDetailsBytes);

                Console.WriteLine(JsonConvert.SerializeObject(fortDetailsResponse, Formatting.Indented));
            }
            else
            {
                Logger.Info("No fort found nearby.");
            }

            // Handle quit commands.
            HandleCommands();
        }