private async Task <ElectionResultsData> CombineAllSources(ResultsQuery resultsQuery)
        {
            var electionGetResult = _electionConfigurationSource.GetElectionById(resultsQuery.ElectionId);

            if (electionGetResult.IsFailure)
            {
                Log.LogWarning($"Could not retrieve election with id {resultsQuery.ElectionId} due to error {electionGetResult.Error}");
                return(ElectionResultsData.Default);
            }
            var availableSources = electionGetResult.Value.Files.Where(f => f.Active && f.FileType == FileType.Results).Select(f => f.Name).ToList();
            var data             = new ElectionResultsData();

            if (availableSources.Count == 0)
            {
                return(CreateEmptyElectionResultsData(resultsQuery, data));
            }
            foreach (var source in availableSources)
            {
                var resultsResponse =
                    await _resultsRepository.Get(resultsQuery.ElectionId, source, FileType.Results.ConvertEnumToString());

                if (resultsResponse.IsSuccess)
                {
                    var deserializedData =
                        JsonConvert.DeserializeObject <ElectionResultsData>(resultsResponse.Value.StatisticsJson);
                    data = StatisticsAggregator.CombineResults(data, deserializedData);
                }
            }

            if (data?.Candidates?.Count == 0)
            {
                return(CreateEmptyElectionResultsData(resultsQuery, data));
            }
            return(data);
        }
Esempio n. 2
0
        public BotWindowData(string name, GlobalSettings gs, StateMachine sm, Statistics st, StatisticsAggregator sa, WpfEventListener wel, ClientSettings cs, LogicSettings l)
        {
            ProfileName    = name;
            GlobalSettings = gs;
            Machine        = sm;
            Stats          = st;
            Aggregator     = sa;
            Listener       = wel;
            Settings       = cs;
            Logic          = l;
            Lat            = gs.LocationSettings.DefaultLatitude;
            Lng            = gs.LocationSettings.DefaultLongitude;

            Ts     = new TimeSpan();
            _timer = new DispatcherTimer {
                Interval = new TimeSpan(0, 0, 1)
            };
            _timer.Tick += delegate
            {
                Ts += new TimeSpan(0, 0, 1);
                _realWorkSec++;
            };
            _cts        = new CancellationTokenSource();
            _pauseCts   = new CancellationTokenSource();
            PlayerRoute = new GMapRoute(_routePoints);
            PathRoute   = new GMapRoute(new List <PointLatLng>());

            GlobalPlayerMarker = new GMapMarker(new PointLatLng(Lat, Lng))
            {
                Shape  = Properties.Resources.trainer.ToImage("Player - " + ProfileName),
                Offset = new Point(-14, -40),
                ZIndex = 15
            };
        }
        public void combine_candidate_votes_by_id()
        {
            var localResults    = new ElectionResultsData();
            var diasporaResults = new ElectionResultsData();

            localResults.Candidates = new List <CandidateConfig>
            {
                new CandidateConfig {
                    Id = "L1", Votes = 1
                },
                new CandidateConfig {
                    Id = "L2", Votes = 2
                },
            };
            diasporaResults.Candidates = new List <CandidateConfig>
            {
                new CandidateConfig {
                    Id = "L2", Votes = 5
                },
                new CandidateConfig {
                    Id = "L1", Votes = 10
                },
            };
            var combinedVotes = StatisticsAggregator.CombineResults(localResults, diasporaResults);

            combinedVotes.Candidates[0].Id.Should().Be("L1");
            combinedVotes.Candidates[0].Votes.Should().Be(11);
            combinedVotes.Candidates[1].Id.Should().Be("L2");
            combinedVotes.Candidates[1].Votes.Should().Be(7);
        }
Esempio n. 4
0
        private async Task <Result <ElectionResultsData> > GetResultsByType(ResultsType type, string location)
        {
            try
            {
                string resultsType          = type.ConvertEnumToString();
                var    localResultsResponse = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

                var diasporaResultsResponse = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

                if (localResultsResponse.IsFailure || diasporaResultsResponse.IsFailure)
                {
                    return(Result.Failure <ElectionResultsData>("Failed to retrieve data"));
                }
                var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResultsResponse.Value.StatisticsJson);
                var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResultsResponse.Value.StatisticsJson);
                var electionResultsData = StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData);

                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g1").Votes  = 3485292;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g2").Votes  = 527098;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g3").Votes  = 1384450;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g4").Votes  = 357014;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g5").Votes  = 2051725;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g6").Votes  = 32787;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g7").Votes  = 30884;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g8").Votes  = 30850;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g9").Votes  = 27769;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g10").Votes = 815201;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g11").Votes = 39192;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g12").Votes = 244275;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g13").Votes = 48662;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g14").Votes = 141316;
                _totalCounted = electionResultsData.Candidates.Sum(c => c.Votes);
                if (string.IsNullOrWhiteSpace(location) == false)
                {
                    if (location == "TOTAL")
                    {
                        return(Result.Ok(electionResultsData));
                    }
                    if (location == "DSPR")
                    {
                        return(Result.Ok(diasporaResultsData));
                    }
                    if (location == "RO")
                    {
                        return(Result.Ok(localResultsData));
                    }
                    foreach (var candidate in electionResultsData.Candidates)
                    {
                        candidate.Votes = candidate.Counties[location];
                    }
                }
                return(Result.Ok(electionResultsData));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to retrieve results for type {type} and location {location}");
                return(Result.Failure <ElectionResultsData>(e.Message));
            }
        }
Esempio n. 5
0
 public void OnBotStartedEventHandler(ISession session, StatisticsAggregator stat)
 {
     Dispatcher.Invoke(() =>
     {
         var main = MainWindow as MainClientWindow;
         main.OnBotStartedEventHandler(session, stat);
     });
 }
        public async Task <ElectionResultsData> GetResults(ResultsType type)
        {
            string resultsType = ConvertEnumToString(type);

            var localResults = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

            var diasporaResults = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

            var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResults.StatisticsJson);
            var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResults.StatisticsJson);

            return(StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData));
        }
        public async Task build_election_results_model_with_results_from_each_parser()
        {
            var csvParsers = new List <ICsvParser>
            {
                new FakeCandidatesParser(),
                new FakePollingStationsParser()
            };
            var statisticsAggregator = new StatisticsAggregator()
            {
                CsvParsers = csvParsers
            };

            var aggregationResult = await statisticsAggregator.RetrieveElectionData("", new ElectionResultsFile());

            aggregationResult.Value.Candidates.Should().NotBeNull();
        }
        public void OnBotStartedEventHandler(ISession session, StatisticsAggregator stat)
        {
            this.currentSession = session;

            session.EventDispatcher.EventReceived += HandleBotEvent;
            stat.GetCurrent().DirtyEvent += OnPlayerStatisticChanged;
            this.currentSession = session;
            this.botMap.Session = session;
            this.playerStats    = stat;
            this.ctrPokemonInventory.Session     = session;
            this.ctrlItemControl.Session         = session;
            this.ctrlSniper.Session              = session;
            this.ctrlEggsControl.Session         = session;
            this.datacontext.PokemonList.Session = session;
            botMap.SetDefaultPosition(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude);
        }
        private List <CandidateModel> ConvertCandidates(ElectionResultsData electionResultsData)
        {
            electionResultsData.Candidates = StatisticsAggregator.CalculatePercentagesForCandidates(
                electionResultsData.Candidates,
                electionResultsData.Candidates.Sum(c => c.Votes));
            var candidates = electionResultsData.Candidates.Select(c => new CandidateModel
            {
                Id         = c.Id,
                ImageUrl   = c.ImageUrl,
                Name       = c.Name,
                Percentage = c.Percentage,
                Votes      = c.Votes
            }).ToList();

            return(candidates);
        }
        public async Task apply_all_defined_aggregations()
        {
            var firstParser  = new FakeCandidatesParser();
            var secondParser = new FakeCandidatesParser();
            var csvParsers   = new List <ICsvParser>
            {
                firstParser,
                secondParser
            };
            var statisticsAggregator = new StatisticsAggregator {
                CsvParsers = csvParsers
            };
            await statisticsAggregator.RetrieveElectionData("");

            firstParser.WasInvoked.Should().BeTrue();
            secondParser.WasInvoked.Should().BeTrue();
        }
Esempio n. 11
0
        public void OnBotStartedEventHandler(ISession session, StatisticsAggregator stat)
        {
            currentSession = session;

            session.EventDispatcher.EventReceived += HandleBotEvent;
            stat.GetCurrent().DirtyEvent += OnPlayerStatisticChanged;
            currentSession = session;
            botMap.Session = session;
            playerStats    = stat;
            ctrPokemonInventory.Session     = session;
            ctrlItemControl.Session         = session;
            ctrlSniper.Session              = session;
            ctrlEggsControl.Session         = session;
            datacontext.PokemonList.Session = session;
            botMap.SetDefaultPosition(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude);
            var accountManager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            gridAccounts.ItemsSource = accountManager.Accounts;
        }
Esempio n. 12
0
        public void set_percentages_for_each_candidate(int c1Votes, decimal c1Percentage,
                                                       int c2Votes, decimal c2Percentage,
                                                       int c3Votes, decimal c3Percentage)
        {
            var candidatesResultsParser = new TestableCandidatesResultsParser(null)
            {
                ParsedCandidates = CreateListOfCandidatesWithVotes(c1Votes, c2Votes, c3Votes)
            };
            var electionResultsData = new ElectionResultsData {
                Candidates = CreateListOfCandidatesWithVotes(c1Votes, c2Votes, c3Votes)
            };
            var sumOfVotes = candidatesResultsParser.ParsedCandidates.Sum(c => c.Votes);

            StatisticsAggregator.CalculatePercentagesForCandidates(electionResultsData, sumOfVotes);

            electionResultsData.Candidates[0].Percentage.Should().Be(c1Percentage);
            electionResultsData.Candidates[1].Percentage.Should().Be(c2Percentage);
            electionResultsData.Candidates[2].Percentage.Should().Be(c3Percentage);
        }
Esempio n. 13
0
        private async Task <Result <ElectionResultsData> > GetResultsByType(ResultsType type, string location)
        {
            try
            {
                string resultsType          = type.ConvertEnumToString();
                var    localResultsResponse = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

                var diasporaResultsResponse = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

                if (localResultsResponse.IsFailure || diasporaResultsResponse.IsFailure)
                {
                    return(Result.Failure <ElectionResultsData>("Failed to retrieve data"));
                }
                var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResultsResponse.Value.StatisticsJson);
                var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResultsResponse.Value.StatisticsJson);
                var electionResultsData = StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData);
                if (string.IsNullOrWhiteSpace(location) == false)
                {
                    if (location == "TOTAL")
                    {
                        return(Result.Ok(electionResultsData));
                    }
                    if (location == "DSPR")
                    {
                        return(Result.Ok(diasporaResultsData));
                    }
                    if (location == "RO")
                    {
                        return(Result.Ok(localResultsData));
                    }
                    foreach (var candidate in electionResultsData.Candidates)
                    {
                        candidate.Votes = candidate.Counties[location];
                    }
                }
                return(Result.Ok(electionResultsData));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to retrieve results for type {type} and location {location}");
                return(Result.Failure <ElectionResultsData>(e.Message));
            }
        }
Esempio n. 14
0
        private async Task <ElectionResultsData> CombineAllSources(ResultsQuery resultsQuery)
        {
            var files            = _electionConfigurationSource.GetListOfFilesWithElectionResults();
            var availableSources = files.Where(f => f.Active && f.FileType == FileType.Results).Select(f => f.Name);
            var data             = new ElectionResultsData();

            foreach (var source in availableSources)
            {
                var resultsResponse =
                    await _resultsRepository.Get(resultsQuery.ElectionId, source, FileType.Results.ConvertEnumToString());

                if (resultsResponse.IsSuccess)
                {
                    var deserializedData =
                        JsonConvert.DeserializeObject <ElectionResultsData>(resultsResponse.Value.StatisticsJson);
                    data = StatisticsAggregator.CombineResults(data, deserializedData);
                }
            }
            return(data);
        }
Esempio n. 15
0
        public MainWindow()
        {
            InitializeComponent();

            //global settings
            GlobalCatchemSettings.Load();

            InitWindowsControlls();
            BotWindow = this;
            LogWorker();
            RpcWorker();
            InitBots();
            SettingsView.BotMapPage.SetSettingsPage(SettingsView.BotSettingsPage);
            SetVersionTag();

            SettingsView.BotMapPage.SetGlobalSettings(GlobalCatchemSettings);
            GlobalMapView.SetGlobalSettings(GlobalCatchemSettings);
            SettingsView.BotSettingsPage.SetGlobalSettings(GlobalCatchemSettings);
            RouteCreatorView.SetGlobalSettings(GlobalCatchemSettings);

            _listener             = new WpfEventListener();
            _statisticsAggregator = new StatisticsAggregator();
        }
Esempio n. 16
0
            public BotWindowData(string name, GlobalSettings gs, StateMachine sm, Statistics st, StatisticsAggregator sa, WpfEventListener wel, ClientSettings cs, LogicSettings l)
            {
                ProfileName    = name;
                Settings       = new ClientSettings(gs);
                Logic          = new LogicSettings(gs);
                GlobalSettings = gs;
                Machine        = sm;
                Stats          = st;
                Aggregator     = sa;
                Listener       = wel;
                Settings       = cs;
                Logic          = l;

                _ts    = new TimeSpan();
                _timer = new DispatcherTimer {
                    Interval = new TimeSpan(0, 0, 1)
                };
                _timer.Tick += delegate
                {
                    _ts            += new TimeSpan(0, 0, 1);
                    RunTime.Content = _ts.ToString();
                };
                _cts = new CancellationTokenSource();
            }
Esempio n. 17
0
        private static void Main(string[] args)
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            var    culture    = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.New), subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            Boolean        boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                if (!VersionCheckState.IsLatest())
                {
                    settings = GlobalSettings.Load(subPath, true);
                }
                else
                {
                    settings = GlobalSettings.Load(subPath);
                }
            }
            else
            {
                settings                         = new GlobalSettings();
                settings.ProfilePath             = profilePath;
                settings.ProfileConfigPath       = profileConfigPath;
                settings.GeneralConfigPath       = Path.Combine(Directory.GetCurrentDirectory(), "config");
                settings.TranslationLanguageCode = strCulture;

                boolNeedsSetup = true;
            }

            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation) && !settings.isGui)
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFile);
                }
                else
                {
                    GlobalSettings.Load(subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }
            ProgressBar.start("NecroBot is starting up", 10);

            session.Client.ApiFailure = new ApiFailureStrategy(session);
            ProgressBar.fill(20);

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.fill(30);
            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.fill(60);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            if (settings.UseWebsocket)
            {
                session.EventDispatcher.EventReceived += evt => new WebSocketInterface(settings.WebSocketPort, session).Listen(evt, session);
            }
            ProgressBar.fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.fill(80);

            Logger.SetLoggerContext(session);
            ProgressBar.fill(90);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;
            ProgressBar.fill(100);

            machine.AsyncStart(new VersionCheckState(), session);
            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }
            Console.Clear();

            QuitEvent.WaitOne();
        }
Esempio n. 18
0
        private void startUp()
        {
            setLogger();
            var settings = GlobalSettings.Load("");

            if (settings == null)
            {
                Logger.Write("This is your first start and the bot has generated the default config!", LogLevel.Warning);
                Logger.Write("We will now shutdown to let you configure the bot and then launch it again.", LogLevel.Warning);
                var x = MessageBox.Show("This is your first start and the bot has generated the default config!\nWe will now shutdown to let you configure the bot and then launch it again.", "Config created", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                if (x == DialogResult.OK)
                {
                    Environment.Exit(0);
                }
            }
            else
            {
                if (settings.ConsoleSettings == null)
                {
                    settings.ConsoleSettings = new ConsoleConfig();
                }
                settings.ConsoleSettings.TranslationLanguageCode = "en";
            }
            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            _session = session;
            session.Client.ApiFailure = new ApiFailureStrategy(session);

            var machine = new StateMachine();
            var stats   = new Statistics();

            stats.DirtyEvent += () =>
            {
                this.UIThread(delegate
                {
                    this.labelAccount.TextLine2       = stats.GetTemplatedStats("{0}", "");
                    this.labelRuntime.TextLine2       = stats.GetTemplatedStats("{1}", "");
                    this.labelXpH.TextLine2           = stats.GetTemplatedStats("{3:0.0}", "");
                    this.labelPH.TextLine2            = stats.GetTemplatedStats("{4:0.0}", "");
                    this.labelStardust.TextLine2      = stats.GetTemplatedStats("{5:n0}", "");
                    this.labelTransferred.TextLine2   = stats.GetTemplatedStats("{6}", "");
                    this.labelRecycledCount.TextLine2 = stats.GetTemplatedStats("{7}", "");

                    this.labelLevel.TextLine2     = stats.GetTemplatedStats("{2}", "{0}");
                    this.labelNextLevel.TextLine2 = stats.GetTemplatedStats("{2}", "{1}h {2}m");
                    this.labelXp.TextLine2        = stats.GetTemplatedStats("{2}", "{3:n0}/{4:n0}");
                    this.labelSpeed.TextLine2     = this._session.LogicSettings.WalkingSpeedInKilometerPerHour + "km/h";
                });
            };

            var aggregator = new StatisticsAggregator(stats);
            var listener   = new EventListener(this);

            session.EventDispatcher.EventReceived += (IEvent evt) => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += (IEvent evt) => aggregator.Listen(evt, session);
            machine.SetFailureState(new LoginState());
            Logger.SetLoggerContext(session);

            session.Navigation.UpdatePositionEvent += (lat, lng) => {
                session.EventDispatcher.Send(new UpdatePositionEvent {
                    Latitude = lat, Longitude = lng
                });
                this.UIThread(delegate
                {
                    this.labelLat.TextLine2  = lat.ToString("0.00000");
                    this.labelLong.TextLine2 = lng.ToString("0.00000");
                });
                this.setLocation(lng, lat);
            };

            var profilePath   = Path.Combine(Directory.GetCurrentDirectory());
            var workspaceFile = Path.Combine(profilePath, "workspace.xml");

            if (File.Exists(workspaceFile))
            {
                Logger.Write("Found a workspace.xml file, loading...");
                try
                {
                    workspaceDashboard.LoadLayoutFromFile(openFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    Logger.Write("Unable to load workspace.xml. " + ex.Message, LogLevel.Error);
                }
            }
            else
            {
                Logger.Write("There is no workspace.xml in your root directory to load.");
            }

            if (this.debugUI)
            {
                return;
            }

            machine.AsyncStart(new VersionCheckState(), session);
            string now      = DateTime.Now.ToString("yyyyMMddHHmm");
            string filename = $"http://rawgit.com/vandernorth/NecroBot.GUI/master/Map/getMap.html?date={now}lat={settings.LocationSettings.DefaultLatitude}&long={settings.LocationSettings.DefaultLongitude}&radius={settings.LocationSettings.MaxTravelDistanceInMeters}&version={this.version}";

            if (debugMap == true)
            {
                filename = Application.StartupPath + $"\\Map\\getMap.html?lat={settings.LocationSettings.DefaultLatitude}&long={settings.LocationSettings.DefaultLongitude}&radius={settings.LocationSettings.MaxTravelDistanceInMeters}";
            }
            this.webMap.ScriptErrorsSuppressed = !debugMap;
            this.webMap.Url = new Uri(filename);

            if (settings.TelegramSettings.UseTelegramAPI)
            {
                session.Telegram = new Logic.Service.TelegramService(settings.TelegramSettings.TelegramAPIKey, session);
            }

            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
                this.snipeStarted = true;
            }

            settings.checkProxy(session.Translation);
        }
Esempio n. 19
0
        private void InitializeBot()
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            _logger = new ConsoleLogger(LogLevel.LevelUp);
            Logger.SetLogger(_logger, subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var authFile          = Path.Combine(profileConfigPath, "auth.json");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            BoolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                /** if (!VersionCheckState.IsLatest())
                 *  settings = GlobalSettings.Load(subPath, true);
                 * else **/
                _settings = GlobalSettings.Load(subPath, true);
                _settings.Auth.Load(authFile);
            }
            else
            {
                _settings = new GlobalSettings
                {
                    ProfilePath             = profilePath,
                    ProfileConfigPath       = profileConfigPath,
                    GeneralConfigPath       = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    TranslationLanguageCode = strCulture
                };
                BoolNeedsSetup = true;
            }

            _session = new Session(new ClientSettings(_settings), new LogicSettings(_settings));

            _session.Client.ApiFailure = new ApiFailureStrategy(_session);

            _machine = new StateMachine();
            var stats = new Statistics();

            // var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(3); NOT USED ATM

            //Status bar
            stats.DirtyEvent +=
                () =>
                SetStatusText(stats.GetTemplatedStats(
                                  _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                                  _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString)));

            var aggregator = new StatisticsAggregator(stats);
            var listener   = new ConsoleEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);

            if (_settings.UseWebsocket)
            {
                var websocket = new WebSocketInterface(_settings.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var plugins = new PluginManager(new PluginInitializerInfo
            {
                Logger     = _logger,
                Session    = _session,
                Settings   = _settings,
                Statistics = stats
            });

            plugins.InitPlugins();
            _machine.SetFailureState(new LoginState());
            Logger.SetLoggerContext(_session);

            _session.Navigation.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;

            RouteOptimizeUtil.RouteOptimizeEvent +=
                optimizedroute =>
                _session.EventDispatcher.Send(new OptimizeRouteEvent {
                OptimizedRoute = optimizedroute
            });
            RouteOptimizeUtil.RouteOptimizeEvent += InitializePokestopsAndRoute;

            Navigation.GetHumanizeRouteEvent +=
                (route, destination) =>
                _session.EventDispatcher.Send(new GetHumanizeRouteEvent {
                Route = route, Destination = destination
            });
            Navigation.GetHumanizeRouteEvent += UpdateMap;

            FarmPokestopsTask.LootPokestopEvent +=
                pokestop => _session.EventDispatcher.Send(new LootPokestopEvent {
                Pokestop = pokestop
            });
            FarmPokestopsTask.LootPokestopEvent += UpdateMap;

            CatchNearbyPokemonsTask.PokemonEncounterEvent +=
                mappokemons =>
                _session.EventDispatcher.Send(new PokemonsEncounterEvent {
                EncounterPokemons = mappokemons
            });
            CatchNearbyPokemonsTask.PokemonEncounterEvent += UpdateMap;

            CatchIncensePokemonsTask.PokemonEncounterEvent +=
                mappokemons =>
                _session.EventDispatcher.Send(new PokemonsEncounterEvent {
                EncounterPokemons = mappokemons
            });
            CatchIncensePokemonsTask.PokemonEncounterEvent += UpdateMap;
        }
Esempio n. 20
0
        private static void Main(string[] args)
        {
            var culture = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            var subPath = "";

            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.Info), subPath);

            var settings = GlobalSettings.Load(subPath);


            if (settings == null)
            {
                Logger.Write("This is your first start and the bot has generated the default config!", LogLevel.Warning);
                Logger.Write("We will now shutdown to let you configure the bot and then launch it again.",
                             LogLevel.Warning);
                Thread.Sleep(2000);
                Environment.Exit(0);
            }
            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            session.Client.ApiFailure = new ApiFailureStrategy(session);


            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            stats.DirtyEvent +=
                () =>
                Console.Title =
                    stats.GetTemplatedStats(
                        session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                        session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));

            var aggregator = new StatisticsAggregator(stats);
            var listener   = new ConsoleEventListener();
            var websocket  = new WebSocketInterface(settings.WebSocketPort, session);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);

            machine.SetFailureState(new LoginState());

            Logger.SetLoggerContext(session);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });

            machine.AsyncStart(new VersionCheckState(), session);
            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            //Non-blocking key reader
            //This will allow to process console key presses in another code parts
            while (true)
            {
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)
                {
                    break;
                }
                Thread.Sleep(5);
            }
        }
Esempio n. 21
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    //_ignoreKillSwitch = false;
                    break;

                case "false":
                    //_ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            //Only check killswitch if use legacyAPI
            //if (settings.Auth.APIConfig.UseLegacyAPI  && (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch()))
            //    return;

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You select pogodev API but not provide API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key call be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    //TODO - test api call to valida auth key
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 second, You are running bot with  Legacy API (0.45) it will increase your risk to be banned and trigger captcha. Config captcha in config.json to auto resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method is selected, please correct your auth.json, ",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(
                new ClientSettings(settings, elevationService), logicSettings, elevationService,
                translation
                );
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            if (onBotStarted != null)
            {
                onBotStarted(_session, aggregator);
            }

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot &&
                _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START. AUTO START AFTER 30 SEC");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    int day  = (int)item.RuntimeTotal / 1440;
                    int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                    int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);

                    var runtime = $"{day:00}:{hour:00}:{min:00}:00";

                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername} \t\t{runtime}");
                    index++;
                }

                char     select       = ' ';
                DateTime timeoutvalue = DateTime.Now.AddSeconds(30);

                while (DateTime.Now < timeoutvalue && !availableOption.Contains(select))
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo cki = Console.ReadKey();
                        select = cki.KeyChar;
                        select = Char.ToUpper(select);
                        if (!availableOption.Contains(select))
                        {
                            Console.Out.WriteLine("Please select an account from list");
                        }
                    }
                    else
                    {
                        Thread.Sleep(100);
                    }
                }

                if (availableOption.Contains(select))
                {
                    var bot = _session.Accounts[select - 65];
                    _session.ReInitSessionWithNextBot(bot);
                }
                else
                {
                    var bot = _session.Accounts.OrderBy(p => p.RuntimeTotal).First();
                    _session.ReInitSessionWithNextBot(bot);
                }
            }

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token); // that need to keep data live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }


            QuitEvent.WaitOne();
        }
Esempio n. 22
0
        public void StartBot()
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            var    culture    = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture     = culture;
            Thread.CurrentThread.CurrentCulture         = culture;
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            PoGo.NecroBot.Logic.GlobalSettings Einstellungen = new PoGo.NecroBot.Logic.GlobalSettings();

            List <KeyValuePair <int, string> > PokemonTranslationStrings = Uebersetzer._PokemonNameToId;

            pokemonNameToId["missingno"] = "001";
            foreach (var pokemon in PokemonTranslationStrings)
            {
                string pomoName = pokemon.Key.ToString();
                string idC      = "";
                if (pomoName.Length == 1)
                {
                    idC = "00" + pomoName;
                }
                if (pomoName.Length == 2)
                {
                    idC = "0" + pomoName;
                }
                if (pomoName.Length == 3)
                {
                    idC = pomoName;
                }
                pokemonNameToId[pokemon.Value.ToString()] = idC;
            }

            if (File.Exists(configFile))
            {
                Einstellungen = GlobalSettings.Load(subPath);
            }
            else
            {
                return;
            }

            session = new Session(new ClientSettings(Einstellungen), new LogicSettings(Einstellungen));
            session.Client.ApiFailure = new ApiFailureStrategy(session);
            var stats = new Statistics();


            stats.DirtyEvent += () =>
            {
                isLoaded = true;
                this.GraphicalInterface.updateData(stats.getNickname().ToString(), stats.getLevel().ToString(), stats.getNeedXp(), stats.getTotalXp(), stats.getStardust().ToString(), Math.Round((stats.GetRuntime() * 60), 3).ToString());
            };

            var aggregator = new StatisticsAggregator(stats);
            var machine    = new StateMachine();

            session.EventDispatcher.EventReceived += evt => Informations.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);

            machine.SetFailureState(new LoginState());

            session.Navigation.UpdatePositionEvent += (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;
            machine.AsyncStart(new VersionCheckState(), session, subPath);
            pokemonDisplay = new getPokemonDisplayed(session);
            Einstellungen.checkProxy(session.Translation);
        }
Esempio n. 23
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            if (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write("Migrating existing json confix to excel config, please check the config.xlsm in your config folder");

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot && _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START.");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername}");
                    index++;
                }
                ;

                char select = ' ';
                do
                {
                    select = Console.ReadKey(true).KeyChar;
                    Console.WriteLine(select);
                    select = Char.ToUpper(select);
                }while (!availableOption.Contains(select));

                var bot = _session.Accounts[select - 65];

                _session.ResetSessionToWithNextBot(bot);
            }
            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe && _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session, _session.CancellationTokenSource.Token);// that need to keep data  live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            QuitEvent.WaitOne();
        }
Esempio n. 24
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You select pogodev API but not provide API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key call be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    //TODO - test api call to valida auth key
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 second, You are running bot with  Legacy API (0.45) it will increase your risk to be banned and trigger captcha. Config captcha in config.json to auto resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method is selected, please correct your auth.json, ",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(logicSettings.Bots);
            ioc.Register <MultiAccountManager>(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            if (onBotStarted != null)
            {
                onBotStarted(_session, aggregator);
            }

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            //TODO: temporary
            if (settings.Auth.APIConfig.UseLegacyAPI)
            {
                Logger.Write("The PoGoDev Community Has Updated The Hashing Service To Be Compatible With 0.57.4 So We Have Updated Our Code To Be Compliant. Unfortunately During This Update Niantic Has Also Attempted To Block The Legacy .45 Service Again So At The Moment Only Hashing Service Users Are Able To Login Successfully. Please Be Patient As Always We Will Attempt To Keep The Bot 100% Free But Please Realize We Have Already Done Quite A Few Workarounds To Keep .45 Alive For You Guys.  Even If We Are Able To Get Access Again To The .45 API Again It Is Over 3 Months Old So Is Going To Be More Detectable And Cause Captchas. Please Consider Upgrading To A Paid API Key To Avoid Captchas And You Will  Be Connecting Using Latest Version So Less Detectable So More Safe For You In The End.", LogLevel.Warning);
                Logger.Write("The bot will now close", LogLevel.Error);
                Console.ReadLine();
                Environment.Exit(0);
                return;
            }
            //

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                // jjskuld - Ignore CS4014 warning for now.
                #pragma warning disable 4014
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token); // that need to keep data live
                #pragma warning restore 4014
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Esempio n. 25
0
        private static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
            Console.Title           = "NecroBot starting";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            var culture = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;
            var subPath = "";

            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.Info), subPath);

            var settings = GlobalSettings.Load(subPath);

            if (settings == null)
            {
                Logger.Write("This is your first start and the bot has generated the default config!", LogLevel.Warning);
                Logger.Write("Press a Key to continue...",
                             LogLevel.Warning);
                Console.ReadKey();
                return;
            }
            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            session.Client.ApiFailure = new ApiFailureStrategy(session);

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            stats.DirtyEvent +=
                () =>
                Console.Title =
                    stats.GetTemplatedStats(
                        session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                        session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));

            var aggregator = new StatisticsAggregator(stats);
            var listener   = new ConsoleEventListener();
            var websocket  = new WebSocketInterface(settings.WebSocketPort, session);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);

            machine.SetFailureState(new LoginState());

            Logger.SetLoggerContext(session);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;
            machine.AsyncStart(new VersionCheckState(), session);
            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            QuitEvent.WaitOne();
        }
Esempio n. 26
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                _subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), _subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                var crds = args[1].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            _session = new Session(new ClientSettings(settings), logicSettings, translation);

            if (boolNeedsSetup)
            {
                Logger.SetLoggerContext(_session);
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            _session.Client.ApiFailure = new ApiFailureStrategy(_session);
            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            Logger.SetLoggerContext(_session);
            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;
            UseNearbyPokestopsTask.UpdateTimeStampsPokestop      += SaveTimeStampsPokestopToDisk;
            CatchPokemonTask.UpdateTimeStampsPokemon             += SaveTimeStampsPokemonToDisk;

            ProgressBar.Fill(100);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer || _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            settings.checkProxy(_session.Translation);

            QuitEvent.WaitOne();
        }
Esempio n. 27
0
        private static void Main(string[] args)
        {
            Console.CancelKeyPress += (sender, eArgs) => {
                _quitEvent.Set();
                eArgs.Cancel = true;
            };

            var culture = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            var subPath = "";

            if (args.Length > 0)
            {
                subPath = args[0];
            }

#if DEBUG
            LogLevel logLevel = LogLevel.Debug;
#else
            LogLevel logLevel = LogLevel.Info;
#endif
            Logger.SetLogger(new ConsoleLogger(logLevel), subPath);

            var settings = GlobalSettings.Load(subPath);


            if (settings == null)
            {
                Logger.Write("This is your first start and the bot has generated the default config!", LogLevel.Warning);
                Logger.Write("After pressing a key the config folder will open and this commandline will close", LogLevel.Warning);

                //pauses console until keyinput
                Console.ReadKey();

                // opens explorer with location "config"
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                {
                    FileName        = "config",
                    UseShellExecute = true,
                    Verb            = "open"
                });
                Environment.Exit(0);
            }
            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));
            session.Client.ApiFailure = new ApiFailureStrategy(session);


            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();
            stats.DirtyEvent +=
                () =>
                Console.Title =
                    stats.GetTemplatedStats(
                        session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                        session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));

            var aggregator = new StatisticsAggregator(stats);
            var listener   = new ConsoleEventListener();
            var websocket  = new WebSocketInterface(settings.WebSocketPort, session);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);

            machine.SetFailureState(new LoginState());

            Logger.SetLoggerContext(session);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });

#if DEBUG
            machine.AsyncStart(new LoginState(), session);
#else
            machine.AsyncStart(new VersionCheckState(), session);
#endif
            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            _quitEvent.WaitOne();
        }
Esempio n. 28
0
        private static void Main(string[] args)
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            Boolean        boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings                         = new GlobalSettings();
                settings.ProfilePath             = profilePath;
                settings.ProfileConfigPath       = profileConfigPath;
                settings.GeneralConfigPath       = Path.Combine(Directory.GetCurrentDirectory(), "config");
                settings.TranslationLanguageCode = strCulture;

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                string[] crds = args[1].Split(',');
                double   lat, lng;
                try
                {
                    lat = Double.Parse(crds[0]);
                    lng = Double.Parse(crds[1]);
                    settings.DefaultLatitude  = lat;
                    settings.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }


            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation) && !settings.isGui)
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFile);

                    if (!settings.isGui)
                    {
                        var fileName = Assembly.GetExecutingAssembly().Location;
                        System.Diagnostics.Process.Start(fileName);
                        Environment.Exit(0);
                    }
                }
                else
                {
                    GlobalSettings.Load(subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }
            ProgressBar.start("NecroBot is starting up", 10);

            session.Client.ApiFailure = new ApiFailureStrategy(session);
            ProgressBar.fill(20);

            //Initialize Encryption-Service
            NecroBot_Network_Logic.Encryption.InitializeEncryption();

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.fill(30);
            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.fill(60);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            if (settings.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebSocketPort, session);
                session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);
            }

            ProgressBar.fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.fill(80);

            Logger.SetLoggerContext(session);
            ProgressBar.fill(90);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;

            ProgressBar.fill(100);

            machine.AsyncStart(new VersionCheckState(), session);

            try
            {
                Console.Clear();
            }
            catch (IOException) { }

            if (settings.UseTelegramAPI)
            {
                session.Telegram = new Logic.Service.TelegramService(settings.TelegramAPIKey, session);
            }

            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            settings.checkProxy(session.Translation);

            QuitEvent.WaitOne();
        }
Esempio n. 29
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync($"https://pokehash.buddyauth.com/{_session.Client.ApiEndPoint}", null).Result;
                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault())).ToLocalTime();
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.Now;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expiration Date: {AuthTokenExpiration.Month}/{AuthTokenExpiration.Day}/{AuthTokenExpiration.Year} ({Expiration.Days} Days {Expiration.Hours} Hours {Expiration.Minutes} Minutes)";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method must be selected, please correct your auth.json.",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
            {
                GetPlayerResponse x    = _session.Client.Player.GetPlayer().Result;
                string            warn = x.Warn ? "*(Flagged)*-" : null;

                Console.Title = $"[Necrobot2 v{strVersion}] Team: {x.PlayerData.Team} - {warn}" +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            };
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            onBotStarted?.Invoke(_session, aggregator);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Esempio n. 30
0
 public StatisticsController(StatisticsAggregator statisticsAggregator)
 {
     _statisticsAggregator = statisticsAggregator;
 }